Skip to content

Instantly share code, notes, and snippets.

@Seluj78
Created November 17, 2026 06:37
Show Gist options
  • Select an option

  • Save Seluj78/8a4b6e020f2a0dee442c129f9fd3cc0a to your computer and use it in GitHub Desktop.

Select an option

Save Seluj78/8a4b6e020f2a0dee442c129f9fd3cc0a to your computer and use it in GitHub Desktop.
agent-of-empires performance audit, 2026-11-16: full findings

agent-of-empires performance audit (2026-11-16)

AI-generated. Read-only static analysis by Claude agents, each finding re-read by a second agent told to refute it. Audited commit: 240d68c68. File and line references are from that commit and may have moved. Finding ids (#N) are audit ids, not GitHub issue numbers. The tracking epic and its sub-issues describe the current state of each item.

Static analysis by 40 finder agents (32 planned areas + 8 gap follow-ups), each finding re-read by a skeptic agent told to refute it. No builds or benchmarks were run locally; CI numbers come from real gh run data.

  • Filed: 611. Refuted or already handled: 17. Kept but judged no real impact: 64.
  • Remaining: 14 high, 86 medium, 430 low.
  • Evidence: 319 proven by code, 12 measured, 199 plausible and need measurement.
  • Several agents report the same root cause from different angles. Section 1 groups those duplicates.

1. Root-cause clusters (high and medium findings, deduplicated)

A. Status tick forks tmux per session

Hooked agents (Claude, Codex, Gemini, Cursor) never skip capture, and each capture forks an extra list-panes. Cost scales with live session count, 2 to 4 forks per session per tick.

  • #0 [high/M] Hooked agents re-capture the pane every status tick even when the screen is unchanged (src/session/instance/status_update.rs:19-36)
  • #43 [medium/S] Hooked agents bypass the window_activity capture skip, so every status tick runs capture-pane (src/session/instance/status_update.rs:19)
  • #54 [medium/M] Hooked sessions capture the pane every tick: skip_capture is disabled whenever a hook file exists (src/session/instance/status_update.rs:19-36)
  • #14 [medium/S] Pane capture re-resolves the pane id with an extra tmux fork although PaneMetadata already has it (src/session/instance/status_update.rs:364)
  • #33 [medium/S] Every pane capture forks list-panes (and maybe has-session) before capture-pane (src/tmux/session.rs:833-852)
  • #45 [medium/S] Daemon status tick forks twice per captured session, and the extra fork is redundant (src/tmux/session.rs:822-851)
  • #55 [medium/S] Every pane capture forks an extra list-panes to resolve a pane id the batch metadata already has (src/tmux/session.rs:837-855)

B. Config re-read and re-parsed from disk on hot paths

resolve_config (TOML parse, merge, status-rule regex compile, global write locks) runs per TUI frame, per status tick and per publish. One resolved-config cache with file-watch invalidation fixes all of them.

  • #1 [high/S] Status bar resolves full profile config from disk on every frame (src/tui/home/render.rs:4572-4593)
  • #19 [medium/M] Every snapshot publish re-reads and re-parses config TOML several times per profile and per project (src/server/api/sessions/list.rs:42)
  • #24 [medium/M] Every status tick re-reads and re-parses all config files and recompiles status-rule regexes for every profile (src/server/reload.rs:318-325)
  • #41 [medium/M] Publish loop re-resolves config TOML and opens git repos synchronously on every publish (src/server/api/sessions/list.rs:41)
  • #57 [medium/M] project_sessions re-resolves config, git main-repo discovery and canonicalize on every call (src/server/api/sessions/list.rs:96-104)

C. Runtime publish rebuilds the full session projection

project_sessions runs 3 to 6 times per second on async workers under the instances read lock, with SQLite queries per structured session, mostly to find no change.

  • #3 [high/M] Runtime publish rebuilds the full session projection on every timer and wake, with SQLite and file I/O on the async runtime (src/server/runtime.rs:278-300)
  • #40 [medium/M] Publish loop runs per-session SQLite queries on the writer connection, on a tokio worker, under the instances read lock (src/server/runtime.rs:282-289)
  • #42 [medium/M] publish_loop rebuilds the full session projection every 2s (500ms with subscribers), on the async runtime (src/server/runtime.rs:786)
  • #56 [medium/M] project_sessions (full O(N) projection with config, git, and SQLite) runs 3 to 6 times per second, mostly to find no change (src/server/runtime.rs:278-345)
  • #58 [medium/M] SQLite queries and JSON decodes per structured session on every projection (src/server/api/sessions/list.rs:55-80)
  • #59 [medium/S] Status WebSocket runs a full runtime publish for every status change on every connection (src/server/session_status_ws.rs:204-212)
  • #61 [medium/L] Runtime WS sends the full N-session snapshot per revision, and the TUI rebuilds everything on its UI thread (src/server/runtime.rs:330-345)

D. sessions.json write echo and reload

Passive status writes fsync the whole file, and the daemon's own writes trigger full all-profile reloads in daemon and TUI.

  • #60 [medium/M] Passive status transitions rewrite and fsync the whole sessions.json, which echoes into full reloads in daemon and TUI (src/server/status_poll.rs:85-163)
  • #94 [medium/M] Every daemon-own sessions.json write echoes into a full all-profile reload (src/server/disk_watch.rs:63-69)
  • #95 [medium/S] Disk-watch reload bypasses ProfileSessionsCache and re-parses unchanged profiles (src/server/disk_watch.rs:285-291)

E. TUI structured view is O(transcript) per frame

Whole transcript re-parsed (markdown), re-wrapped and re-laid out on every draw, two draws per streamed chunk, plus an unconditional 120 ms redraw.

  • #2 [high/M] Structured view rebuilds the entire transcript (markdown, tool cards, wrap) on every frame (src/tui/structured_view/render.rs:730)
  • #4 [high/M] Structured view re-lays out the entire transcript on every draw (src/tui/structured_view/render.rs:730)
  • #7 [high/M] TUI redraws the whole app and rebuilds the full transcript twice per chunk (src/tui/app.rs:1233-1243)
  • #17 [medium/S] No coalescing of WS messages: two full redraws per streamed chunk (src/tui/structured_view/mod.rs:378-387)
  • #15 [medium/S] Mounted structured preview forces a full redraw every 120ms forever (src/tui/app.rs:1503-1512)
  • #16 [medium/S] Full-screen structured view redraws unconditionally every 120 ms while idle (src/tui/structured_view/mod.rs:44-46)
  • #18 [medium/M] Each tool card clones diffs and full output, JSON-parses args and runs a Myers diff per frame (src/tui/structured_view/render.rs:1874-1893)
  • #51 [medium/S] TUI upsert_transcript_row scans all rows for every appended chunk (src/tui/structured_view/reducer.rs:266-271)
  • #93 [medium/S] Structured view TUI blocks input and redraw during reconnect, then wakes every 200 ms forever after it gives up (src/tui/structured_view/mod.rs:386-397)

F. ACP streaming plane on the server

Full reduced_state serialized per chunk per connection, global instances write lock per chunk, one SQLite transaction per event, one transcript row per token chunk, replay from seq 0 on connect.

  • #20 [medium/M] acp_ws re-serializes the whole AcpState per event per connection (src/server/acp_ws.rs:233-262)
  • #44 [medium/M] Web ACP socket rebuilds and re-serializes full control state on every event, per connection (src/server/acp_ws.rs:222-263)
  • #47 [medium/M] Each WS connection re-serializes the whole control state on every event (src/server/acp_ws.rs:223-230)
  • #48 [medium/S] Server sends a full reduced_state snapshot on every chunk per WS connection although chunks do not change it (src/server/acp_ws.rs:228-235)
  • #21 [medium/L] acp_ws connect and lag recovery replay the whole event log from seq 0 (src/server/acp_ws.rs:356-409)
  • #46 [medium/M] WS connect and lag rebuild load a session's entire event history into one Vec (src/server/acp_ws.rs:346-372)
  • #22 [medium/S] ACP listener takes the global instances write lock for every streamed chunk (src/server/acp_events.rs:441-464)
  • #28 [medium/M] Event writer commits one SQLite transaction per event; no group commit (src/acp/supervisor/sink.rs:162)
  • #50 [medium/M] TranscriptModel creates one row per token chunk, inflating memory, snapshots and every downstream O(rows) loop (src/acp/transcript.rs:315-331)
  • #29 [medium/S] try_in_flight_turn json_extracts every BackgroundAgentProgress row in the session (src/acp/event_store/turns.rs:586-628)
  • #30 [medium/S] TranscriptModel finds tool start rows and id rows with linear scans over all rows (src/acp/transcript.rs:936-941)
  • #31 [medium/S] upsert_transcript_row and patch_transcript_row search from the front, making snapshot merges quadratic (src/acp/transcript.rs:1030-1055)
  • #32 [medium/M] search_content scans the whole events table; SEARCH_ROW_SCAN_CAP does not bound the scan (src/acp/event_store/search.rs:16)
  • #25 [medium/M] Startup serially replays every structured session's full event log before the daemon is ready (src/server/acp_events.rs:724-742)

G. Web structured view per-chunk cost

Full transcript JSON.stringify to localStorage on every state change, all message objects rebuilt per chunk, three renders per chunk with no frame batching, Shiki re-highlight per chunk.

  • #5 [high/S] Browser persists the full ACP state, including the whole transcript, to localStorage on every state change (web/src/hooks/useAcpSession.ts:236-239)
  • #6 [high/S] Web persists the whole AcpState (full transcript) to localStorage on every state change (web/src/hooks/useAcpSession.ts:237-239)
  • #12 [high/S] Every ACP state change JSON.stringifies the whole transcript into localStorage (web/src/hooks/useAcpSession.ts:237-239)
  • #11 [high/M] activityToThreadMessages rebuilds every message object on every activity change, defeating assistant-ui's converter cache (web/src/components/acp/AcpRuntime.tsx:193-203)
  • #52 [medium/M] Web rebuilds every assistant message in the window per chunk, and the window grows with each chunk (web/src/components/acp/AcpRuntime.tsx:171-205)
  • #81 [medium/M] Every WS event renders the whole AcpRuntime tree synchronously; no coalescing of streaming chunks (web/src/components/acp/AcpRuntime.tsx:160-203)
  • #49 [medium/M] Each chunk yields three WS messages and three separate React dispatches/renders with no frame coalescing (web/src/hooks/acpSession/useAcpConnection.ts:281-330)
  • #86 [medium/M] ACP WebSocket dispatches one React render per message, no frame batching (web/src/hooks/acpSession/useAcpConnection.ts:400-408)
  • #82 [medium/M] Tool cards re-parse args_preview 5 to 10 times per render with no memo boundary (web/src/components/acp/ThreadMessages.tsx:215-279)
  • #83 [medium/S] EditToolCard recomputes diffPair for every top-level edit card each render because tool.diffs identity changes (web/src/components/acp/CoreToolCards.tsx:174-184)
  • #84 [medium/M] Running subagent payload re-serialized and re-parsed whole on every chunk (quadratic in child count) (web/src/components/acp/activityMessages.ts:309-324)
  • #85 [medium/S] Shiki re-highlights the whole growing code block on every chunk, synchronously, with no cache (web/src/components/acp/Markdown.tsx:166-198)

H. Web sidebar re-renders every row every 3 s

Session poll and plugin UI poll replace every object even on unchanged data, and SessionRow memo is defeated.

  • #62 [medium/S] Web sessions poll replaces every row object every 3s, even on unchanged 304 responses (web/src/hooks/useSessions.ts:96-157)
  • #87 [medium/M] Session list poll replaces every row object every 3s, re-rendering the whole sidebar (web/src/hooks/useSessions.ts:12)
  • #88 [medium/M] Every 3s poll re-renders all sidebar rows; SessionRow memo is defeated twice (web/src/hooks/useSessions.ts:98-153)
  • #63 [medium/M] Sidebar row memoization defeated: every status push re-renders all N rows (web/src/components/WorkspaceSidebar.tsx:231-270)
  • #99 [medium/S] Plugin UI poll hands React fresh entries/revisions every 3s, re-rendering all of AppContent (web/src/hooks/usePluginUiState.ts:71)

I. Web bundle and asset serving

10.7 MB IIFE diff worker times 4, 2.4 MB entry served uncompressed, heavy views bundled eagerly.

  • #10 [high/S] Diff worker bundled as IIFE inlines every Shiki grammar: 10.7 MB worker, spawned 4 times (web/vite.config.ts:36-56)
  • #79 [medium/S] Embedded dashboard JS/CSS is served uncompressed (2.4 MB entry instead of ~530 KB brotli) (src/server/router.rs:588-603)
  • #26 [medium/S] Assets from the embedded web bundle are served uncompressed and copied on every request (src/server/assets.rs:62-115)
  • #80 [medium/M] Main entry eagerly bundles diff viewer, ACP markdown, tool cards, settings, wizards; StructuredView lazy split is largely defeated (web/src/App.tsx:156-205)

J. Live terminal

Scrollback reading falls off the VT grid onto capture-pane polling; snapshot transport forks tmux twice per 50 ms while idle.

  • #8 [high/S] Scrolling back in any long session falls off the VT grid onto 2-fork capture-pane polling of up to 4000 lines (src/server/live_ws.rs:445)
  • #23 [medium/M] Snapshot live view forks tmux twice every 50ms per viewer, even when the pane is idle (src/server/live_ws.rs:1209-1228)
  • #53 [medium/M] Snapshot transport (paired shells, pipe_owned fallback) forks tmux twice every 50ms even when the pane is idle (src/server/live_ws.rs:128)

K. CI

Main-branch macOS runs cancelled before finishing, push re-tests the SHA the merge queue tested, kache prefetch hit rate 0%, no path filtering.

  • #9 [high/S] cancel-in-progress on main pushes kills the only macOS run before it finishes (.github/workflows/tests.yml:12-14)
  • #71 [medium/M] Push to main re-runs the full Tests+CI pipeline on the exact SHA the merge queue already tested (.github/workflows/tests.yml:3-14)
  • #73 [medium/M] kache gives almost no net benefit: prefetch hit rate is 0% and hit overhead equals the compile time it saves (.github/actions/kache/action.yml:41-49)
  • #72 [medium/M] macOS job compiles serially on a 3-core runner, making macOS-gated PRs take 23-54 min (.github/workflows/tests.yml:338-388)
  • #75 [medium/M] No PR-level path filtering: docs-only and web-only PRs run every Rust job, and Rust-only PRs run web suites (.github/workflows/tests.yml:29-34)
  • #74 [medium/S] playwright-live runs npm ci serially before cargo, though build.rs would overlap it with the dependency compile (.github/workflows/tests.yml:621-623)
  • #76 [medium/S] Cachix push rebuilds the full LTO Nix package on every main push, with no concurrency cancel (.github/workflows/cachix-push.yml:12-54)
  • #77 [medium/M] Docker sandbox images build arm64 under QEMU and likely never hit the GHA layer cache (45 min) (.github/workflows/docker.yml:27-28)

L. Rust build

657k-line root crate, dev-dependency feature unification splits build and test artifacts, build.rs invalidates the package on every commit.

  • #64 [medium/L] Monolithic 657k-line root crate; TUI is a cheap first crate seam (Cargo.toml:1-2)
  • #65 [medium/M] Dev-dependencies add features to normal deps, so cargo build and cargo test share almost no artifacts (Cargo.toml:242)
  • #66 [medium/M] build.rs watches .git/HEAD and logs/HEAD, so every commit or checkout recompiles the whole package (build.rs:26-53)
  • #67 [medium/S] With web, any web/src edit reruns npm build and recompiles the lib; xtask dev --watch rebuilds the frontend it never serves (build.rs:126-172)

M. Tests

About 2,400 lib tests serialized under cargo test, web-e2e leg compiles the full lib test binary for 7 tests, jsdom boot per file.

  • #68 [medium/M] Local cargo test serializes about 2,400 lib tests behind #[serial] plus a global ENV_LOCK (AGENTS.md:31-40)
  • #69 [medium/M] web-e2e leg compiles the full lib test binary and integration binary to run about 7 filtered tests (.github/workflows/tests.yml:112-130)
  • #70 [medium/M] jsdom boots in ~300 test files under default isolation (web/vite.config.ts:47-70)

N. Operation latency (create, send, stop, CLI)

Fixed sleeps and redundant subprocesses on user-visible operations.

  • #13 [high/S] Sandbox stop always waits Docker's 10s grace: PID 1 is sleep infinity with no init (src/containers/runtime_base.rs:596-598)
  • #34 [medium/S] wait_until_ready sleeps 200ms before the first check, adding 200-400ms to every send (src/tmux/session.rs:855-882)
  • #36 [medium/S] Served-read output (aoe list/ps/status) waits on a GitHub update check before printing (src/cli/runtime_read/mod.rs:285-309)
  • #37 [medium/S] aoe ps spawns two tmux subprocesses per session for pane pid despite batched metadata (src/cli/ps.rs:507-575)
  • #38 [medium/M] Sandbox start/reuse issues 6 to 9 separate docker inspect subprocesses for one container (src/session/instance/container.rs:533)
  • #91 [medium/M] ACP teardown liveness probe spawns ps -A (macOS) or scans /proc (Linux) on async workers every 50ms, under global mutexes (src/acp/supervisor/teardown.rs:1394-1403)
  • #92 [medium/S] Plugin worker reap sleeps a fixed 2s, which delays every daemon shutdown and restart (src/process/worker.rs:239-243)
  • #90 [medium/S] Structured create runs before_session host hooks twice (src/server/session_spawn.rs:778)
  • #27 [medium/M] terminal/create runs the whole command inside the SDK dispatch loop while holding the ingress fence (src/acp/acp_client/connection/mod.rs:106-131)

O. Git and diff

Full-repo libgit2 scans and Myers diff on the TUI thread; web diff remounts on any list change.

  • #39 [medium/M] TUI compute_file_diff runs the similar Myers diff synchronously on the UI thread (src/git/diff.rs:308)
  • #96 [medium/M] Changed-file scan uses libgit2 (no fsmonitor, untracked cache or sparse index) over the whole worktree (src/git/diff.rs:86-96)
  • #97 [medium/M] TUI diff open and refresh run full repo scans on the UI thread (src/tui/home/input.rs:4254-4262)
  • #89 [medium/M] Any diff-list change remounts and refetches the open file, resetting scroll (web/src/hooks/useDiffFiles.ts:38-50)

P. Fleet footprint

macOS metrics sample forks 8 processes per tick; each runner owns its own file watcher.

  • #35 [medium/M] macOS metrics sample forks about 8 processes per tick (src/process/macos.rs:1104-1121 (sample_memory))
  • #98 [medium/S] Each runner owns its own file-watch service (inotify instance + 3 threads) to watch one file, and sees every process's log writes (src/process/runner/mod.rs:154)

Unclustered high/medium

  • #78 [medium/S] Website hero serves a 1.9 MB GIF as the high-priority LCP image; GIFs total 4.4 MB in the checkout (website/src/pages/index.astro:111-120)

2. High impact, full detail

#0 Hooked agents re-capture the pane every status tick even when the screen is unchanged

  • Impact high, effort M, verdict confirmed, evidence proven-by-code, area session-instance, category cpu
  • Where: src/session/instance/status_update.rs:19-36, src/session/instance/status_update.rs:308-312, src/session/instance/status_update.rs:485-531, src/server/status_poll.rs:461-471
  • Frequency: Per session per daemon status tick: 500ms with a web/TUI subscriber, 2s otherwise. Scales with the number of live sessions whose agent writes a hook status file (claude, codex, gemini, cursor, ...), and that file persists for the life of the session.
  • Problem: skip_capture refuses to reuse the last verdict whenever has_hook is true. For hooked agents the hook file always exists, so every idle session forks tmux capture-pane (plus list-panes, see next finding), strips ANSI and re-runs the detector every tick. 20 idle Claude sessions with the dashboard open cost about 40 to 80 tmux forks per second.
  • Fix: Keep the last ANSI-stripped capture on Instance as a runtime field next to detection (for example last_clean_capture: Option<Arc<str>>) and carry it in merge_runtime_from_reload/inherit_runtime. In update_status_from_manifest, when activity is unchanged and nothing is pending, run plan.detect(&cached, &observation) with the fresh hook observation and skip the capture. This keeps the documented hook-write rationale and drops the fork.
  • Verifier: skip_capture has !has_hook (status_update.rs:33). The doc comment from faab441c5 gives the reason: a hook write changes the verdict with no redraw. The proposed fix keeps that rule. Cache the raw capture, not only the clean text, because resolve_detected_status and summarize_error_from_pane read the raw pane_content.
  • Measure: Run 20 idle Claude sessions with the dashboard open. Count tmux execs per second for 30s with sudo dtrace -n 'proc:::exec-success /execname=="tmux"/{@=count()}'.

#1 Status bar resolves full profile config from disk on every frame

  • Impact high, effort S, verdict confirmed, evidence proven-by-code, area tui-loop-home, category render
  • Where: src/tui/home/render.rs:4572-4593, src/tui/home/projects.rs:94-106, src/tui/home/projects.rs:142-147, src/tui/home/input.rs:7350-7365, src/tui/home/config_refresh.rs:31-35, src/session/config/profile_config.rs:183-196
  • Frequency: Every draw while the cursor is on a non-structured session row with the shortcut bar shown (default): every keypress, every 120ms spinner redraw, every 33ms tick in live-send; also per frame while help is open
  • Problem: render_status_bar calls default_attach_mode, which calls resolve_session_config_for, then resolve_config_or_warn. That reads and TOML-parses global config.toml and the profile config.toml, merges them, and runs status_rules::install_from_config. install_from_config takes global write locks and recompiles any custom status_rules regexes. All of this runs on the paint thread up to 30 times per second.
  • Fix: Cache the resolved SessionConfig per profile on HomeView (HashMap<String, SessionConfig>). Fill it in apply_config_to_state and try_refresh_from_config_watcher, and clear it when config_watch.dirty fires. Make resolve_session_config_for read the cache. Never call resolve_config from render_status_bar, live_key, or help_live_on_enter.
  • Verifier: render_status_bar (render.rs:4588) calls default_attach_mode -> resolve_session_config_for -> resolve_config_or_warn, which runs Config::load (config.toml plus state.toml), load_profile_config, a JSON round-trip merge_configs, and install_from_config (write locks, regex compile). No cache exists. Runs per draw, including 8 Hz spinner frames. The fix must also invalidate the cache on profile config watch events.
  • Measure: Wrap resolve_config with a tracing span or counter and log calls per second while a Running session is selected with the shortcut bar visible.

#2 Structured view rebuilds the entire transcript (markdown, tool cards, wrap) on every frame

  • Impact high, effort M, verdict confirmed, evidence proven-by-code, area tui-views, category cpu
  • Where: src/tui/structured_view/render.rs:730, src/tui/structured_view/render.rs:886-903, src/tui/structured_view/render.rs:1514-1519, src/tui/structured_view/render.rs:1524-1690, src/tui/structured_view/render.rs:1231, src/tui/structured_view/embedded.rs:567-580, src/tui/structured_view/mod.rs:1956-1969, src/tui/structured_view/embedded.rs:42-48
  • Frequency: Every redraw: 8.3 Hz idle tick, every WS message, keystroke, hover, wheel; embedded preview on every home draw (120 ms spinner tick, per embedded event)
  • Problem: render_transcript calls wrapped_transcript, which re-concatenates every message group's chunk rows, re-parses each with pulldown-cmark, rebuilds every tool card, then grapheme-wraps all lines; context_primer_pending also scans all rows twice. Cost is O(transcript length) per frame and grows for hours. RetainedView already caches this (RetainedTextCache) but the live view does not.
  • Fix: Add a transcript cache on StructuredViewState (RefCell) keyed by (rows_revision, width, theme, path_roots, subagents) mirroring RetainedTextCache; bump rows_revision in merge_server_rows/apply_transcript_delta/drop_rows. Better: cache wrapped lines per group id so a streaming delta re-renders only the tail group. Paint only the visible slice like components/preview.rs render_scrolled_output.
  • Verifier: render.rs:730 calls wrapped_transcript every frame; transcript_lines (1524+) re-concatenates group chunks, re-runs markdown::render, rebuilds tool cards, then wraps all lines. Only RetainedView has RetainedTextCache (embedded.rs:43). Live embedded preview also rebuilds per home draw (embedded.rs:578) and selection_text. context_primer_pending scans rows twice per frame.
  • Measure: Wrap wrapped_transcript in a tracing span with elapsed micros; attach to a multi-hour session and log p50/p99 per frame vs row count.

#3 Runtime publish rebuilds the full session projection on every timer and wake, with SQLite and file I/O on the async runtime

  • Impact high, effort M, verdict confirmed, evidence proven-by-code, area server-state, category cpu
  • Where: src/server/runtime.rs:278-300, src/server/runtime.rs:320-327, src/server/runtime.rs:785-801, src/server/api/sessions/list.rs:40-131, src/server/status_poll.rs:612-627
  • Frequency: publish_loop: every 500ms with subscribers, 2s otherwise, plus every request_publish wake. Also an explicit publish after each status tick, per mutation response, and per /runtime GET. Scales with session count.
  • Problem: publish() calls project_sessions before the change check. While holding instances.read and the publication read lock on an async worker, it does the following: reads ~/.claude/settings.json, runs 3 synchronous SQLite queries per live structured session (latest_plan, pending_wakeup, active_monitor), resolves resume configs, and then deep-compares the whole snapshot. Each status tick projects twice (wake plus explicit publish). Any change re-serializes and resends every session.
  • Fix: Keep a dirty generation that mutation_epoch, status changes, and event-store appends bump, and skip project_sessions when it has not moved. Run project_sessions in spawn_blocking. Cache read_tui_fullscreen by file mtime. Cache the per-session SQLite overlays keyed by the session's last event seq. Remove the explicit publish in status_poll_loop, since request_publish already wakes the loop.
  • Verifier: Understated. On every publish, project_sessions (list.rs:40) holds instances.read on an async worker and reads settings.json. It runs 3 or more SQLite queries per live structured row and calls resolve_config per profile three times (resume_configs, SessionCfgCache, tie_cache), each with install_from_config. The change check at runtime.rs:322 comes after projection. status_poll also calls publish explicitly after request_publish wakes.
  • Measure: Add tracing span timing around project_sessions in runtime.rs:287; run with 50 sessions and a web client attached; check total CPU per second with Instruments or perf.

#4 Structured view re-lays out the entire transcript on every draw

  • Impact high, effort M, verdict confirmed, evidence proven-by-code, area sweep-alloc-serde, category render
  • Where: src/tui/structured_view/render.rs:730, src/tui/structured_view/render.rs:886-903, src/tui/structured_view/render.rs:1524-1584, src/tui/structured_view/render.rs:942-950, src/tui/structured_view/embedded.rs:581, src/tui/app.rs:1240-1245
  • Frequency: Per frame of the live structured view and embedded preview: each event, each 120ms spinner tick, each key; scales with transcript row count (one row per chunk, unbounded by default).
  • Problem: render_transcript calls wrapped_transcript every draw: builds completions/children/starts maps, concatenates chunk rows, re-parses markdown for every agent message via tui::markdown::render, deep-owns every span (own_line into_owned) and re-wraps all lines, though only text_area.height lines are shown. Only the retained (read-only) view has a text_cache.
  • Fix: Cache the wrapped Text in StructuredViewState keyed by (width, theme, server_rows revision) like RetainedTextCache in embedded.rs:43; render markdown per message group once and invalidate only the tail group on a Patch/Append. Slice just the visible window into the Paragraph.
  • Verifier: render_transcript (render.rs:730) calls wrapped_transcript on every draw, and nothing caches the result. That call rebuilds transcript_lines, re-renders the markdown for each message (render.rs:1515), runs own_line and re-wraps every line. Only the embedded retained path has RetainedTextCache (embedded.rs:264). app.rs:1243 redraws on every embedded event, so the cost grows with transcript length times the event rate.
  • Measure: Time wrapped_transcript with Instant around render.rs:730 on a 2000-row transcript while a turn streams. Log the p50 and p99 per draw.

#5 Browser persists the full ACP state, including the whole transcript, to localStorage on every state change

  • Impact high, effort S, verdict confirmed, evidence proven-by-code, area sweep-memory, category memory
  • Where: web/src/hooks/useAcpSession.ts:236-239, web/src/hooks/acpSession/stateCache.ts:97-101, web/src/hooks/acpSession/stateCache.ts:175-179, web/src/hooks/acpSession/stateCache.ts:47-71
  • Frequency: Every reducer state change of an open structured view. That is 2-3 times per ACP event (frame, reduced_state, transcript_delta), so tens per second while an agent streams. Scales with transcript length (activity rows).
  • Problem: A useEffect([state]) calls cacheSet, which JSON.stringifies the full state (all activity rows) and writes it to localStorage synchronously. At 10k rows that is MBs of allocation per chunk, on the main thread. Once the entry exceeds quota, every write also runs evictOldestPersistedAcpState, which JSON.parses every other persisted session entry.
  • Fix: Split cacheSet into an in-memory lruInsert/notify and a trailing-throttled persist (for example 2s, flushed on pagehide/visibilitychange). In toPersistedState, persist only the tail window: rows from lastUserBoundaryIndex, at least DEFAULT_HISTORY_WINDOW, with oldestSeq set to match. reopenState and replay already reload older pages.
  • Verifier: useAcpSession.ts:237-239 runs cacheSet on every reducer state; cacheSet (stateCache.ts:175-179) calls persistState, which JSON.stringifies the full state including all activity rows and writes localStorage synchronously. No throttle or debounce exists. On quota failure, evictOldestPersistedAcpState JSON.parses every other entry.
  • Measure: Chrome Performance trace while an agent streams in a 5k-row session; sum self-time of persistState/JSON.stringify per second.

#6 Web persists the whole AcpState (full transcript) to localStorage on every state change

  • Impact high, effort S, verdict confirmed, evidence proven-by-code, area trace-acp-stream, category render
  • Where: web/src/hooks/useAcpSession.ts:237-239, web/src/hooks/acpSession/stateCache.ts:96-101, web/src/hooks/acpSession/stateCache.ts:171-175
  • Frequency: 3x per streamed chunk (frame, reduced_state, transcript_delta each produce a new state), per open session tab
  • Problem: useEffect on [state] calls cacheSet, which runs persistState: JSON.stringify of the entire state including every activity row, then synchronous localStorage.setItem on the main thread. Cost is O(transcript) per chunk, so O(n^2) per turn, and blocks rendering on long sessions.
  • Fix: Split cacheSet: keep lruInsert + notifyStateListeners immediate, but debounce persistState per session (trailing 1-2 s via setTimeout or requestIdleCallback) and flush on visibilitychange/pagehide and on unmount. Optionally persist only the last N activity rows.
  • Verifier: useAcpSession.ts:237-239 runs cacheSet on every committed state; persistState JSON.stringifies the full AcpState including every activity row and calls localStorage.setItem synchronously. No debounce exists. Frequency is per React commit, not per dispatch, but each chunk is its own row (msg-{seq}), so cost grows with turn length. Rows are not capped.
  • Measure: Chrome Performance trace while streaming a long turn; sum persistState self time, or wrap persistState with performance.mark/measure and log per-call ms and body length.

#7 TUI redraws the whole app and rebuilds the full transcript twice per chunk

  • Impact high, effort M, verdict confirmed, evidence proven-by-code, area trace-acp-stream, category render
  • Where: src/tui/app.rs:1233-1243, src/tui/structured_view/render.rs:886-903, src/tui/structured_view/render.rs:1524-1580, src/tui/structured_view/render.rs:728-738
  • Frequency: Per WS message (reduced_state + transcript_delta = 2 per chunk) while the structured view is open
  • Problem: Each embedded event triggers self.draw; render_transcript calls wrapped_transcript, which re-walks all server_rows, rebuilds HashMaps of completions, concatenates every message group, renders markdown lines and wraps every line, before scrolling to show only the viewport. O(transcript) per message, O(n^2) per turn.
  • Fix: In the app loop, after apply_event drain ready events with a non-blocking try_next loop before drawing, and cap redraws at ~30 fps with a dirty flag. Cache wrapped lines per group in StructuredViewState keyed by (group_id, text len, width), rebuilding only the tail group.
  • Verifier: app.rs:1233-1243 calls self.draw after each embedded event, with no drain or frame cap. render_transcript calls wrapped_transcript, which rebuilds the completion and child maps, concatenates every message group, renders markdown and wraps every line, then shows only the viewport. Cost is O(rows) per message. No cache exists in render.rs.
  • Measure: Add a tracing span around wrapped_transcript in the TUI. Log its duration and call count per second while a 5k-row session streams.

#8 Scrolling back in any long session falls off the VT grid onto 2-fork capture-pane polling of up to 4000 lines

  • Impact high, effort S, verdict confirmed, evidence proven-by-code, area trace-terminal-stream, category cpu
  • Where: src/server/live_ws.rs:445, src/server/live_ws.rs:1202, src/tmux/vt.rs:779, src/tmux/vt.rs:1881, web/src/hooks/useLiveTerminal.ts:303, web/src/hooks/useLiveTerminal.ts:516
  • Frequency: Every 250ms (idle cadence) while a web viewer reads scrollback, per viewer; plus one full-frame resend on entering and leaving reading
  • Problem: The client asks for window = rows + history. The grid reports history = total scrollback (max 2000), so once scrollback fills, window = 2000 + rows exceeds SCROLLBACK_LINES and grid_transport_eligible fails. The loop then forks list-panes plus a chained capture-pane of about 2000 lines every 250ms. The transport flip also clears last_sent, so a full multi-hundred-KB frame goes out on each flip.
  • Fix: In grid_transport_eligible, compare window_lines against SCROLLBACK_LINES + current grid rows (pass ch.rows), because grid_content can serve total_sb + h lines. Or clamp the client window in enterReading/handleMessageText to rows + history, where history already comes from the grid.
  • Verifier: grid_content reports history=total_sb (parser capped at SCROLLBACK_LINES=2000); useLiveTerminal.ts:305/519 asks rows+history, so window exceeds 2000 once total_sb > 2000-rows and grid_transport_eligible (live_ws.rs:459) fails. Window > screen*4 forces 250ms idle cadence; transport flip clears last_sent (1579). Fix must compare to SCROLLBACK_LINES+rows; panes with history-limit above 2000 lose the deeper capture-path history.
  • Measure: In a pane with 2000+ scrollback lines, scroll back in the web view, then count tmux forks/s with sudo execsnoop -n tmux and log the transport messages.

#9 cancel-in-progress on main pushes kills the only macOS run before it finishes

  • Impact high, effort S, verdict confirmed, evidence measured, area ci-main, category ci-time
  • Where: .github/workflows/tests.yml:12-14, .github/workflows/tests.yml:338-388
  • Frequency: Every push to main. Measured: 7 of the last 10 main push runs were cancelled. The cancelled macOS jobs had already run 902s, 1414s, 1991s and 2626s.
  • Problem: The group tests-push-refs/heads/main cancels the running main build on each new merge. macOS needs about 37 min (641s lib build plus 1138s test build plus tests) and merges come faster than that. Most macOS runs are thrown away, and macOS regressions on main go unseen for hours. Example: run 43911157806 failed, and only its predecessor's cancellation let it finish.
  • Fix: In tests.yml set cancel-in-progress: ${{ github.event_name != 'push' }}. GitHub still drops older pending runs, so the current main run finishes and the newest queued one runs next. With the push-trimming finding, only macOS (and maybe coverage) stays in this group.
  • Verifier: tests.yml:13-14 uses cancel-in-progress: true for every event. In 6 of the last 8 main push runs, macOS was cancelled after 15 to 33 min, while the Linux legs finished in about 8 min. With cancel-in-progress false for push, at most one run waits and newer pushes replace it.
  • Measure: Count macOS job conclusions on push runs over one week, before and after the change: gh run list -w Tests -e push, then gh run view --json jobs.

#10 Diff worker bundled as IIFE inlines every Shiki grammar: 10.7 MB worker, spawned 4 times

  • Impact high, effort S, verdict confirmed, evidence measured, area web-bundle, category bundle-size
  • Where: web/vite.config.ts:36-56, web/src/components/diff/pierre/DiffWorkerPoolProvider.tsx:14-38
  • Frequency: Each time a diff or full-file viewer mounts (DiffFileViewer / FullFileViewer), and on every theme change (provider is keyed by theme); 4 workers per pool.
  • Problem: vite.config.ts sets no worker.format, so Vite uses iife, which cannot code-split and inlines all of @pierre/diffs' dynamic grammar imports. The sibling build shows worker-*.js = 10,742,432 B with 207 grammar scopeNames and 2 inlined wasm blobs (source worker.js is 72 KB ESM). Each of the 4 pool workers parses ~10 MB JS; it also bloats the aoe binary by ~10 MB.
  • Fix: Add worker: { format: "es" } to the defineConfig return in web/vite.config.ts (the Worker is already created with type: "module"). Grammars then load as shared lazy chunks per language. Optionally lower poolSize in DiffWorkerPoolProvider to Math.min(4, Math.max(1, navigator.hardwareConcurrency - 1)).
  • Verifier: vite.config.ts sets no worker.format, so Vite 8.3.5 uses the iife default. The sibling worker-.js starts with (function(){, is 10.7 MB, and has 260 inlined scopeName grammars that also exist as separate main-thread chunks (cpp-.js etc.). The pool has poolSize 4 and is keyed by theme. DiffWorkerPoolProvider already uses type module, so worker.format es is safe.
  • Measure: npm run build; ls -la dist/assets/worker-*.js; DevTools Performance: script eval time of the 4 workers when a diff opens

#11 activityToThreadMessages rebuilds every message object on every activity change, defeating assistant-ui's converter cache

  • Impact high, effort M, verdict confirmed, evidence proven-by-code, area web-acp-render, category render
  • Where: web/src/components/acp/AcpRuntime.tsx:193-203, web/src/components/acp/AcpRuntime.tsx:209-219, web/src/components/acp/activityMessages.ts:51-183, web/src/components/acp/activityMessages.ts:240-258, web/src/components/acp/activityMessages.ts:297-306, web/src/components/acp/activityMessages.ts:364-373
  • Frequency: Every WS event that changes acp.state.activity (each streamed text chunk, tool update, completion). Scales with windowed row count and total tool-args bytes in the window.
  • Problem: The memo depends on displayActivity, so each chunk re-walks all rows, JSON.parses every args_preview, re-stringifies every tool part and group payload, and re-parses argsText in argString/isTodoWriteArgsText. All ThreadMessageLike objects are new, and convertMessage is an inline lambda, so assistant-ui's identity-keyed converter cache misses and every message and part runtime state changes, re-rendering the whole transcript per chunk.
  • Fix: Make activityToThreadMessages incremental: keep a per-message cache (useRef Map keyed by message id) storing the row references that produced it and return the previous object when those rows are reference-equal. Hoist convertMessage to a module-level const identity = (m) => m. Memoize parseJsonObject results in a bounded Map keyed by the args string.
  • Verifier: AcpRuntime.tsx:216 passes inline convertMessage: (m) => m; assistant-ui core external-store-thread-runtime-core.ts:652 resets ThreadMessageConverter whenever convertMessage identity changes, so every AcpRuntime render reconverts all messages, even when messages is memo-stable. argsText also embeds uncapped _aoe_diffs and _aoe_prompt, re-stringified per chunk. Hoisting convertMessage is a one-line first step.
  • Measure: React Profiler: record 10s of a streaming turn with 150 rows; count message component commits per chunk before and after hoisting convertMessage.

#12 Every ACP state change JSON.stringifies the whole transcript into localStorage

  • Impact high, effort S, verdict confirmed, evidence proven-by-code, area web-data-layer, category cpu
  • Where: web/src/hooks/useAcpSession.ts:237-239, web/src/hooks/acpSession/stateCache.ts:97-102, web/src/hooks/acpSession/stateCache.ts:175-179, web/src/hooks/acpSession/stateCache.ts:47-71
  • Frequency: Per reducer dispatch: every WS transcript_delta, frame, reduced_state, per streamed chunk, per open structured view
  • Problem: The effect on [state] calls cacheSet, which runs persistState: JSON.stringify of the full AcpState (all activity rows, tool output) plus a synchronous localStorage.setItem, on every streamed chunk. Cost is O(transcript size) per chunk on the main thread. On quota failure, evictOldestPersistedAcpState JSON.parses every persisted entry per chunk. Other same-origin tabs receive a storage event carrying the multi-MB old and new values each time.
  • Fix: Split cacheSet: keep lruInsert+notifyStateListeners synchronous, but debounce persistState per session (e.g. 1-2s trailing, plus flush on pagehide/visibilitychange hidden and on session switch). Also cap persisted activity to the last window (e.g. rows after initialHistoryWindow boundary) in toPersistedState, and make evictOldest read savedAt without parsing the whole body (store savedAt in a separate small key).
  • Verifier: useAcpSession.ts:237-239 runs cacheSet on every state change; cacheSet (stateCache.ts:175) calls persistState synchronously, which JSON.stringifies the whole AcpState and calls localStorage.setItem. There is no debounce. The server sends one transcript_delta per event frame (acp_ws.rs:248-251) and does not coalesce them. Keep lruInsert and notify synchronous. Activity capping must respect reopenState and oldestSeq.
  • Measure: In the browser, wrap persistState with performance.mark/measure, stream a long turn on a large transcript, and sum the time per second in a DevTools Performance trace.

#13 Sandbox stop always waits Docker's 10s grace: PID 1 is sleep infinity with no init

  • Impact high, effort S, verdict confirmed, evidence proven-by-code, area gap-stop-delete-shutdown-latency, category latency
  • Where: src/containers/runtime_base.rs:596-598, src/containers/runtime_base.rs:750-754, src/containers/runtime.rs:748-753, src/session/worktree_edit.rs:256-295, src/session/instance/kill.rs:441-445, src/server/api/sessions/lifecycle.rs:1606-1635, docker/Dockerfile
  • Frequency: Every stop, idle auto-stop, and TUI stop of a sandboxed session (terminal or structured). Scales linearly with the number of sandboxed sessions stopped.
  • Problem: Containers run image sleep infinity with no --init and no ENTRYPOINT in docker/Dockerfile. As PID 1, sleep ignores SIGTERM, so docker stop <name> (no -t) always waits the runtime's full 10s before SIGKILL. A structured stop holds the instance lock, submission guard and namespace read lease for that time. The HTTP stop returns more than 10s late.
  • Fix: In RuntimeBase::stop_container, pass -t 0 (or --time 0), because the container only runs sleep and the agents are already torn down. Another option: add --init to build_create_args when the runtime supports it, so SIGTERM ends PID 1 at once.
  • Verifier: build_create_args ends with image sleep infinity (runtime_base.rs:596-598), no --init anywhere in src/containers. stop_container runs bare stop <name> (runtime_base.rs:753, also execution.rs:92). PID 1 sleep has no SIGTERM handler, so every stop waits the 10s default. Check Apple container stop flag spelling before adding -t 0.
  • Measure: time docker stop on a running aoe sandbox container; expect about 10s now, under 1s with -t 0 or --init

3. Medium impact, full detail

#14 Pane capture re-resolves the pane id with an extra tmux fork although PaneMetadata already has it

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area session-instance, category subprocess
  • Where: src/session/instance/status_update.rs:364, src/session/instance/status_update.rs:513-516, src/tmux/session.rs:833-850, src/tmux/session.rs:1274-1283, src/tmux/mod.rs:324-327
  • Frequency: Every pane capture in the status poll (per session per 500ms/2s tick for hooked or changed panes), plus explain_error_from_pane captures.
  • Problem: Session::capture calls live_pane_target_with_deadline, which forks tmux list-panes (first_pane_id_with_deadline) unless a VT channel is registered. The batched PaneMetadata already carries pane_id, so each capture costs two tmux processes where one is enough.
  • Fix: Add a tmux::Session::capture_pane_target(target: &str, lines) (or capture_pane_with_metadata) and call it from update_status_from_manifest and the legacy path at status_update.rs:364 with metadata.pane_id when metadata is Some, falling back to capture_pane otherwise.
  • Verifier: Session::capture (session.rs:833) calls live_pane_target_with_deadline, which forks list-panes unless a VT channel exists. PaneMetadata.pane_id comes from the same batched list-panes and is pane_index 0 of the first window, so it targets the same pane. The legacy capture is at status_update.rs:362, the manifest capture at ~569.
  • Measure: Count tmux list-panes execs per status tick with dtrace or a trace log in first_window_pane_ids_with_deadline, before and after the change.

#15 Mounted structured preview forces a full redraw every 120ms forever

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area tui-loop-home, category cpu
  • Where: src/tui/app.rs:1503-1512, src/tui/structured_view/embedded.rs:550-562
  • Frequency: Every 120ms (~8 fps) while any structured session is selected, because preview-on-select mounts it, even when nothing changes
  • Problem: The loop sets needs_full_refresh whenever last_spinner_redraw is older than 120ms and structured_preview is Some. The comment says this keeps the composer caret blinking. But the caret only exists while view.is_active(). A passively mounted transcript re-renders the whole home view (list, status bar, transcript layout) about 8 times per second with no visible change.
  • Fix: In App::run, gate the caret cadence on view.is_active() (and only while the composer has focus). Otherwise redraw only when view.tick() reports a toast change or next_event delivers data, which already calls draw.
  • Verifier: Claim holds: the loop redraws every 120ms whenever a preview is mounted. The caret rationale is wrong even when active, because render.rs:1475 uses the terminal cursor (set_cursor_position) and the terminal blinks it. visible_notices does auto-hide on elapsed time, so the fix needs a notice-expiry deadline, not just an is_active gate.
  • Measure: Count draw() calls per second with an idle structured session selected (add a counter in App::draw), before and after the change.

#16 Full-screen structured view redraws unconditionally every 120 ms while idle

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area tui-views, category cpu
  • Where: src/tui/structured_view/mod.rs:44-46, src/tui/structured_view/mod.rs:353-354, src/tui/structured_view/mod.rs:412-423, src/tui/structured_view/render.rs:1460-1476
  • Frequency: 8.3 Hz for the whole lifetime of aoe acp attach, even with no input or agent activity
  • Problem: redraw_ticker fires every 120 ms and always calls redraw, which (see transcript finding) rebuilds the whole transcript. Nothing in the frame is time-driven except toast expiry; the caret is the terminal's hardware cursor via set_cursor_position, so it needs no redraw to blink.
  • Fix: Remove redraw_ticker. Add a select arm sleep_until(toast_deadline) (pending() when None) that clears the toast, calls drain_plugin_toast and redraws. drain_plugin_toast is already called on the plugin arm.
  • Verifier: Ticker at mod.rs:353 redraws every 120 ms unconditionally; caret is hardware cursor and busy indicator is static. But visible_notices (state.rs:282) hides notices by age via NoticePolicy timeout, so removal also needs a notice-expiry deadline, not only toast. Win shrinks to near zero if finding 0 lands.
  • Measure: Run aoe acp attach on an idle long session and sample CPU with top -pid <pid> or sample before and after removing the ticker.

#17 No coalescing of WS messages: two full redraws per streamed chunk

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area tui-views, category latency
  • Where: src/tui/structured_view/mod.rs:378-387, src/tui/structured_view/mod.rs:463-496, src/tui/app.rs:1234-1244
  • Frequency: Per WS message; the daemon sends a reduced_state plus a transcript_delta per agent event, so 2 frames per token chunk during streaming, per open view
  • Problem: Each received message triggers an immediate terminal.draw (embedded: a full home draw). During fast streaming this is dozens of full transcript rebuilds per second, which starves input handling and burns CPU proportional to transcript length times chunk rate.
  • Fix: After apply_ws_message, drain further ready messages with ws.recv().now_or_never() in a bounded loop (e.g. 64) before redrawing, or set a dirty flag and draw at most once per 16-33 ms via a deadline arm. Same in App for EmbeddedView::apply_event.
  • Verifier: server/acp_ws.rs:242-255 sends reduced_state then one transcript_delta per event; mod.rs:378-381 and app.rs:1240 draw after each message. So at least two full transcript rebuilds per streamed chunk. Draining ready messages before drawing is safe since apply_ws_message already batches state. Impact scales with finding 0.
  • Measure: Count draws per second with a counter in redraw() during a fast streaming turn; compare with WS message rate.

#18 Each tool card clones diffs and full output, JSON-parses args and runs a Myers diff per frame

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area tui-views, category cpu
  • Where: src/tui/structured_view/render.rs:1874-1893, src/tui/structured_view/render.rs:1896-1935, src/tui/structured_view/render.rs:2000-2061, src/tui/structured_view/render.rs:2083-2088, src/tui/structured_view/render.rs:2203-2241
  • Frequency: Per frame per tool card in the transcript (until the transcript cache exists, then per change)
  • Problem: tool_card_from_rows clones name/args/diffs (old_text/new_text can be whole files) and summarize_output_blocks joins the full output String even for successful cards that render one compact line and never read it. compact_tool_line reparses args JSON and runs TextDiff::from_lines for +/- counts. output_preview_lines ANSI-parses the entire output, then keeps 12 lines.
  • Fix: Make ToolCallRow borrow (&str, &[DiffPreview]); build completion content only on non-Ok paths; memoize (added, removed) and parsed args per tool_call_id in a HashMap on the view state; in styled_output_lines split to the first TOOL_PREVIEW_MAX_LINES+1 lines before into_text.
  • Verifier: Real: full-screen loop redraws every 120ms (REDRAW_INTERVAL ticker, mod.rs:46,412) and render_transcript calls wrapped_transcript which rebuilds every card with no cache. But per-card memo is the wrong layer; cache the wrapped transcript keyed by (last_seq/revision, width, path_roots) and all card costs vanish together.
  • Measure: Wrap wrapped_transcript in a tracing span with elapsed; open a session with 200+ Edit tool calls and log p50 per frame.

#19 Every snapshot publish re-reads and re-parses config TOML several times per profile and per project

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area server-api-sessions, category disk-io
  • Where: src/server/api/sessions/list.rs:42, src/server/api/sessions/list.rs:96-104, src/server/api/sessions/list.rs:137-166, src/server/api/sessions/list.rs:207-222, src/server/api/sessions/list.rs:285-291, src/server/api/sessions/list.rs:369-381, src/server/api/sessions/model.rs:411-482, src/session/config/profile_config.rs:183-196
  • Frequency: Every publish (500ms with WS clients, 2s idle) and every mutation
  • Problem: Per publish: read_tui_fullscreen reads and parses ~/.claude/settings.json; resume_profile_config, tie_cache and the park probe each call resolve_config (global config.toml, state.toml, profile config.toml, merge, status-rule reinstall) per profile; SessionCfgCache resolves once per distinct project, plus libgit2 find_main_repo; ProjectRegistryCache loads projects and canonicalizes paths. All caches are per request, so nothing survives across ticks. Only cleanup defaults has a 30s TTL.
  • Fix: Hold a process-wide resolved-config cache on AppState keyed by (profile, repo source) with invalidation from the existing file_watch service (or mtime check), and reuse it for resume, tie, park, smart-rename and acp_capable overlays. Cache read_tui_fullscreen by mtime. Memoize repo_config_source_path per project_path permanently.
  • Verifier: resolve_config is uncached: reads global config.toml, state, profile toml, merges, and recompiles status_rules regexes. Called per profile by resume, tie, park, plus per distinct project via SessionCfgCache with libgit2 discovery, every 500ms. Cache must preserve install_from_config side effect so status_rules edits still apply.
  • Measure: Count resolve_config calls and total time per publish via a trace span; compare list_sessions_resolver_misses per tick with 20 projects.

#20 acp_ws re-serializes the whole AcpState per event per connection

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area server-streaming, category cpu
  • Where: src/server/acp_ws.rs:233-262, src/server/acp_ws.rs:470-541
  • Frequency: Every ACP broadcast frame for the watched session (each AgentMessageChunk/AgentThoughtChunk token burst), per open structured-view socket
  • Problem: For every event, each socket runs serde_json::to_value(AcpState), then to_string() plus a hash for each of 5 cold fields, then serializes the whole frame again. Cost is O(state size) per streamed chunk per viewer, so it grows with recent_diffs, commands and config options. The work also slows the socket loop, which makes broadcast lag and its full replay more likely.
  • Fix: Serialize once per event, not once per subscriber. Have ChannelSink, which already folds into acp_control_cache, publish an Arc reduced_state, or coalesce reduced_state to one send per ~50ms per socket. Store cold-field digests on the cached state version so ColdFieldCache compares u64s instead of re-stringifying values. Do not send reduced_state for chunk events that cannot change the control fields.
  • Verifier: Confirmed at acp_ws.rs:240-243 and 470-541: each chunk on each socket runs to_value(AcpState), 5 to_string+hash, then to_string of the frame. State is bounded (MAX_RECENT_DIFFS=16), and there are usually 1-2 viewers, so the cost is per-chunk constant work, not unbounded. Sharing one serialization is hard because each socket has its own fold, projection and cold cache. Coalescing or skipping chunk-only frames is the cheaper fix.
  • Measure: Wrap send_reduced_state in a tracing span with elapsed time and payload bytes, then stream a long turn with config_options and commands populated.

#21 acp_ws connect and lag recovery replay the whole event log from seq 0

  • Impact medium, effort L, verdict partly, evidence proven-by-code, area server-streaming, category latency
  • Where: src/server/acp_ws.rs:356-409, src/server/acp_ws.rs:263-323, src/server/acp_ws.rs:437-458, src/server/session_service.rs:1898-1901
  • Frequency: Every structured-view WS connect or reconnect (tab open, mobile resume, network blip) and every RecvError::Lagged
  • Problem: replay_from(session, 0) reads and decodes the full history, then folds both AcpState and TranscriptModel. session_service.rs says this exact rebuild measured 68ms at 20k events and 342ms at 100k, and that it holds the event store connection mutex. That is why fold_control_state caches it. acp_ws bypasses the cache. A slow client that lags repeats the full scan, which slows it further.
  • Fix: Seed reduced from session_service.fold_control_state(id), which is cached. Add a cached TranscriptModel to the acp_control_cache entry, folded at the same publish point. Clone both on connect, and fetch only replay_from(since) for raw frames. On Lagged, rebuild from the same cache rather than store.replay_from(0).
  • Verifier: Connect (acp_ws.rs:366) and Lagged (277) both call replay_from(session,0) and fold everything. replay_from now uses reader(), a pooled WAL read connection, so the writer-mutex stall cited from session_service.rs:1898 mostly no longer applies. The full transcript snapshot still needs every row, so a daemon-wide cached TranscriptModel adds memory per session.
  • Measure: Time drain_replay_into_socket on a session with 20k and 100k events; log the elapsed ms at the 'agent ws subscribed' debug line.

#22 ACP listener takes the global instances write lock for every streamed chunk

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area server-streaming, category concurrency
  • Where: src/server/acp_events.rs:441-464, src/server/acp_events.rs:521-562, src/server/acp_events.rs:1131-1146
  • Frequency: Every AgentMessageChunk/AgentThoughtChunk/ToolCallStarted of every structured session; scales with sessions streaming at once
  • Problem: status_policy returns Authoritative for chunk events, so status_update is Some. The serial listener then takes state.instances.write() and does a linear find, even though status almost never changes mid-turn. This write lock blocks the status poller, runtime publish, API reads and live_ws lookups, and the single listener task risks lagging the 256-slot broadcast.
  • Fix: In acp_event_listener, keep a HashMap<session_id, Status> of the last applied projection, or check under instances.read(). Skip the write lock when projected == inst.status && !inst.plugin_revival_pending and there is no acp_change or capability update. Take the write lock only when apply_status_intent would mutate.
  • Verifier: status_policy (acp_events.rs:1131-1146) marks AgentMessageChunk, AgentThoughtChunk and ToolCallStarted Authoritative. status_update is then Some, and line 521 takes instances.write() plus a linear find for every chunk. tokio RwLock is fair, so queued writes block new readers. A read-locked pre-check, skipping the write when projected == status, is safe.
  • Measure: Count instances.write() acquisitions per second in acp_event_listener during a streaming turn, and record the wait time with a tracing span.

#23 Snapshot live view forks tmux twice every 50ms per viewer, even when the pane is idle

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area server-streaming, category subprocess
  • Where: src/server/live_ws.rs:1209-1228, src/server/live_ws.rs:2013-2061, src/tmux/session.rs:922-977, src/tmux/utils.rs:288-295
  • Frequency: Per live viewer of a paired host/container shell, or of an agent pane on the capture fallback (tmux <3.4, vt_live off, split window): every 50ms fast and 250ms idle/backgrounded
  • Problem: capture_window_composited_with_cursor runs first_pane_id (list-panes fork) and then a chained display/capture-pane fork. That is about 40 forks/s per open shell tab and 8/s while backgrounded. Content dedup only suppresses the WS send, not the forks. Two viewers of the same pane double it, because nothing is shared.
  • Fix: Cache the pane0 id per connection and re-resolve only when a capture fails. Drive the snapshot loop from a change signal: give Osc52Channel's raw pipe observer (already armed for snapshot surfaces) a watch::Receiver, and use it like vt_rx in wait_for_next, keeping a slow ceiling. Optionally share one capture per (tmux_name, lines) across viewers.
  • Verifier: Snapshot transport (shells, or capture fallback) calls capture_window_composited_with_cursor. That forks first_pane_id (list-panes) and then a chained tmux command every 50ms when focused and 250ms when idle, plus window_pane_count once a second. Caching pane0 halves the forks (S). The proposed change signal is weak: Osc52Channel arms only when clipboard_forward is enabled, and pipe-pane is single-owner.
  • Measure: Open one shell tab and count tmux execs per second with sudo execsnoop or dtrace -n 'proc:::exec-success /execname=="tmux"/{@=count()}'.

#24 Every status tick re-reads and re-parses all config files and recompiles status-rule regexes for every profile

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area server-state, category cpu
  • Where: src/server/reload.rs:318-325, src/server/reload.rs:464-560, src/server/reload.rs:589-614, src/session/config/profile_config.rs:183-196, src/tmux/status_rules.rs:86-115, src/server/status_poll.rs:463-509
  • Frequency: Every status_poll_loop tick: 500ms while any runtime subscriber (web/TUI) is attached, 2s otherwise. Scales with profile count.
  • Problem: ProfileSessionsCache::load caches only sessions files. load_profiles still calls Config::load, load_workspace_ordering, projects::load_global, and per profile load_profile_details -> resolve_config (Config::load again, profile TOML, JSON round-trip merge) plus install_from_config, which recompiles status_rules regexes and re-logs the 'shadow the built-in detector' warn every tick. All of it runs while disk_reload_guard is held exclusively, which stalls queue mutations.
  • Fix: Cache ProfileDetails, default_profile, workspace ordering, and global projects in ProfileSessionsCache, keyed by mtime/len of config.toml, state.toml, the profile config, and the projects files. Alternatively, invalidate the cache from FileWatchService config events. Call status_rules::install_from_config only when the resolved config changed. Do the config stat checks before taking disk_reload_guard.
  • Verifier: ProfileSessionsCache caches only sessions files. load_profiles calls Config::load (config.toml plus state.toml) and, per profile, load_profile_config, projects::load_profile and resolve_config, which calls install_from_config. That recompiles regexes and re-logs the shadow warn every tick. It runs in spawn_blocking with disk_reload_guard held. Absolute cost is a few small TOML parses, so impact is medium, not high.
  • Measure: Wrap sessions_cache.load in status_poll.rs:497 with Instant timing and log p50/p99 at 3 and 10 profiles; grep the log for repeated shadow warnings.

#25 Startup serially replays every structured session's full event log before the daemon is ready

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area server-state, category startup
  • Where: src/server/acp_events.rs:724-742, src/server/session_service.rs:1902-1940, src/acp/control_cache.rs:82-98, src/server/startup.rs:1171, src/server/startup.rs:1479
  • Frequency: Once per daemon start. Scales with structured session count times event-log length.
  • Problem: seed_acp_statuses awaits fold_control_state for each structured session one at a time. On a cold cache each call replays the whole log. The code's own comment measures 68ms at 20k events and 342ms at 100k, and the replay holds the event store connection mutex. This finishes before notify_ready and axum::serve, so 50 long sessions add seconds to startup.
  • Fix: Persist a fold checkpoint (AcpState plus last_seq) in the event store on idle or shutdown, and replay only the tail on hydrate. Alternatively, hydrate with a bounded JoinSet and move seeding after the listener binds, so rows publish Unknown until seeded.
  • Verifier: Serial cold fold per structured session before serve (startup.rs:1171, serve at 1490) is real. replay_events defaults to 0, unlimited, so logs grow without bound. The claim that it holds the connection mutex is stale: replay uses pooled WAL read connections (event_store/mod.rs:208). A bounded JoinSet works with the reader pool and is the cheap fix. A persisted checkpoint is the larger fix.
  • Measure: Log elapsed time around seed_acp_statuses at daemon start on a profile with 50 structured sessions holding 20k+ events each.

#26 Assets from the embedded web bundle are served uncompressed and copied on every request

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area server-state, category network
  • Where: src/server/assets.rs:62-115, src/server/router.rs:583, src/server/router.rs:590-603
  • Frequency: Per asset request: every cold dashboard load and every no-cache revalidation of index.html, sw.js and fonts. Matters most for remote and tunnel clients.
  • Problem: compression_layer only compresses application/json, so multi-MB JS/CSS bundles go over tunnels and mobile links uncompressed. serve_embedded_file also copies the &'static embedded bytes with file.data.to_vec() and formats a hex ETag on each request.
  • Fix: Precompress dist at build time (.br/.gz embedded beside each file) and pick a variant from Accept-Encoding with Vary. Or extend the compression predicate to text/javascript, text/css, text/html and image/svg+xml. Build the body with Bytes::from_static when data is Cow::Borrowed, and cache ETags in a OnceLock map.
  • Verifier: Confirmed: compression_layer matches application/json only (router.rs:590-604), and PR #5356 gives no reason to exclude assets. Hashed assets are immutable for a year, so the cost hits cold loads and upgrades, and it matters most on tunnels. The to_vec copy and the per-request ETag formatting are negligible. Drop that part of the fix and update the compression_skips test.
  • Measure: curl -so /dev/null -w '%{size_download}' -H 'Accept-Encoding: gzip' against the entry index-*.js, with and without text/javascript added to the predicate.

#27 terminal/create runs the whole command inside the SDK dispatch loop while holding the ingress fence

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area acp-client, category latency
  • Where: src/acp/acp_client/connection/mod.rs:106-131, src/acp/acp_client/connection/mod.rs:381-385, src/acp/acp_client/terminal_handlers.rs:15-66, src/acp/terminal_handler.rs:85-145, src/acp/acp_client/handshake.rs:30
  • Frequency: Every terminal/create the agent sends (we advertise terminal(true)); blocks for the full command runtime
  • Problem: resource_requests! awaits the handler inline. The SDK docs say this blocks all further message processing. create_and_run awaits wait_with_output, so a 5 minute npm test freezes every session/update, response and permission request for that session, and the fence held in _guard also blocks notification admission. Streaming stalls for the whole command.
  • Fix: Make TerminalManager::create_and_run spawn the child, store a Shared/JoinHandle for its output, and return the id at once. Have output/wait_for_exit await that handle. In resource_requests!, route CreateTerminal and WaitForTerminalExit through conn.spawn the way the permission handler does, and release the fence before any await on the child.
  • Verifier: SDK 5.0.0 jsonrpc.rs:1347 says on_receive_request blocks the dispatch loop. resource_requests! awaits handle_create_terminal inline, and create_and_run awaits wait_with_output (terminal_handler.rs ~130). Permission and elicitation handlers already use conn.spawn. Updates and kill_terminal stall for the whole command. The win depends on how often the agent uses terminal/create.
  • Measure: Run a 60s sleep via terminal/create and check the acp.protocol.tool_dispatch trace elapsed_ns plus the gap in session/update timestamps.

#28 Event writer commits one SQLite transaction per event; no group commit

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area acp-supervisor, category disk-io
  • Where: src/acp/supervisor/sink.rs:162, src/acp/supervisor/sink.rs:428, src/acp/event_store/mod.rs:236-266, src/events/mod.rs:84-95
  • Frequency: Per published event (every agent message/thought chunk, tool update) on the single acp-event-writer thread; scales with streaming rate x concurrent sessions
  • Problem: The writer thread drains for job in queue and calls EventStore::record per job, which opens and commits its own transaction. In WAL mode each commit writes every dirtied page (event leaf, PK autoindex, 3 secondary indexes, acp_history_versions trigger row), so a ~100-byte chunk costs several 4 KB WAL frames. Under a burst the queue holds many jobs that could share one commit.
  • Fix: In the ChannelSink writer loop, after a blocking recv, drain up to N more jobs with try_recv, add EventStore::record_batch that inserts all Publish jobs in one transaction, then fold the control cache and broadcast each frame after commit, and send each persisted receipt. Flush/Test jobs end the batch.
  • Verifier: EventStore::record (event_store/mod.rs:236) opens and commits one transaction per job, and the acp_history_insert trigger also rewrites acp_history_versions on every insert. But synchronous=NORMAL in WAL means no fsync per commit, and the writer thread is already off the drain path (#5252). The real costs are WAL page writes and writer-mutex hold time. The batch must keep per-job receipts and the RateLimit inherit read.
  • Measure: Count WAL bytes written (wal file growth, or fs_usage on the db) and record() latency with a trace span while 5 sessions stream, before and after batching.

#29 try_in_flight_turn json_extracts every BackgroundAgentProgress row in the session

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area acp-supervisor, category cpu
  • Where: src/acp/event_store/turns.rs:586-628, src/acp/event_store/turns.rs:546-564
  • Frequency: Each has_in_flight_turn / holds_live_work / has_open_turn call for a session whose last prompt has ended: terminal-repair every 30 s, idle reap every 60 s, respawn probes, attach_project; scales with total progress rows ever written
  • Problem: The bg-agent subquery UNION ALLs all BackgroundAgentLaunched and BackgroundAgentProgress rows and json_extracts agent_id from each. Progress rows carry the full tools array (up to 250 entries) and are never pruned at the default unlimited retention, so each probe parses megabytes of JSON for long sessions with many subagents.
  • Fix: Restrict the scan to rows with created_at >= the stale cutoff (add AND created_at >= ?2 to both UNION arms, served by idx_session_created_at), since older rows can never satisfy last_at >= ?2. Optionally store agent_id in a generated column to avoid JSON parsing.
  • Verifier: The bg-agent subquery at turns.rs:598-620 json_extracts every Launched and Progress row in the session. Progress is throttled to 1.5 s per agent (background_agent.rs:17), carries up to 250 tools, and is never pruned at the default replay_events=0. Filtering both arms with created_at >= ?2 gives the same set of agents for last_at >= cutoff.
  • Measure: In sqlite3 on a long session, time this query with .timer on, then time it again with AND created_at >= cutoff added to both arms.

#30 TranscriptModel finds tool start rows and id rows with linear scans over all rows

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area acp-supervisor, category cpu
  • Where: src/acp/transcript.rs:936-941, src/acp/transcript.rs:704-719, src/acp/transcript.rs:721-776, src/acp/transcript.rs:779-808, src/acp/transcript.rs:394, src/acp/transcript.rs:561, src/acp/transcript.rs:610
  • Frequency: Per ToolCallStarted/Updated/Completed event (find_tool_start up to 3 times in on_tool_updated), per UserPromptSent/SessionNotice; per WS connection fold and per replay; scales with transcript rows
  • Problem: find_tool_start does rows.iter().position from the start, and UserPromptSent, SessionNotice and CompactionSummary search rows by id linearly although row_ids exists. Rows grow one per message chunk, so each tool update costs O(rows) and a full replay of a long session is O(rows x tool events).
  • Fix: Add tool_start_idx: HashMap<String, usize> and row_idx: HashMap<String, usize> to TranscriptModel, maintained in append and rebuilt in remove_rows_for_tool. Use them in find_tool_start and the id lookups, and check row_ids before any search.
  • Verifier: find_tool_start scans rows linearly, and on_tool_updated calls it up to 3 times. Rows grow one per AgentMessageChunk (msg-{seq}). Every WS connect replays from seq 0 (acp_ws.rs:360 replay_from(...,0)) into a fresh TranscriptModel. So connect cost is O(rows x tool events) on long sessions. The index must be rebuilt after rows.retain in remove_rows_for_tool.
  • Measure: Time the drain_replay_into_socket fold for a 20k-event session DB with tracing span timing, before and after adding the tool_start index

#31 upsert_transcript_row and patch_transcript_row search from the front, making snapshot merges quadratic

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area acp-supervisor, category cpu
  • Where: src/acp/transcript.rs:1030-1055, src/tui/structured_view/reducer.rs:256-270, src/acp/client/http.rs:340-347
  • Frequency: Per transcript row in merge_server_rows (TUI connect snapshot) and in client http row replay; per delta in apply_transcript_delta; scales with rows squared
  • Problem: Each call does rows.iter().position(|r| r.id == incoming.id) from index 0. merge_server_rows and the http replay call it once per incoming row, so loading a 50k-row transcript does about 1.25e9 string comparisons. Appends almost always target new ids at the tail.
  • Fix: Add a batch helper merge_transcript_rows(rows, incoming) that builds a HashMap<String, usize> of existing ids once and upserts through it; use it in TranscriptReducer::merge_server_rows and http.rs. For single deltas use rposition so tail hits are O(1).
  • Verifier: Batch paths are quadratic: merge_server_rows (reducer.rs:256) and replay_rows_paged (http.rs:337) call upsert_transcript_row, which does a linear position() per row. Retention defaults to unlimited (replay_events=0), so long sessions get large. TUI only; web mergeServerRows already uses a Map index. rposition does not help: new-id Appends miss and still scan all rows. Keep an id index in the reducer instead.
  • Measure: Time TranscriptReducer::merge_server_rows on 20k and 50k synthetic msg-N rows in a unit bench, or log the elapsed time around the TUI connect replay.

#32 search_content scans the whole events table; SEARCH_ROW_SCAN_CAP does not bound the scan

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area acp-supervisor, category latency
  • Where: src/acp/event_store/search.rs:16, src/acp/event_store/search.rs:46-60, src/events/mod.rs:111-112
  • Frequency: Per session search request from the dashboard; scales with total events across all sessions
  • Problem: The query is WHERE event_json LIKE '%x%' ORDER BY created_at DESC LIMIT 2000 with no index on created_at alone, so SQLite LIKE-tests every row in acp_events, sorts the matches, then applies LIMIT. The comment says the cap stops a no-match query from walking a huge table, but the scan is still full. It also holds the single read_conn mutex.
  • Fix: Add an FTS5 table (acp_events_fts over extracted prose, kept in sync by insert/delete triggers) and query it with MATCH. Cheaper interim fix: add an index on created_at so the DESC walk can stop at the LIMIT, and use self.reader() instead of read_conn().
  • Verifier: Confirmed: no created_at-only index exists (events/mod.rs:109-112 indexes are session-prefixed), so LIKE scans the whole table and sorts before LIMIT. The handler already uses spawn_blocking and the client debounces for 200ms. The interim created_at index stops early only on queries with many matches. A no-match query still walks everything. FTS5 is the real fix and needs a migration plus backfill.
  • Measure: Run EXPLAIN QUERY PLAN and time the search query with sqlite3 against a real acp.db holding at least 500k events, for a term that matches nothing.

#33 Every pane capture forks list-panes (and maybe has-session) before capture-pane

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area tmux, category subprocess
  • Where: src/tmux/session.rs:833-852, src/tmux/session.rs:1274-1284, src/tmux/session.rs:382-384, src/tmux/utils.rs:268-277, src/tmux/utils.rs:321-381, src/tmux/session.rs:926-930
  • Frequency: Per captured session per daemon tick (500ms/2s); per TUI live-preview capture (250ms idle cadence) when no VT channel; scales with active session count.
  • Problem: Session::capture calls exists() (has-session fork on cache miss), then live_pane_target_with_deadline -> first_pane_id_with_deadline (a list-panes fork), then capture-pane: 2-3 forks per capture. The poller already holds PaneMetadata.pane_id for the same pane 0 from the batched list-panes -a. capture_window_composited_with_cursor_with_deadline pays the same extra list-panes fork per frame.
  • Fix: Add Session::capture_pane_at(pane_id, lines) and have update_status_from_manifest/the legacy path pass metadata.pane_id; drop the exists() pre-check in capture (a failed capture-pane already maps to None). For the TUI preview, read pane_id from PANE_META_CACHE and fall back to first_pane_id only on miss or capture failure.
  • Verifier: exists() reads the SESSION_CACHE that was refreshed earlier in the same tick, so has-session rarely forks. The real waste is one extra list-panes -s fork per capture via first_pane_id_with_deadline, unless a VT channel exists. PaneMetadata.pane_id is the first window's pane 0, the same pane, so passing it in is safe. Keep the first_pane_id fallback for when metadata is missing.
  • Measure: Run the daemon with N streaming sessions and count tmux forks per tick (dtrace execsnoop / fs_usage filtering tmux) before and after.

#34 wait_until_ready sleeps 200ms before the first check, adding 200-400ms to every send

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area tmux, category latency
  • Where: src/tmux/session.rs:855-882, src/server/api/sessions/send.rs:181-184
  • Frequency: Per API/CLI message send to a terminal agent (send.rs, cli/session.rs).
  • Problem: The loop sleeps poll_interval before capturing, so even an already-ready pane waits 200ms; agents without a ready_marker (all but one) need two equal captures, so the minimum is about 400ms plus 2-3 forks per capture_pane(5).
  • Fix: Capture once before the first sleep and move std::thread::sleep to the end of the loop body, so a present marker returns immediately and the stable-capture path returns after one interval. Use the pane-id capture from the second finding to cut forks per iteration.
  • Verifier: session.rs:855-882 sleeps 200ms before every capture. Only one agent sets ready_marker (agents.rs:693, "ask anything"), so most sends wait at least 400ms because they need two equal captures. Called from send.rs:181 and cli/session.rs:1435. Capturing before the first sleep cuts this to 0ms with a marker and 200ms without, and keeps the semantics.
  • Measure: Time POST /api/sessions/{id}/send on an idle running claude session with tracing spans around wait_until_ready, before and after.

#35 macOS metrics sample forks about 8 processes per tick

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area process-daemon, category cpu
  • Where: src/process/macos.rs:1104-1121 (sample_memory), src/process/macos.rs:1123-1150 (sample_system), src/process/macos.rs:1152-1163 (process_snapshot), src/process/macos.rs:1228-1247 (sysctl_string, read_vm_stat), src/process/metrics.rs:203-252 (MetricsSampler::sample), src/tui/app.rs:1323, web/src/hooks/useSystemHealth.ts:6
  • Frequency: Once per second in the TUI while diagnostics or system health are shown. Every 500ms per web tab with the detail open, every 15s collapsed.
  • Problem: Each sample spawns sysctl three times, vm_stat, ps -A -o %cpu, and ps -axo with lstart, plus tmux list-panes. All of these values come from in-process APIs. ps -A runs twice, and lstart parsing is costly. On a busy host, the readout itself adds measurable CPU.
  • Fix: Replace sysctl_string/sysctl_u64 with libc::sysctlbyname (already used in boot_id). Replace vm_stat with host_statistics64(HOST_VM_INFO64). Take host CPU from host_processor_info deltas and drop the ps %cpu pass. Build process_snapshot from proc_listallpids plus proc_pidinfo(PROC_PIDTASKINFO) for RSS and CPU time, and use pbi_start_tvsec from PROC_PIDTBSDINFO for start_id.
  • Verifier: Each sample forks sysctl 4 times (memsize, pressure, loadavg, swapusage), plus vm_stat, ps %cpu, ps -axo lstart and tmux list-panes, so 8 forks. TUI samples every 1s only while diagnostics, health or tip is visible. Web has no server cache, so each tab with the detail open samples every 500ms. sysctlbyname is already used in the module.
  • Measure: Run sudo dtrace -n 'proc:::exec-success /ppid==$target/ {@[execname]=count()}' -p <aoe pid> for 10s with the health detail open.

#36 Served-read output (aoe list/ps/status) waits on a GitHub update check before printing

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area cli-startup, category latency
  • Where: src/cli/runtime_read/mod.rs:285-309, src/main.rs:437-440, src/update/mod.rs:119-230, src/update/mod.rs:365-378
  • Frequency: Every table-printing read command (list, ps and similar). Network cost whenever the 24h cache is stale, or on EVERY run while offline or rate-limited (failures are never cached).
  • Problem: finish() awaits update_notice() before returning the ReadOutcome, and main.rs only prints stdout after that. On a stale cache, check_for_update does list_releases (5s timeout, 20 releases with bodies) and then possibly latest_release (another 5s). Failure writes no cache, so offline users pay up to ~10s on every aoe list.
  • Fix: In finish(), return stdout first and run update_notice() under a ~300ms tokio::time::timeout, or print stdout before awaiting it. In check_for_update, save a negative cache (checked_at plus empty latest) on failure with a 1h retry gap. Fetch per_page=1..5 for the CLI path.
  • Verifier: finish() awaits update_notice() whenever projection.session_table, before main prints stdout. Default mode is Notify. On failure, check_for_update writes no cache: list_releases fails, then latest_release ? fails. So a blackholed or rate-limited network re-pays up to 2x5s on every aoe list. Offline DNS failures return fast, so worst case is narrower than claimed.
  • Measure: Make the cache stale or route api.github.com to a blackhole (pf/hosts), then compare time aoe list with update_check_mode=off.

#37 aoe ps spawns two tmux subprocesses per session for pane pid despite batched metadata

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area cli-startup, category subprocess
  • Where: src/cli/ps.rs:507-575, src/process/mod.rs:897-940, src/tmux/mod.rs:1434-1443
  • Frequency: Per aoe ps invocation, 2 x N tmux sessions (first_pane_id list-panes plus display-message), plus the unmatched-session loop.
  • Problem: collect_tmux_states already fetches batch_pane_metadata (which includes pane_pid and pane_dead for every pane), but then calls process::get_pane_pid(&name) for each session. That runs first_pane_id (a tmux list-panes) and then tmux display-message, so 30 sessions cost about 60 forks.
  • Fix: In collect_tmux_states use meta.get(&name).and_then(|m| (!m.pane_dead).then_some(m.pane_pid).flatten()) for both the instance loop and the unknown-session loop. Drop the get_pane_pid calls here.
  • Verifier: collect_tmux_states (ps.rs ~557, ~578) calls get_pane_pid per session: a first_pane_id tmux query plus a display-message. batch_pane_metadata already holds pane_pid and pane_dead for the first window's pane 0, the same pane. Reuse meta and keep the pid>0 and i32 filters.
  • Measure: With 30 sessions, run hyperfine 'aoe ps'. Count tmux forks with sudo dtrace -n 'proc:::exec-success /execname=="tmux"/{@=count()}' while it runs.

#38 Sandbox start/reuse issues 6 to 9 separate docker inspect subprocesses for one container

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area plugin-git-containers, category subprocess
  • Where: src/session/instance/container.rs:533, src/session/instance/container.rs:608, src/session/instance/container.rs:657, src/session/instance/container.rs:681, src/containers/runtime.rs:336, src/containers/runtime.rs:644, src/containers/runtime.rs:703
  • Frequency: Per sandboxed session start, restart, or reuse. Each docker CLI call is 50 to 300ms (more on Docker Desktop macOS), all serial.
  • Problem: exists(), agent_tool_matches, is_running, sandbox_store_generation_matches (twice), shared_credential_mounts_match, mount_fingerprint_matches, carries_shared_credential_label, id and workdir each spawn their own docker container inspect -f, then the same container is inspected again after start. Each also pays temp-file stdout/stderr setup in run_with_timeout.
  • Fix: Add one ContainerRuntime::inspect_labels_state(name) that runs docker container inspect once and returns Id, State.Running, Config.Labels and WorkingDir. Make label_matches and is_running read from that snapshot in the start path, and re-inspect only after a mutating call (create, start, remove).
  • Verifier: Running-reuse path issues exists, agent_tool_matches, is_running, sandbox_store_generation_matches, carries_shared_credential_label, identity mount check, id, workdir: about 8 serial inspect subprocesses per start. Fix must re-inspect after hooks too, because locks are released around run_hook and state can change there.
  • Measure: AOE debug log with timing on probe_output; count docker inspect calls via dtruss/strace -f -e execve during one sandboxed session restart.

#39 TUI compute_file_diff runs the similar Myers diff synchronously on the UI thread

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area plugin-git-containers, category latency
  • Where: src/git/diff.rs:308, src/git/diff.rs:325, src/git/diff.rs:430, src/tui/diff/mod.rs:256
  • Frequency: Per file selected in the TUI diff view (cache miss), on the render/input thread. Scales with file size and churn.
  • Problem: The server path switched to libgit2 xdiff because similar took about 20s on a +10k/-13k lockfile churn in debug (comment at diff.rs:431). compute_file_diff still uses TextDiff::from_lines and allocates a String per DiffLine. It reads the working file unbounded with no size cap, freezing the TUI on large files.
  • Fix: Build hunks in compute_file_diff from git2::Patch::from_buffers (as compute_file_contents does) via patch.hunk()/line_in_hunk. Move the call to a background task, or at minimum skip files over a size cap and show a placeholder.
  • Verifier: get_current_diff is called from tui/home/render.rs:1161 during draw. On a cache miss it runs TextDiff::from_lines, with no size cap and no deadline in read_file_state. The server path dropped similar for this reason (diff.rs:431). A size cap is an S-effort stopgap; moving the diff to libgit2 plus a background task is M.
  • Measure: Select a +10k/-13k lockfile in the release TUI diff view; time get_current_diff with a tracing span.

#40 Publish loop runs per-session SQLite queries on the writer connection, on a tokio worker, under the instances read lock

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area sweep-async-blocking, category latency
  • Where: src/server/runtime.rs:282-289, src/server/runtime.rs:787-802, src/server/api/sessions/list.rs:40-81, src/server/api/sessions/list.rs:105-118, src/server/api/sessions/list.rs:7-17, src/acp/event_store/turns.rs:127-134, src/acp/event_store/turns.rs:417-439, src/acp/event_store/wakeups.rs:13-80, src/acp/event_store/mod.rs:196-198
  • Frequency: Every publish: every 500ms with a subscriber (2s without), on each request_publish wake, and inline in about 78 mutation handlers that await runtime.publish. Scales with the number of live structured sessions.
  • Problem: project_sessions calls latest_plan, latest_pending_wakeup, latest_active_monitor (up to 4 queries) and pending_approval_requests (json_extract NOT IN subquery) for each structured session. It runs them synchronously on the async thread through self.conn(), the writer mutex that the event writer thread holds for every streamed event. Publishing and event persistence block each other. Both instances.read() and publication.read() stay held for the whole time.
  • Fix: Serve current_plan and pending_approvals from acp_control_cache, because AcpState already folds them (state.rs current_plan, pending_approvals). Move the wakeup and monitor lookups into the existing park_probes spawn_blocking batch (list.rs:338) and run them on self.reader(), not self.conn(). One batched query over all session ids can replace the per-session queries.
  • Verifier: list.rs:52-117 calls latest_plan, latest_pending_wakeup, latest_active_monitor (up to 4 queries) and pending_approval_requests per live structured session. All use self.conn(), the writer mutex, synchronously under instances.read() and publication.read(). Queries hit the (session_id, discriminant, seq) index, so each is cheap; the cost is N x ~6 per 500ms. ControlStateCache only hydrates on demand, so the fix must hydrate first.
  • Measure: Wrap project_sessions' map closure in a tracing span with elapsed time; run 30 structured sessions with the dashboard open and log p50/p99 per publish.

#41 Publish loop re-resolves config TOML and opens git repos synchronously on every publish

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area sweep-async-blocking, category latency
  • Where: src/server/api/sessions/list.rs:41, src/server/api/sessions/list.rs:96-104, src/server/api/sessions/list.rs:121-169, src/server/api/sessions/list.rs:207-219, src/server/api/sessions/list.rs:270-289, src/server/api/sessions/list.rs:436-442, src/server/api/sessions/model.rs:420-460, src/session/config/repo_config/mod.rs:284-306, src/claude_settings.rs:16-30
  • Frequency: Every publish (500ms with subscribers, 2s otherwise, and inline in each mutating request). Scales with the number of distinct (profile, project) pairs and profiles.
  • Problem: Each project_sessions call does the following on the runtime thread under instances.read(). It reads ~/.claude/settings.json. It creates a fresh SessionCfgCache, so each pair re-reads config.toml, the profile and the repo config, and runs GitWorktree::find_main_repo (libgit2) twice. It also calls resume_profile_config per profile and resolve_config_or_warn per profile for tie_workdir without caching. A first remote-owner miss opens libgit2 under remote_owner_cache.write().
  • Fix: Hoist SessionCfgCache, resume configs and the tie_workdir_to_name map to AppState, keyed like cleanup_defaults_cache. Invalidate them through the existing config_watch or file_watch on config.toml, profile and repo config changes, not per call. Cache read_tui_fullscreen behind the same watch. Run the uncached remote-owner resolution in spawn_blocking, then insert it under the write lock.
  • Verifier: Nothing caches across calls. Each call creates a fresh SessionCfgCache (list.rs:131) and resume_configs/tie_cache maps. read_tui_fullscreen reads the file every time. A miss calls find_main_repo twice (source(), then inside resolve_config_with_repo). The server has no config_watch, so use a TTL like cleanup_defaults_cache, or file_watch.
  • Measure: Log list_sessions_resolver_misses delta and elapsed time per publish (trace already exists at list.rs:290) with 20 projects across 3 profiles.

#42 publish_loop rebuilds the full session projection every 2s (500ms with subscribers), on the async runtime

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area sweep-timers-polling, category cpu
  • Where: src/server/runtime.rs:786, src/server/runtime.rs:288, src/server/api/sessions/list.rs:42, src/server/api/sessions/list.rs:56, src/claude_settings.rs:16
  • Frequency: Every 2s with no clients, every 500ms with runtime WS subscribers. status_poll_loop also publishes on each tick. Scales with the session count.
  • Problem: publish_loop already wakes on runtime.wake, but it also sleeps on a timer and then calls publish(). Each publish runs project_sessions on a tokio worker thread: blocking SQLite queries per structured session, fs::read_to_string plus a JSON parse of the Claude settings file, and resume_profile_config disk reads. The dedup in publish only compares results after all of that work is done.
  • Fix: Remove the periodic sleep arm in publish_loop and rely on request_publish() from mutation paths, keeping a long safety period such as 30s. Run project_sessions inside spawn_blocking. Cache read_tui_fullscreen behind the FileWatchService instead of reading the file on every publish.
  • Verifier: project_sessions runs sync SQLite (latest_plan, wakeup, monitor, approvals) and reads/parses ~/.claude/settings.json on a tokio worker. publish_loop and status_poll each publish every tick. Do not remove the timer: ACP event-store writes (plans, approvals, wakeups) are not wired to request_publish (acp_events.rs:688 fires only on canonical_changed). spawn_blocking and caching the settings file are safe wins.
  • Measure: Wrap project_sessions in an Instant timer with a trace log. Run with 50 structured sessions and an open dashboard, then read the p50/p99 per publish.

#43 Hooked agents bypass the window_activity capture skip, so every status tick runs capture-pane

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area sweep-timers-polling, category subprocess
  • Where: src/session/instance/status_update.rs:19, src/session/instance/status_update.rs:550, src/session/instance/status_update.rs:568, src/tmux/session.rs:833
  • Frequency: Each status_poll tick (2s, or 500ms with runtime subscribers), once per tmux session that has a hook file (Claude Code installs hooks).
  • Problem: skip_capture returns false whenever has_hook is true. A session with a hook file is captured every tick even when window_activity has not changed and the hook status is the same. Each capture spawns tmux capture-pane (plus a pane-target lookup when the vt channel is absent). Idle Claude sessions stay idle for hours, so N sessions cost N subprocesses per tick.
  • Fix: In update_status_from_manifest, put the hook (status, age bucket or mtime) into observation_key, or pass the previous hook observation to skip_capture. Then replace the blanket !has_hook with "hook unchanged since the last capture".
  • Verifier: skip_capture requires !has_hook (status_update.rs:33). A Claude session with any hook file runs capture-pane each tick, plus a live_pane_target lookup in capture() (session.rs:833). Hook rules depend only on status and the age thresholds 30s/900s (manifest.rs:423,435). A key of status plus age bucket is safe.
  • Measure: With 10 idle hooked Claude sessions, count tmux execs for 60s, e.g. sudo execsnoop | grep capture-pane | wc -l, before and after the change.

#44 Web ACP socket rebuilds and re-serializes full control state on every event, per connection

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area sweep-alloc-serde, category cpu
  • Where: src/server/acp_ws.rs:222-263, src/server/acp_ws.rs:482-503, src/server/acp_ws.rs:507-520, src/server/acp_ws.rs:524-549
  • Frequency: Per ACP event (every message/thought chunk, tool update) per connected web or TUI client; scales with event rate, client count, and size of recent_diffs/available_commands/config_options/background_agents.
  • Problem: Each frame clones the Event, folds it into a per-connection AcpState, then send_reduced_state does serde_json::to_value(whole AcpState), runs to_string() on 5 cold fields just to hash them, wraps in json!, and to_string() again. Chunk events never change most of that state, yet a reduced_state frame is always sent beside the raw frame and the transcript_delta.
  • Fix: In the recv arm, compare a cheap revision (e.g. a state version counter bumped by AcpState::apply_event only when a field changes) and skip send_reduced_state when unchanged. Hash cold fields via a hasher-writing serde Serializer or a per-field dirty bit rather than Value::to_string. Serialize a typed struct directly, not Value then json!.
  • Verifier: The per-event to_value of the whole AcpState and the to_string of the cold fields happen as claimed (acp_ws.rs:241-243, 482-549). ColdFieldCache already strips unchanged cold fields from the wire, so the bandwidth cost is handled. recent_diffs is capped at 16 (state.rs:1067). The remaining cost is CPU per chunk per connection. Before skipping frames on an unchanged revision, check whether the client relies on reduced_state.seq.
  • Measure: Wrap send_reduced_state in a tracing span with elapsed micros. Stream a long Claude turn with 3 web tabs open and sum the time per second.

#45 Daemon status tick forks twice per captured session, and the extra fork is redundant

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area sweep-subprocess, category subprocess
  • Where: src/tmux/session.rs:822-851, src/tmux/session.rs:1274-1284, src/tmux/utils.rs:323-350, src/session/instance/status_update.rs:572-580, src/session/instance/status_update.rs:356, src/server/reload.rs:872-898, src/server/status_poll.rs:470-530
  • Frequency: Every status tick (2s, 500ms with terminal subscribers), once per session whose window_activity changed. Scales with Running session count.
  • Problem: Session::capture calls live_pane_target_with_deadline, which forks tmux list-panes -s to find the first pane id, then forks capture-pane. PaneMetadata from the same tick's list-panes -a already holds that pane_id. The loop is serial inside one spawn_blocking, so N running agents cost 2N sequential forks per tick.
  • Fix: Add Session::capture_pane_by_id(pane_id, lines) and pass metadata.pane_id from update_status_from_manifest. Optionally chain all due captures into one tmux invocation with ; and display-message -p delimiters, as capture_pane_with_cursor_with_deadline already does for its header/capture pair.
  • Verifier: Session::capture (session.rs:833) runs has-session from cache, then list-panes -s through first_pane_id_with_deadline, then capture-pane. PaneMetadata.pane_id is window 0 pane 0 from the same tick's list-panes -a. The loop runs serially in one spawn_blocking (status_poll.rs:508). A VT channel skips the lookup only for web-attached sessions.
  • Measure: Count forks via the fork_probe test hook, or run dtrace -n 'proc:::exec-success /execname=="tmux"/' over 60s with 10 busy sessions.

#46 WS connect and lag rebuild load a session's entire event history into one Vec

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area sweep-memory, category memory
  • Where: src/server/acp_ws.rs:346-372, src/server/acp_ws.rs:271-287, src/server/acp_ws.rs:438-460, src/acp/event_store/replay.rs:38-40, src/server/session_service.rs:1922-1931, src/server/session_service.rs:1950-1962
  • Frequency: Every /acp/ws connect and reconnect (web tab open, network blip, TUI open), every broadcast Lagged event, every cold fold_control_state hydrate, and every sidebar_status_at call. Scales with total events per session, which retention leaves unlimited by default.
  • Problem: replay_from(id, 0) deserializes every stored event into one Vec<(u64, Event)> before folding, even when since is recent (deliberate, because folds need prior state). At 100k events with tool outputs, peak memory is hundreds of MB per connect, and several concurrent tabs or a reconnect storm multiply it.
  • Fix: Add EventStore::for_each_from(session, since, batch, FnMut(u64, Event)) that loops replay_page(limit=1000) on last_scanned_seq. Use it in drain_replay_into_socket, the Lagged rebuild, fold_control_state hydrate and sidebar_status_at. fold_connect_history then streams, and to_forward is sent per batch.
  • Verifier: Confirmed: connect (acp_ws.rs:346-372) and Lagged rebuild (271-287) call replay_from(id,0) into one Vec. Overstated: fold_control_state goes through acp_control_cache.get_or_hydrate, so it runs only on a cold cache. sidebar_status_at runs only for frames published while the cache was cold. Peak memory also depends on retention, which defaults to unlimited.
  • Measure: Peak RSS of aoe serve while opening 5 /acp/ws connections to a 100k-event session (heaptrack or /usr/bin/time -l).

#47 Each WS connection re-serializes the whole control state on every event

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area sweep-memory, category cpu
  • Where: src/server/acp_ws.rs:223-230, src/server/acp_ws.rs:482-503, src/server/acp_ws.rs:505-550
  • Frequency: Every broadcast event (including each AgentMessageChunk), on every open /acp/ws connection for that session.
  • Problem: send_reduced_state runs serde_json::to_value on the whole AcpState and drops background_agents for the web after serializing it. strip_unchanged then calls value.to_string() on every cold field to hash it, and the frame is serialized again. A message chunk changes no control state, yet it pays the full state serialization several times.
  • Fix: Have AcpState::apply_event return whether control state changed. Skip send_reduced_state for events that do not change it (message and thought chunks, ToolCallContent). In project_control_state, skip serializing background_agents for Web with a projection struct or #[serde(skip)] wrapper, not by removing it after serialization.
  • Verifier: acp_ws.rs:241-245 calls send_reduced_state on every frame, including AgentMessageChunk, which only changes the skip-serialized sidebar_phase plus last_seq and updated_at. project_control_state (507) serializes the full state, then removes background_agents for Web. strip_unchanged (486) runs to_string on 5 cold fields, then serializes the frame again. Cost is per connection per chunk.
  • Measure: Add a tracing span timing send_reduced_state; stream a long turn with 3 tabs open and compare total time per chunk before and after.

#48 Server sends a full reduced_state snapshot on every chunk per WS connection although chunks do not change it

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area trace-acp-stream, category cpu
  • Where: src/server/acp_ws.rs:228-235, src/server/acp_ws.rs:478-509, src/server/acp_ws.rs:522-554, src/acp/state.rs:1472, src/acp/state.rs:1482-1483
  • Frequency: Per chunk x per connected WS client of that session (web tabs + TUI)
  • Problem: After each frame the handler serializes the entire AcpState to a Value, re-serializes 5 cold fields to strings to hash them, then serializes the frame again and sends it. For AgentMessageChunk the fold only touches sidebar_phase (serde skip), last_seq and updated_at, so the client gets an identical snapshot every token, then re-runs applyReducedState and re-renders.
  • Fix: In handle(), skip send_reduced_state when the event is AgentMessageChunk, ToolCallContent, RawAgentUpdate or another arm that only touches non-projected fields (add fn projects_control_state(&Event) -> bool next to AcpState::apply_event). Clients already take seq from frames/deltas.
  • Verifier: Claim holds: AgentMessageChunk only sets serde-skipped sidebar_phase plus last_seq/updated_at, yet acp_ws.rs:243 serializes and sends a full snapshot per frame per client. But the TUI uses reduced_state seq as its reconnect since cursor (structured_view/reducer.rs:124,329), so the fix must also advance TUI last_seq from transcript_delta. AgentThoughtChunk changes thinking; exclude it.
  • Measure: Count reduced_state bytes per streamed turn with a WS logger (websocat) on /acp ws; time send_reduced_state with a tracing span under a streaming session.

#49 Each chunk yields three WS messages and three separate React dispatches/renders with no frame coalescing

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area trace-acp-stream, category render
  • Where: web/src/hooks/acpSession/useAcpConnection.ts:281-330, web/src/hooks/acpSession/useAcpConnection.ts:399-407, web/src/lib/acpTypes.ts:1125-1129, src/server/acp_ws.rs:213-251
  • Frequency: Per chunk; tens to hundreds per second while an agent streams
  • Problem: ws.onmessage dispatches immediately, so raw frame, reduced_state and transcript_delta each run the reducer and a full render pass in separate tasks. The raw AgentMessageChunk frame only bumps lastSeq for the web (applyEvent returns a new object), yet still costs a parse, a state object and a render.
  • Fix: Buffer parsed messages in useAcpConnection and flush once per requestAnimationFrame as a single {kind:"batch", actions} Action reduced in one pass. Server side, skip forwarding raw AgentMessageChunk/AgentThoughtChunk frames for projection=web and set lastSeq from the transcript_delta seq.
  • Verifier: Three messages per chunk confirmed (frame, reduced_state, transcript_delta). React 19 batches DefaultLane updates until its scheduler task runs, so back-to-back onmessage tasks may already coalesce into one render; actual render count is unproven. Dropping raw AgentThoughtChunk frames for web is unsafe: applyEvent sets turnActive from it. No rAF batching or memo exists in components/acp.
  • Measure: React Profiler commit count vs chunk count during a streamed reply; compare commits per second before and after rAF batching.

#50 TranscriptModel creates one row per token chunk, inflating memory, snapshots and every downstream O(rows) loop

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area trace-acp-stream, category memory
  • Where: src/acp/transcript.rs:315-331, src/acp/transcript.rs:890-894, src/acp/transcript.rs:169-200
  • Frequency: Per chunk per WS connection (each connection owns a TranscriptModel), plus connect snapshots and ?view=rows replays
  • Problem: Each AgentMessageChunk appends a TranscriptRow (~hundreds of bytes plus id/group strings) and clones it into the delta; row_ids grows too. A long session holds tens of thousands of rows per connection, snapshots resend them all, and web/TUI concat them back per render.
  • Fix: Coalesce consecutive chunks of the open message group into one row: keep the row index of open_message_group and append text in place, emitting a new TranscriptDelta::AppendText { id, text } (web and TUI append to that row). Keep message_start semantics by starting a new row on message id change.
  • Verifier: apply_event (transcript.rs:325-336) builds a new msg-{seq} row per AgentMessageChunk; append (890) clones it into rows and the delta. replay_events defaults to 0 (unlimited) and connect replay reads from seq 0, so rows grow without bound. Fix changes the row/delta wire contract for web, TUI and ?view=rows.
  • Measure: Count rows vs message groups in a long session: curl the ?view=rows endpoint and compare rows.length to distinct group_id count and JSON bytes.

#51 TUI upsert_transcript_row scans all rows for every appended chunk

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area trace-acp-stream, category cpu
  • Where: src/tui/structured_view/reducer.rs:266-271, src/acp/transcript.rs:1030-1046
  • Frequency: Per chunk in the TUI
  • Problem: Append deltas go through upsert_transcript_row, which does rows.iter().position by string id over the whole server_rows vec before pushing. Ids of live appends are almost always new, so it scans everything each token.
  • Fix: In AcpTranscript keep a HashMap<String, usize> id index (or check the last row id first and skip the scan when the incoming msg-/thought- seq is greater than the tail's), falling back to position only for snapshot merges.
  • Verifier: Claim holds (transcript.rs:1030 position scan; daemon emits one msg-{seq} row per chunk, server_rows uncapped). Per-chunk cost is a short id compare per row, small. Bigger waste: merge_server_rows and replay_rows_paged (http.rs:345) upsert row by row, O(n^2) on open, reconnect and lag reseed. Daemon already keeps a row_ids HashSet; mirror it with a HashMap index.
  • Measure: Unit bench: merge_server_rows with 50k msg rows into empty TranscriptState, time with std::time::Instant before and after index.

#52 Web rebuilds every assistant message in the window per chunk, and the window grows with each chunk

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area trace-acp-stream, category render
  • Where: web/src/components/acp/AcpRuntime.tsx:171-205, web/src/components/acp/activityMessages.ts:45-180, web/src/hooks/useHistoryWindow.ts:36-44, web/src/components/acp/StructuredView.tsx:223
  • Frequency: Per activity change (per chunk)
  • Problem: activityToThreadMessages re-walks all windowed rows, re-concatenates message text, re-JSON.stringifies tool args and re-parses them in collapseSubagents/argString, producing new objects for every message so assistant-ui re-renders them. useHistoryWindow grows visibleRows by each appended row (extra setState render), and lastClearIndex/pinnedWindowStart scan all rows each render.
  • Fix: Memoize built messages per completed turn (cache keyed by turn's first row id and row count; only rebuild the tail turn), parse tool argsText once per part. Combined with chunk coalescing into one row, the window stops growing per token.
  • Verifier: Confirmed: each WS chunk dispatches separately, activityToThreadMessages rebuilds all windowed messages and re-stringifies tool args. Window growth per append is deliberate (#3707), so the fix cannot stop it; the setState runs in render and is cheap. Missed cost: mergeServerRows (acpTypes.ts:965) rebuilds an id Map over all activity and slices the array per chunk.
  • Measure: React Profiler on a 2k-row session while streaming: commit duration and render count of AcpRuntime and message components per transcript_delta.

#53 Snapshot transport (paired shells, pipe_owned fallback) forks tmux twice every 50ms even when the pane is idle

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area trace-terminal-stream, category subprocess
  • Where: src/server/live_ws.rs:128, src/server/live_ws.rs:1217, src/tmux/session.rs:939, src/tmux/utils.rs:323, src/server/live_ws.rs:2007
  • Frequency: Per visible paired host/container shell tab and per agent viewer on the capture fallback: every 50ms (20 samples/s, 40 forks/s), 250ms when idle cadence
  • Problem: Each capture_window_composited_with_cursor call runs first_pane_id_with_deadline (a list-panes fork) and then a chained display/capture fork. There is no dirty signal, so an idle shell keeps forking 40 times a second and capturing the whole window just to dedup it. The doc comment says the single-pane path is 'one fork', but the list-panes probe makes it two.
  • Fix: Cache the pane0 id per connection in handle_live_ws_inner and pass it into a capture_window_composited_with_cursor variant. Re-resolve it only when a capture fails. Then gate captures on output: add a chunk counter to Osc52Channel (already armed on shells), or check #{window_activity} in the chained probe, and skip capture-pane when nothing changed.
  • Verifier: Confirmed: session.rs:939 forks list-panes, then a chained display/capture/display fork, every 50ms on paired shells (always Snapshot). Caching pane0 halves the forks. The window_activity gate still needs a fork, so it saves only bytes. Osc52Channel exists only when clipboard forwarding is on, so the dirty signal is not universal.
  • Measure: Open a paired shell tab with an idle prompt and count tmux execs per second with sudo execsnoop -n tmux before and after the pane-id cache.

#54 Hooked sessions capture the pane every tick: skip_capture is disabled whenever a hook file exists

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area trace-status-list, category subprocess
  • Where: src/session/instance/status_update.rs:19-36, src/session/instance/status_update.rs:311-315, src/session/instance/status_update.rs:441-471, src/server/status_poll.rs:458-466
  • Frequency: Every daemon status tick (500ms when a runtime WS subscriber such as the TUI is connected, 2s otherwise), for every live terminal session whose agent writes a hook status file (Claude, Codex, and others). Scales linearly with N.
  • Problem: skip_capture returns false when has_hook, so window_activity and the observation key cannot short-circuit the capture. Every hooked session runs tmux capture-pane, strip_ansi, and the regex manifest on every tick, even when the screen and the hook are unchanged. At N=300 with the TUI attached, that is about 600 captures/s. Each capture is 2 forks (next finding). This hides the activity-based skip the code was designed to give.
  • Fix: Store a hook fingerprint (status and mtime) in DetectionState. In skip_capture, replace !has_hook with 'fingerprint unchanged and hook age has not crossed the manifest's freshness bound since captured_at'. Pass the HookObservation and the plan's bound into skip_capture. The hook write that changes the verdict still forces a capture.
  • Verifier: skip_capture has && !has_hook (status_update.rs:33); update_status_from_manifest passes hook.is_some() (line 553). A persistent hook file means every idle hooked pane is captured, stripped and matched each tick. Fix must respect hook age freshness, which the observation_key does not encode. Real win scales with N; N=300 is atypical.
  • Measure: Count tmux execs per tick: sudo dtrace -n 'proc:::exec-success /execname=="tmux"/ {@=count()}' over 10s with 20 idle Claude sessions, before and after.

#55 Every pane capture forks an extra list-panes to resolve a pane id the batch metadata already has

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area trace-status-list, category subprocess
  • Where: src/tmux/session.rs:837-855, src/tmux/session.rs:1274-1284, src/tmux/utils.rs:288-295, src/tmux/mod.rs:324-345
  • Frequency: Once per capture: every tick for every captured session (see above), plus the error and explain paths. Linear in N.
  • Problem: Session::capture calls exists() and then live_pane_target_with_deadline. Without a live VT channel (most sessions), that runs first_pane_id_with_deadline, which forks tmux list-panes, before the capture-pane fork. PaneMetadata from the tick's single list-panes -a already carries pane_id. So each capture costs 2 forks instead of 1: about 1200 forks/s at N=300 and 200 forks/s at N=50.
  • Fix: Add Session::capture_pane_at(pane_id: &str, lines) and use it from update_status_from_manifest and the legacy path when metadata.pane_id is non-empty. This skips both exists() and the list-panes fork. Keep the current path as the fallback when metadata is None.
  • Verifier: Session::capture (session.rs:833) calls live_pane_target_with_deadline, which forks first_pane_id (list-panes) unless a VT channel exists. exists() uses the per-tick session cache, so no fork there. PaneMetadata.pane_id comes from first window, pane index 0 (mod.rs batch_pane_metadata), same pane. Halves capture forks.
  • Measure: dtrace or fs_usage -f exec count of tmux list-panes -t invocations per status tick with N terminal sessions, before and after.

#56 project_sessions (full O(N) projection with config, git, and SQLite) runs 3 to 6 times per second, mostly to find no change

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area trace-status-list, category cpu
  • Where: src/server/runtime.rs:278-345, src/server/runtime.rs:787-803, src/server/status_poll.rs:612, src/server/reload.rs:1418, src/server/api/sessions/list.rs:40-520
  • Frequency: With a runtime subscriber: the status_poll_loop publish every 500ms, a publish_loop wake from request_publish in the same tick, and the publish_loop 500ms timer. Plus get_runtime_info/snapshot and every mutation response. Each call is O(N).
  • Problem: NativeRuntime::publish always rebuilds every SessionResponse through project_sessions before it compares with the previous snapshot. One tick publishes twice: a direct call, then the request_publish wake. The publish_loop also fires on its own 500ms timer when nothing changed. The comment at list.rs:132 still assumes a '3s sidebar poll', but this now runs on the publish cadence.
  • Fix: Add an AtomicU64 projection_generation to AppState and bump it whenever instances, metadata, the worker state, or the event-store overlays change. publish returns the previous snapshot when both the generation and mutation_epoch are unchanged. Remove the publish_loop timer arm, or keep it at 30s as a safety net. Drop the redundant request_publish when the caller publishes directly.
  • Verifier: Each tick publishes directly (status_poll.rs:624) after reload_state_instances_from_disk already called request_publish (reload.rs:1418), so publish_loop reruns immediately; plus its 500ms timer. project_sessions rereads claude settings, resume configs, resolve_config_or_warn per profile, SQLite overlays. A generation counter is unsafe: overlays read disk config and SQLite outside AppState. Drop the duplicate wake and timer first.
  • Measure: Add a counter plus elapsed tracing in NativeRuntime::publish; log publishes/s and mean duration with TUI attached and 50 idle sessions.

#57 project_sessions re-resolves config, git main-repo discovery and canonicalize on every call

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area trace-status-list, category disk-io
  • Where: src/server/api/sessions/list.rs:96-104, src/server/api/sessions/list.rs:134-163, src/server/api/sessions/list.rs:200-216, src/server/api/sessions/list.rs:263-290, src/server/api/sessions/list.rs:343-366, src/server/api/sessions/model.rs:431-462, src/server/api/sessions/model.rs:487-505, src/session/config/repo_config/mod.rs:284-320, src/session/instance/mod.rs:131-143
  • Frequency: Every project_sessions call (3 to 6/s, see previous finding). Scales with distinct profiles, distinct project paths, and N for canonicalize.
  • Problem: Each call builds a fresh SessionCfgCache and ProjectRegistryCache. Per call it does: resolve_config per profile for resume, the tie overlay, and park probes. Per distinct project path it does repo_config_source_path (.git stat plus GitWorktree::find_main_repo), then resolve_config_with_repo_or_warn (a second repo discovery plus a full config parse). canonical_key does a realpath per session. read_tui_fullscreen reads ~/.claude/settings.json. Every resolve also reinstalls the status rules.
  • Fix: Move SessionCfgCache, ProjectRegistryCache, the resume configs, and the repo-source map onto AppState. Invalidate them on the config file_watch events that the TUI ConfigWatchState already subscribes to, or on file stamps. Cache read_tui_fullscreen by mtime. Memoize canonical_key per project_path.
  • Verifier: project_sessions runs on every publish (publish_loop 500ms with subscribers, status_poll 500ms tick, WS changes, request_publish). Only cleanup defaults use an AppState TTL cache. resolve_config rereads config.toml, state.toml, profile toml, typechecks overrides, reinstalls status rules, 3+ times per profile per call. find_main_repo is cheap (gitfile read). Comment at list.rs:134 still says 3s poll.
  • Measure: Add a tracing span around project_sessions and log resolver_misses plus elapsed; run aoe serve with 2 dashboard tabs and 50 sessions across 5 profiles.

#58 SQLite queries and JSON decodes per structured session on every projection

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area trace-status-list, category cpu
  • Where: src/server/api/sessions/list.rs:55-80, src/server/api/sessions/list.rs:106-121, src/acp/event_store/turns.rs:127-134, src/acp/event_store/turns.rs:417-442, src/acp/event_store/wakeups.rs:13-80
  • Frequency: Every project_sessions call (3 to 6/s) times the number of live structured sessions.
  • Problem: For each structured row, project_sessions calls latest_plan (query plus a full Plan JSON decode), latest_pending_wakeup, latest_active_monitor (up to 3 queries), and pending_approval_requests. pending_approval_requests runs a json_extract NOT IN subquery over all ApprovalResolved rows. These run synchronously on a tokio worker while state.instances is read-locked, and they serialize on the event-store connection. N=300 structured is about 1,500 queries per call and several thousand per second.
  • Fix: Keep an in-memory SessionOverlay { plan_summary, next_wakeup, active_monitor, pending_approvals } per session in AcpEventStore. Update it when the append path writes PlanUpdated, WakeupScheduled, MonitorArmed, ApprovalRequested, or ApprovalResolved, and seed it once at startup. project_sessions reads the overlay map.
  • Verifier: Queries are real and per structured row per publish, but each is an indexed point lookup on (session_id, discriminant, seq); approvals only run for Running workers; wakeup/monitor skip archived. Real cost is use of the write conn() mutex (contends with streaming appends) under the instances read lock. Cheaper fix: read_conn plus prepare_cached, or spawn_blocking, before an overlay cache.
  • Measure: Time the map closure in project_sessions with 100 structured sessions while 5 sessions stream; also log conn() mutex wait time in EventStore.

#59 Status WebSocket runs a full runtime publish for every status change on every connection

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area trace-status-list, category latency
  • Where: src/server/session_status_ws.rs:204-212, src/server/session_status_ws.rs:104-112, src/server/reload.rs:1419-1422
  • Frequency: Per StatusChange broadcast times per open dashboard tab. A tick with C transitions and K tabs gives C*K publishes.
  • Problem: Next::Change awaits state.runtime.publish for each change so that the frame's cursor covers the move. Each publish rebuilds project_sessions (O(N) with config, git, and SQLite) under publish_lane. A burst of 30 transitions with 2 tabs is 60 serialized full projections, which delays the frames and blocks other publishers. frame_for then does a linear find over N rows per change.
  • Fix: Publish once in status_poll_loop before broadcasting. Make reload_state_instances_from_disk return the changes, and have status_poll_loop send them only after runtime.publish, with the published cursor attached to StatusChange. The WS handler then builds the frame from change.cursor and change.new without calling publish.
  • Verifier: reload.rs:1424 broadcasts each change, then each WS serve loop awaits runtime.publish per change (session_status_ws.rs:205), each a full project_sessions under publish_lane, before status_poll.rs:624 publishes too. C*K recomputes confirmed; typical C and K are small. Simpler fix: drain queued changes with try_recv and publish once per batch.
  • Measure: Count publish calls per status_poll tick via a counter in NativeRuntime::publish with 2 tabs and 20 terminal sessions toggling Running/Idle.

#60 Passive status transitions rewrite and fsync the whole sessions.json, which echoes into full reloads in daemon and TUI

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area trace-status-list, category disk-io
  • Where: src/server/status_poll.rs:85-163, src/session/storage.rs:2586-2625, src/server/disk_watch.rs:264-330, src/tui/app.rs:1418-1450, src/tui/home/lifecycle.rs:460-483, src/tui/home/status.rs:445-475
  • Frequency: Every tick that has any terminal-session transition, per affected profile. At N=300, almost every 500ms tick has one.
  • Problem: flush_passive_transition_writes serializes all N rows with to_vec_pretty and does an atomic replace with sync_all (F_FULLFSYNC on macOS). notify_local_change then wakes disk_watcher_consumer, which runs an uncached load_profiles_for_reload of every profile for changes it already holds in memory. It also sets the TUI disk_watch dirty latch, so the TUI runs reload_storage_only on its UI thread: an uncached load_complete_with_groups, duplicate_reports, and a subscription rewire.
  • Fix: Coalesce PassiveStatusPatch writes in a daemon buffer and flush every 5s and on shutdown. Lifecycle commits stay immediate. Use serde_json::to_vec for this path. Tag self-originated writes, for example by recording the written DataFileStamp, so disk_watcher_consumer skips matching events. In the TUI, ignore disk_watch.dirty while sidebar_source is Daemon.
  • Verifier: Confirmed: passive patches rewrite whole sessions.json with to_vec_pretty plus sync_all (F_FULLFSYNC on macOS) while holding the publication write guard; notify_local_change wakes disk_watcher_consumer (75ms debounce) for an uncached all-profile reload; TUI Daemon mode reload_storage_only calls load_complete_with_groups. Only terminal-session transitions trigger it, so 'almost every tick' needs many terminal sessions. 5s coalescing trades durability; self-write echo suppression is the safer win.
  • Measure: Log elapsed of flush_passive_transition_writes and disk_watcher_consumer latency_us trace with 30 terminal sessions cycling status for 5 minutes.

#61 Runtime WS sends the full N-session snapshot per revision, and the TUI rebuilds everything on its UI thread

  • Impact medium, effort L, verdict partly, evidence plausible-needs-measurement, area trace-status-list, category network
  • Where: src/server/runtime.rs:330-345, src/server/runtime.rs:750-756, src/tui/home/status.rs:445-694, src/tui/home/status.rs:800-850, src/tui/home/lifecycle.rs:580-612, src/tui/home/projects.rs:15-32
  • Frequency: Every snapshot revision. With many active sessions, that is about every 500ms tick. Scales with N times the row size (93-field SessionResponse, about 2 to 3KB of JSON).
  • Problem: Any field change on any session sends a full RuntimeFrame::Snapshot, about 1MB at N=300. The TUI parses it, then on the UI thread: clones every Instance, parses 8 RFC3339 stamps per row, clones rows again per profile for GroupTree, reads workspace_ordering and the projects files (refresh_registered_projects canonicalizes each project), and rebuilds flat items from cloned instances. Keystroke latency grows with N.
  • Fix: Add RuntimeFrame::Delta { cursor, upserts: Vec, removed: Vec } computed by diffing the previous published sessions by id in publish. In the TUI, patch only changed rows in apply_canonical_projection. Skip refresh_registered_projects and load_workspace_ordering unless profiles or workspace_ordering changed.
  • Verifier: publish() (runtime.rs:322-328) skips publishing when contents are unchanged, and SessionResponse has no per-tick fields like activity time. So frames go out only on real changes, not every 500ms. The full rebuild per change is real (status.rs:445-694): clones, 8 RFC3339 parses per row, GroupTree row clones, sync load_workspace_ordering (status.rs:~810) and refresh_registered_projects. Skipping those disk reads is an S-sized partial fix.
  • Measure: Count published revisions per minute (log revision in publish) and time apply_canonical_projection with tracing spans at N=300 sessions.

#62 Web sessions poll replaces every row object every 3s, even on unchanged 304 responses

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area trace-status-list, category render
  • Where: web/src/hooks/useSessions.ts:96-157, web/src/hooks/useSessions.ts:263-283, web/src/lib/api.ts:224-235
  • Frequency: Every 3s per dashboard tab, regardless of change. Scales with N.
  • Problem: With no-cache, a 304 reaches fetch as a 200 carrying the cached body, so res.json() re-parses into new objects. applyResult rejects only revision < floor. An equal revision still rebuilds rowById, observedById, and the sessions array, and setWorkspaceOrdering receives a new array. So useWorkspaces, all grouping builds, and every row re-render every 3s even when nothing changed. Any real change sends the full list.
  • Fix: In applyResult, return early when the cursor's epoch and revision equal floorGet.current, after updating the trash count. In setState, reuse the previous row object when its fields are equal (shallow compare) and keep the previous array when no row changed. Call setWorkspaceOrdering only when the ordering differs.
  • Verifier: applyResult only rejects revision < floor (useSessions.ts:97). An equal revision still rebuilds rowById, observedById and the sessions array, and setWorkspaceOrdering gets a new array. res.json() re-parses the 304-revalidated body (api.ts:226). The early return must still prune the pushed map and keep the absent/seen bookkeeping right.
  • Measure: React Profiler: record 30s idle dashboard with 200 sessions; count SessionRow commits per poll before and after the equal-revision early return.

#63 Sidebar row memoization defeated: every status push re-renders all N rows

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area trace-status-list, category render
  • Where: web/src/components/WorkspaceSidebar.tsx:231-270, web/src/components/sidebar/SessionRow.tsx:49, web/src/components/sidebar/useSessionRowModel.ts:17-41, web/src/hooks/useWorkspaces.ts:13-56, web/src/lib/sidebarGroups.ts:140-160, web/src/components/sidebar/GroupLists.tsx:79-101
  • Frequency: Every pushed status, mutation receipt, and list poll. Each one re-renders N SessionRow and dnd-kit useSortable instances.
  • Problem: rowProps passes observedById, a record rebuilt on every applyResult and mutation, to every SessionRow. useSessionRowModel never reads it, so it only busts memo. useWorkspaces and the build*Groups slices create new Workspace objects for all workspaces when one session changes. GroupHeader receives a fresh {...full} object and inline callbacks, so the SidebarGroupHeader memo never hits either.
  • Fix: Remove observedById from SessionRowProps and RowObservation (SessionActionProvider already holds it in a ref). In useWorkspaces, keep a ref Map of id to Workspace and reuse the old object when its sessions are reference-equal; apply the same reuse to the per-group slices. Pass stable callbacks to the headers through ctx.
  • Verifier: observedById reaches every SessionRow (WorkspaceSidebar.tsx:247), but useSessionRowModel never reads it. Removing it alone gains little: useWorkspaces rebuilds every Workspace object from new session rows on each poll, so the memo on the workspace prop still misses. Workspace reuse plus the #9 row reuse are both needed.
  • Measure: React DevTools Profiler 'why did this render' on SessionRow across one status push with 200 sessions.

#64 Monolithic 657k-line root crate; TUI is a cheap first crate seam

  • Impact medium, effort L, verdict partly, evidence plausible-needs-measurement, area rust-build, category compile-time
  • Where: Cargo.toml:1-2, src/lib.rs:34, src/session/environment.rs:192-204, src/tmux/status_bar.rs:6, src/server/api/system.rs:1246, src/server/api/system.rs:1786-1821, src/server/startup.rs:1544, src/cli/acp.rs:1283, src/cli/plugin.rs:220-221, src/cli/migrate.rs:329, src/cli/theme.rs:6
  • Frequency: Every edit to any src file. The lib is compiled as lib, lib --test, and the bin. That is 3 rustc invocations over 657k lines (about 326k are inline test code).
  • Problem: All modules form one crate, so rustc incremental must re-validate 657k lines and relink every test binary on any change, and nothing compiles in parallel. tui (140k lines) depends on everything but is depended on only through theme styles, open_url, bindings::parse_chord, migrate_for_startup and run_standalone. session/tmux/server are cyclic and harder to split.
  • Fix: Split the workspace into aoe-core (session, tmux, process, git, acp, server, daemon, plugin, migrations) and aoe-tui (src/tui), with the aoe bin crate holding main.rs plus src/cli. Move tui/styles (2.1k lines) and tui/open_url.rs into core first. Their outside callers are session/environment.rs, tmux/status_bar.rs, server/api/system.rs and server/startup.rs. Next seams: events, github, update, sound (leaf modules).
  • Verifier: Counts hold: src is 656,857 lines, src/tui 140,352, and only 10 non-tui files reference crate::tui, almost all tui::styles. But 'nothing compiles in parallel' is overstated: dev uses codegen-units 16 and incremental. The real win is skipping tui's front end when you edit core, and only a measurement can size it.
  • Measure: cargo build --timings after touching src/session/mod.rs vs src/tui/app.rs; compare the agent-of-empires lib unit time with -Zself-profile front-end share.

#65 Dev-dependencies add features to normal deps, so cargo build and cargo test share almost no artifacts

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area rust-build, category dev-loop
  • Where: Cargo.toml:242, Cargo.toml:248, Cargo.toml:261, Cargo.toml:41, Cargo.toml:52, src/cli/runtime_read/pack.rs:91-103
  • Frequency: Every switch between cargo build/cargo run and cargo test/clippy --all-targets in a worktree. Scales with dependency count (435 crates).
  • Problem: cargo tree -e no-dev vs dev shows these dev-deps change features of normal deps: jsonschema adds serde_json float_roundtrip and regex-automata nfa,perf, the tokio dev-dep adds test-util, and webauthn-authenticator-rs adds tokio-stream sync,tokio-util. serde_json, tokio and regex sit under axum, reqwest, rmcp, ACP and the 657k-line lib. So test builds keep a second full copy of them, and the lib is compiled three times instead of twice.
  • Fix: Add float_roundtrip to the normal serde_json features (Cargo.toml:52). Replace jsonschema in runtime_read/pack.rs with direct serde struct checks, or keep it with an explicit regex-automata feature match. Add sync to a normal tokio-stream entry. For tokio test-util, choose between enabling it on the normal dep (runtime cost: one clock mutex check) and documenting the fork.
  • Verifier: cargo tree -e normal vs default confirms the feature drift: serde_json gains float_roundtrip, tokio gains test-util and regex-automata gains nfa,perf. jsonschema is used only by the cfg(test) pack.rs, so it is dev-only. The cost is one extra lib compile per edit when you alternate build and test, plus duplicate deps on disk.
  • Measure: touch src/lib.rs; cargo build; cargo test --no-run --timings; check whether the agent-of-empires lib unit recompiles in the test step.

#66 build.rs watches .git/HEAD and logs/HEAD, so every commit or checkout recompiles the whole package

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area rust-build, category dev-loop
  • Where: build.rs:26-53, build_git_watch.rs:4-10, src/build_info.rs:14-17
  • Frequency: Every commit, amend, checkout, rebase step, reset or pull in a worktree. logs/HEAD changes on each one. Cost scales with crate size and test binary count.
  • Problem: A changed rustc-env AOE_BUILD_VERSION makes cargo rebuild every target of the package: lib, lib tests, bin, integration, e2e and 2 standalone test binaries. Each rerun also spawns 4 git processes, including git status --porcelain. Only build_info::BUILD_VERSION reads the value (6 uses). Agent worktrees commit often, so many builds after a commit are full re-validations and relinks of 657k lines.
  • Fix: Move aoe (src/main.rs) to its own bin package with its own build.rs that stamps AOE_BUILD_VERSION. Change build_info::BUILD_VERSION to a OnceLock<&'static str> that main sets at startup, with CARGO_PKG_VERSION as the default. Then a commit recompiles only main.rs (515 lines) and relinks aoe. This fits finding 1's bin crate.
  • Verifier: Confirmed: the build script watches HEAD and logs/HEAD and emits a rustc-env, so every commit re-runs rustc on all package targets. It also spawns 4 git processes, including git status. This is a deliberate tradeoff: #3432 already dropped the index watch. Incremental reuses the type-check cache, but parsing, expansion and linking of every test binary still re-run. A cheaper fix is to stamp the git sha only in release or dev-release profiles.
  • Measure: cargo build --tests; git commit --allow-empty -m x; time cargo build --tests; compare with no commit.

#67 With web, any web/src edit reruns npm build and recompiles the lib; xtask dev --watch rebuilds the frontend it never serves

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area rust-build, category dev-loop
  • Where: build.rs:126-172, Cargo.toml:155, src/server/assets.rs:5-7, xtask/src/main.rs:69-80, xtask/src/main.rs:280-292
  • Frequency: Every cargo build --features web after any web/src change, and every Rust-triggered rebuild in cargo xtask dev --watch while the developer edits TS.
  • Problem: build.rs registers rerun-if-changed=web/src, so TS edits rerun the package build script: a full npm run build (Vite production build) plus a recompile of the lib. rust-embed debug-embed also include_bytes the whole dist into debug binaries. cargo xtask dev serves the UI from Vite on 5173, so the embedded bundle is unused there.
  • Fix: In build_web() in xtask/src/main.rs, set AOE_WEB_DIST to a placeholder dir with a stub index.html, like CI's target/ci-web-dist. build.rs then skips npm. Drop debug-embed from rust-embed (Cargo.toml:155) so debug builds read web/dist from disk at runtime and the lib no longer depends on dist contents.
  • Verifier: Confirmed: build.rs:131 watches web/src, xtask build_web (main.rs:71-81) runs cargo build --features web on every .rs change, Vite serves the UI. Fix caveat: AOE_WEB_DIST makes build.rs delete web/dist and copy the placeholder in, so the next plain web build reruns npm. Building xtask without web or using a separate dist dir is safer. Dropping debug-embed alone does not stop the lib recompile.
  • Measure: touch web/src/main.tsx; touch src/lib.rs; time cargo build --features web, then compare with AOE_WEB_DIST set to a placeholder

#68 Local cargo test serializes about 2,400 lib tests behind #[serial] plus a global ENV_LOCK

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area rust-tests, category dev-loop
  • Where: AGENTS.md:31-40, src/test_env_lock.rs:10-52, src/session/test_support.rs:44-56, src/session/test_support.rs:362-386, src/session/mod.rs:382-396
  • Frequency: Every local cargo test run. Scales with lib test count: 857 #[serial] plus 1584 #[serial_test::serial] out of about 6,250 lib tests. Top files: server/api/sessions/tests.rs has 151, session/instance/container.rs has 76.
  • Problem: get_app_dir_path() resolves from the HOME and XDG env vars, so every test that touches state calls isolate_app_dir(), which takes the process-wide ENV_LOCK, and is also marked #[serial]. Under cargo test (the command AGENTS.md documents), about 39% of lib tests run one at a time. CI avoids this with nextest's one process per test, but the documented local loop does not.
  • Fix: Short term: make cargo nextest run the documented local command in AGENTS.md Commands, and keep cargo test only for doctests. Long term: add a cfg(test) thread-local app-dir override checked first in session::get_app_dir_path(). AppDirGuard then sets the thread-local instead of HOME and no longer takes ENV_LOCK. Then drop #[serial] from tests whose only global is the app dir.
  • Verifier: Counts hold (2441 serial of 6258 lib tests; AppDirGuard takes ENV_LOCK via EnvGuard). Doc switch to nextest is cheap. The thread-local override is unsafe: tests spawn tokio workers, spawn_blocking and subprocesses (tmux, git) that read HOME from the real env, so a thread-local misses them.
  • Measure: Compare wall time of cargo test --lib against cargo nextest run --lib on the same warm build.

#69 web-e2e leg compiles the full lib test binary and integration binary to run about 7 filtered tests

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area rust-tests, category ci-time
  • Where: .github/workflows/tests.yml:112-130
  • Frequency: Every web-e2e CI run.
  • Problem: --lib --test integration with web,e2e-tests builds a second whole-crate test-cfg compile beyond the e2e binary. It then runs only daemon_core_web_optional, plugin_install, and 5 named lib tests. The comment presents this as deliberate artifact reuse, but the lib test binary is not reused by anything else in this leg.
  • Fix: Move the 5 web-gated lib tests and the 2 integration modules to cfg(feature = "web") e2e-binary tests that drive the same entry points. Alternatively, build core-rest with --features web, since it already installs Node. Then drop --lib --test integration from the web-e2e build step.
  • Verifier: Confirmed: the web-e2e build compiles lib-test and integration binaries with web just to run 2 filters and 5 lib tests. Lib tests need crate-private access, so moving them to the e2e binary is not trivial. Moving the filters into core-rest with web is cheaper.
  • Measure: Compare web-e2e step timings: 'Build tests' with and without --lib --test integration (cargo build --timings), and check cache hit rates.

#70 jsdom boots in ~300 test files under default isolation

  • Impact medium, effort M, verdict confirmed, evidence measured, area web-tests, category test-time
  • Where: web/vite.config.ts:47-70, web/src/test-setup.ts
  • Frequency: Once per test file: 303 files carry // @vitest-environment jsdom. CI vitest job runs on 4 vCPU, so about 3 workers, with coverage on.
  • Problem: Each jsdom file creates a new jsdom 30 window plus the setup file under default isolate: true. jsdom is the slowest mainstream DOM implementation. No pool, maxWorkers or environment options are tuned, and nothing shows jsdom is still required for all files.
  • Fix: Benchmark environment: 'happy-dom' on a subset (cmdk needs ResizeObserver and scrollIntoView, already stubbed in test-setup.ts). Otherwise keep jsdom and benchmark pool: 'threads' in the vite.config.ts test block.
  • Verifier: Latest main CI Vitest: 418 files, Duration 168.5s, environment 41% (largest bucket), setup 13%, '418 workers spawned, ~528ms startup each'. 303 files use jsdom 30, no pool/isolate tuning in vite.config.ts. A happy-dom swap is risky across 303 files; try isolate:false or a per-file happy-dom opt-in first.
  • Measure: In web/: compare npx vitest run Duration breakdown against npx vitest run --pool=threads and --no-isolate on 4 CPUs.

#71 Push to main re-runs the full Tests+CI pipeline on the exact SHA the merge queue already tested

  • Impact medium, effort M, verdict confirmed, evidence measured, area ci-main, category ci-time
  • Where: .github/workflows/tests.yml:3-14, .github/workflows/ci.yml:3-16, .github/actions/kache/action.yml:28-31
  • Frequency: Every merge to main (dozens/day). Measured: push runs share headSha with a successful merge_group run (gh run list grouped by headSha).
  • Problem: Each push run repeats ~39 min of 8-vCPU Linux runner time (web-e2e 541s, core-rest 437s, bare-core 420s, live 496s, mocked 220s, vitest 235s) plus Clippy 221s, MSRV 222s, Docs 295s on a tree already green in merge_group. The push run exists mainly to write the kache main prefix, post-merge macOS, and Codecov base.
  • Fix: In kache/action.yml give merge_group the aoe-kache-ci-main role (reviewed code, about to be main). Then add if: github.event_name != 'push' to cargo-linux, playwright-live, clippy, msrv, docs. Keep cargo-macos, vitest and playwright-mocked on push for macOS and Codecov base, or upload Codecov from merge_group (same SHA).
  • Verifier: gh run list shows push runs reuse merge_group SHAs (240d68c68, 315072d35, f5c60071a). In recent push runs only macOS failed or got cancelled, so the Linux legs added no signal. kache picks the main role only for push, so a merge_group main role needs an AWS IAM OIDC trust change. The win is runner cost, not PR latency.
  • Measure: gh run list -w Tests -e push -L 50 --json headSha,conclusion; join to merge_group runs by headSha, then sum Linux job durations from gh run view --json jobs.

#72 macOS job compiles serially on a 3-core runner, making macOS-gated PRs take 23-54 min

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area ci-main, category ci-time
  • Where: .github/workflows/tests.yml:338-388, .github/workflows/tests.yml:300-317
  • Frequency: About 22 of the last 90 PR and queue Tests runs (the gate fires on Cargo.lock, build.rs, src/session/mod.rs and others), plus every main push. Measured: successful PR runs took 1362-3218s, compared with about 600s Linux-only.
  • Problem: The kache report shows 82% of macOS time is compile misses: agent_of_empires lib test about 18 min, lib about 7 min. The job runs them as two serial steps to stay within 7 GB. Cargo test (macos) is a required check, so every gated PR waits 3-5x longer in the PR stage and again in the queue. Every Cargo.lock (dependabot) bump triggers it.
  • Fix: Split cargo-macos into two parallel macos-latest jobs with the same gate: (a) cargo nextest run --features e2e-tests --lib (lib test unit only), (b) --bins, --test integration -E cli_read_daemon::, and the acp_ e2e (non-test lib). Each compiles one big unit, so there is no OOM, and wall time drops to about max(18+6, 7+5) min. Update the required-check names.
  • Verifier: Real, but the split saves less than claimed. Job (b) still builds the non-test lib, the integration binary and the e2e binary. Job (a) keeps the roughly 18 min lib-test compile on the critical path. Expect roughly 7 to 10 min saved of about 35, at 2x macOS runner use. The required-check names also change.
  • Measure: Run both split jobs on a ci-macos labelled PR with cold and warm kache; compare max job wall time with the current Cargo Test (macos) duration.

#73 kache gives almost no net benefit: prefetch hit rate is 0% and hit overhead equals the compile time it saves

  • Impact medium, effort M, verdict confirmed, evidence measured, area ci-main, category ci-time
  • Where: .github/actions/kache/action.yml:41-49
  • Frequency: Every Rust job, all events.
  • Problem: kache's own reports: core-rest saves about 6 min of compile, but cache hits cost about 7 min (ROI 0.8x). playwright-live ROI is 0.7x and macOS 0.9x. Prefetch hit 0-4 of about 2250 crates in every job, and the job warns 'Could not verify the daemon's effective remote'. Average key cost is 164-212 ms per crate. Before #5233 (rust-cache), the live build took 145-205s. It takes 197-240s now.
  • Fix: Fix the prefetch path first. Main runs that save manifests are mostly cancelled (see the cancel-in-progress finding), so the PR manifest-key namespaces are never seeded. If ROI stays below about 1.5x, go back to Swatinem/rust-cache with shared-key: ${{ matrix.leg }} on RunsOn Magic Cache. That also caches the C build-script outputs.
  • Verifier: PR run 43917737532 playwright-live: kache reports 97.4% hit, ROI 0.7x, Prefetch 1/2228 hits, plus the 'Could not verify effective remote' warning. Main push Tests: 16 of last 30 cancelled (cancel-in-progress on tests-push-refs/heads/main), so manifests are seeded unreliably. ROI is in serial CPU units, so the wall-time loss still needs an A/B.
  • Measure: A/B the same PR SHA with kache disabled vs enabled: compare 'Build aoe with instrumented web bundle' step duration across 5 runs each.

#74 playwright-live runs npm ci serially before cargo, though build.rs would overlap it with the dependency compile

  • Impact medium, effort S, verdict confirmed, evidence measured, area ci-main, category ci-time
  • Where: .github/workflows/tests.yml:621-623, .github/workflows/tests.yml:636-645, build.rs:173-219
  • Frequency: Every Tests run. This is the critical-path job (497-587s measured).
  • Problem: The 'Install web deps' step takes 40s (measured) before cargo build --features web starts. build.rs maybe_install_web_deps already runs npm ci when node_modules is missing. In the web-e2e leg that install runs alongside the about 65s C dependency chain and finishes as git2 starts (17:24:46 vs 17:24:48). The separate step adds 40s to the slowest job.
  • Fix: Delete the 'Install web deps' step in playwright-live and let build.rs create web/node_modules during the cargo build. Playwright and coverage:merge use the same web/node_modules afterwards. Keep setup-node's npm cache.
  • Verifier: In run 43917737532 'Install web deps' took 40.5s (17:23:11 to 17:23:51) before cargo starts. build.rs maybe_install_web_deps runs npm ci when web/node_modules/.package-lock.json is missing, and node_modules is used only after the build. The real gain is under 40s because the build competes with rustc for CPU.
  • Measure: Remove the step on a branch; compare the playwright-live job wall time over 3 runs against main's runs.

#75 No PR-level path filtering: docs-only and web-only PRs run every Rust job, and Rust-only PRs run web suites

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area ci-main, category ci-time
  • Where: .github/workflows/tests.yml:29-34, .github/workflows/ci.yml:51-56, .github/workflows/ci.yml:116-121
  • Frequency: Every PR push. Of the last 80 merged PRs: 9 docs/ci-only and 17 web+docs-only (no Rust), 40 Rust-only (no web).
  • Problem: A docs-only PR still uses about 6 RunsOn 8-vCPU jobs (about 39 runner-min) plus clippy, msrv and docs (about 12 min). A web-only PR still runs core-rest, bare-core, clippy and msrv, which are irrelevant to web/. Only macOS and the nix jobs have change detection.
  • Fix: Add a changes job like macos-gate that diffs the PR (pulls.listFiles) and outputs rust/web booleans. Add a job-level if on cargo-linux core-rest/bare-core, clippy, msrv and docs for rust, and run all jobs for docs-only PRs only in merge_group. A job-level skip satisfies required checks. Always run everything in merge_group.
  • Verifier: No path filter exists except macos-gate. But the proposed job-level if on the cargo-linux matrix is unsafe: when a matrix job is skipped, it reports one unexpanded context name, so the per-leg required checks never report (see the cargo-linux-release-pr stub job). The fix needs a stub job or step-level skips.
  • Measure: Count the PR runs in the last 80 PRs that have no .rs, Cargo.*, or build.rs change and sum their cargo-linux, clippy, and msrv runner-minutes via gh api.

#76 Cachix push rebuilds the full LTO Nix package on every main push, with no concurrency cancel

  • Impact medium, effort S, verdict confirmed, evidence measured, area ci-other, category ci-time
  • Where: .github/workflows/cachix-push.yml:12-54, .github/workflows/cachix-push.yml:38-54, Cargo.toml:[profile.release]
  • Frequency: Every push to main touching src/, Cargo.*, docker/, themes/, plugins/ (about 6-8 per day), on 2 runners (linux + macOS). Observed: 32 min macOS and 37 min Linux per run (runs 43897630596, 43884158311, 43880719763), several overlapping.
  • Problem: No concurrency group, so queued runs for superseded commits keep burning 35+ min each on two runners. Each run is a release-profile build (lto=true, codegen-units=1) of the crate. Only the newest main commit matters for a binary cache. Also cachix push ./result duplicates cachix-action's post-step push.
  • Fix: Add concurrency: {group: cachix-push-${{ matrix.os }}, cancel-in-progress: true} (workflow level, keep the failure-notify job separate). Optionally gate the macOS leg to schedule/tags only, and drop the explicit cachix push step if cachix-action's auto-push covers ./result.
  • Verifier: No concurrency key in cachix-push.yml; gh run list shows overlapping 40-60 min runs (13:56, 14:17, 14:50 on 11-16). Fix as written is invalid: matrix context is unavailable at workflow level, so put concurrency on the cachix job. The explicit cachix push is near no-op; trivial win.
  • Measure: gh run list --workflow cachix-push.yml --limit 30 --json createdAt,updatedAt; sum overlapping runner minutes before and after the change.

#77 Docker sandbox images build arm64 under QEMU and likely never hit the GHA layer cache (45 min)

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area ci-other, category ci-time
  • Where: .github/workflows/docker.yml:27-28, .github/workflows/docker.yml:55-65, .github/workflows/docker.yml:101-112, docker/Dockerfile:5-120
  • Frequency: Every v* tag push and every nightly (build-base 2726s, build-dev 529s in run 43669069338; base is about 45 min every release). Scales with the number of agent CLIs installed (about 18 serial RUN layers).
  • Problem: linux/arm64 runs under QEMU emulation on an amd64 runner. Base and dev jobs share the default type=gha cache scope with mode=max, so each export overwrites the other's cache, and the base build stays near-uncached. Dockerfile is one linear stage, so unrelated CLI installs run serially.
  • Fix: Use a matrix with a native ubuntu-24.04-arm runner per platform, push by digest and merge with docker buildx imagetools create. Set distinct scope=base/scope=dev on cache-from/to. In docker/Dockerfile split each CLI install into its own FROM base AS x stage and COPY --from so BuildKit runs them in parallel.
  • Verifier: QEMU arm64 and shared default gha scope confirmed (46 min base build). Fixing cache scopes is unsafe: unpinned installs (curl install.sh, npm -g @latest) would hit cache and ship stale agent CLIs. The cold cache is what keeps them fresh. Use native arm64 runners and parallel stages, and skip cache scopes.
  • Measure: Run docker.yml via workflow_dispatch on a branch with native ubuntu-24.04-arm matrix; compare build-base job duration to 2726s.

#78 Website hero serves a 1.9 MB GIF as the high-priority LCP image; GIFs total 4.4 MB in the checkout

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area ci-other, category bundle-size
  • Where: website/src/pages/index.astro:111-120, website/src/pages/tui.astro:56, website/src/pages/web.astro:55-62, website/public/main.js:3-20, docs/assets/demo.gif, docs/assets/web-desktop.gif, docs/assets/web-mobile.gif
  • Frequency: Per landing-page, /tui and /web view (every visitor); main.js swaps in the 1.4 MB web-desktop.gif when a user clicks the tab. Git history carries 3.9 MB web-demo.gif versions too.
  • Problem: Animated GIFs of terminal recordings are about 10-20x larger than the equivalent muted looping WebM/MP4. The hero is the LCP element with fetchpriority=high, so the full 1.9 MB blocks first paint on mobile. build-site.sh and package.json copy-assets also ship web-mobile.gif, which only README.md references.
  • Fix: Convert demo.gif and web-desktop.gif to webm/mp4 (ffmpeg or agg+ffmpeg in record scripts) and render <video autoplay muted loop playsinline poster> in index.astro, tui.astro, web.astro, with main.js swapping src. Stop copying web-mobile.gif into website/public.
  • Verifier: Confirmed: index.astro:111-119 loads 1.9 MB demo.gif with fetchpriority=high, and main.js:15 swaps in the 1.4 MB web-desktop.gif. Overstated part: copying web-mobile.gif only adds deploy size, since visitors never fetch it. README and docs/index.md:14 still need the GIFs, so add webm/mp4 alongside them instead of replacing them.
  • Measure: Run Lighthouse mobile on the landing page before and after (npx lighthouse --only-categories=performance) and compare LCP and total bytes.

#79 Embedded dashboard JS/CSS is served uncompressed (2.4 MB entry instead of ~530 KB brotli)

  • Impact medium, effort S, verdict confirmed, evidence measured, area web-bundle, category network
  • Where: src/server/router.rs:588-603, src/server/assets.rs:62-115
  • Frequency: Every cold dashboard load and every load after an aoe upgrade (new hashes); per client device. Hashed assets are cached immutable afterwards.
  • Problem: compression_layer only compresses application/json, and serve_embedded_file returns raw bytes. A sibling-worktree build (bengalis-iv dist, Nov 14) shows index-*.js at 2,390,143 B raw vs 676 KB gzip / 532 KB brotli, StructuredView 413 KB vs 122 KB, worker 10.7 MB vs 1.9 MB. Phones over Tailscale/LAN download 3.5-4.5x more bytes before first paint.
  • Fix: Precompress at build: add a Vite closeBundle step writing .br and .gz for js/css/json/svg into dist/assets. In serve_embedded_file, if Accept-Encoding has br/gzip and StaticAssets::get("{path}.br") exists, serve it with Content-Encoding, Vary: Accept-Encoding and the original mime. Cheaper alternative: add text/javascript and text/css to the compression_layer predicate.
  • Verifier: router.rs:588-603 compresses only application/json; assets.rs serve_embedded_file returns raw bytes with no Content-Encoding. The commit #5356 gives no reason to exclude assets. Sibling dist: index 2.39 MB raw vs 672 KB gzip / 532 KB br; worker 10.7 MB vs 1.9 MB gzip. Widening the predicate to JS/CSS is the S fix. Localhost users gain nothing.
  • Measure: curl -sH 'Accept-Encoding: gzip' -o /dev/null -w '%{size_download}' http://host:8080/assets/index-*.js before and after

#80 Main entry eagerly bundles diff viewer, ACP markdown, tool cards, settings, wizards; StructuredView lazy split is largely defeated

  • Impact medium, effort M, verdict confirmed, evidence measured, area web-bundle, category bundle-size
  • Where: web/src/App.tsx:156-205, web/src/components/SettingsView.tsx:7, web/src/components/SkillsManager.tsx:3-20, web/src/components/acp/BackgroundAgentsPanel.tsx, web/src/components/acp/subagents/SubagentDetail.tsx:11, web/src/components/acp/subagents/ActivitySection.tsx:19, web/src/components/MobileMainPane.tsx:6
  • Frequency: Every cold load; parse/compile cost on every page load even when cached.
  • Problem: App.tsx statically imports DiffFileViewer, FileContentViewer (@pierre/diffs/react, react-markdown), SettingsView -> SkillsManager -> acp/Markdown (@assistant-ui/react-markdown, shiki), BackgroundAgentsPanel -> SubagentDetail -> ToolCards (marked, DOMPurify, diffPair), SessionWizard, SetupWizardPage, CommandPalette (cmdk), PluginPageView. The comment at App.tsx:156 claims non-ACP users skip assistant-ui/shiki; they do not. Entry is 2.39 MB raw.
  • Fix: Wrap in React.lazy + Suspense: SettingsView, SessionWizard, SetupWizardPage, DiffFileViewer, FileContentViewer, PluginPageView, CommandPalette, HelpOverlay, AboutModal. In SettingsView lazy-load SkillsManager; in App.tsx and MobileMainPane lazy-load BackgroundAgentsPanel (or SubagentDetail inside it). Update the stale App.tsx:156 comment.
  • Verifier: App.tsx statically imports SettingsView (which imports SkillsManager, then acp/Markdown with @assistant-ui/react-markdown), BackgroundAgentsPanel (then SubagentDetail, then ToolCards), DiffFileViewer, FileContentViewer, SessionWizard, SetupWizardPage and CommandPalette. The sibling entry contains assistant-ui, marked, DOMPurify and cmdk. The App.tsx:156 comment is stale. The gain is parse time on each load, plus bytes on a cold load.
  • Measure: npx vite-bundle-visualizer in web/, compare index-*.js size and Lighthouse TBT/LCP before and after lazy splits

#81 Every WS event renders the whole AcpRuntime tree synchronously; no coalescing of streaming chunks

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area web-acp-render, category render
  • Where: web/src/components/acp/AcpRuntime.tsx:160-203, web/src/components/acp/AcpRuntime.tsx:236-276
  • Frequency: Per WS message while a turn streams (tens per second), per visible structured session.
  • Problem: useAcpSession state changes once per WS frame and AcpRuntime derives messages and re-renders RuntimeHost and the children render-prop each time. Nothing lets React drop intermediate chunks when the main thread is busy, so a slow frame (shiki, markdown parse) queues behind every chunk and input latency in the composer rises during streaming.
  • Fix: In AcpRuntime, wrap the derivation input: const deferredActivity = useDeferredValue(displayActivity) and feed it to activityToThreadMessages and clearFoldGeneration. Keep isRunning and the composer-facing ctx on the undeferred state so typing and Stop stay urgent.
  • Verifier: Real: no coalescing anywhere. useAcpConnection.ts:331 dispatches one frame action per WS message, and no rAF or transition exists in acp code. But useDeferredValue alone is weak because assistant-ui pushes store updates from effects through sync subscriptions. Batching frames per animation frame in useAcpConnection before dispatch is the safer fix.
  • Measure: Chrome Performance trace during a streaming turn while typing in the composer: measure long tasks and INP, and log WS frames vs commits per second.

#82 Tool cards re-parse args_preview 5 to 10 times per render with no memo boundary

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area web-acp-render, category cpu
  • Where: web/src/components/acp/ThreadMessages.tsx:215-279, web/src/components/acp/ThreadMessages.tsx:318-329, web/src/components/acp/ToolCards.tsx:48-107, web/src/components/acp/CoreToolCards.tsx:47, web/src/components/acp/CoreToolCards.tsx:105, web/src/components/acp/CoreToolCards.tsx:158, web/src/components/acp/CoreToolCards.tsx:269, web/src/components/acp/TodoCards.tsx:37, web/src/components/acp/NamedToolCards.tsx:143, web/src/components/acp/NamedToolCards.tsx:166
  • Frequency: Per render of each tool card; with findings 1 and 3 that is every card in the window per streamed chunk. Scales with card count times args size.
  • Problem: toToolItem parses argsText in pickStartedAt, pickPrompt, pickMemoryRecall and pickDiffs separately and builds a new ToolCall object each render. renderToolCard then runs classifyMemory, classifyMcp, classifySkill, classifyTodoWrite, classifyWorkflow (each parsing args_preview again), and the card body parses once more without useToolArgs. No component is React.memo.
  • Fix: Parse once: in AssistantToolCall, useMemo toToolItem on [toolCallId, argsText, result, isError] and parse argsText a single time inside it. Wrap ToolCard in React.memo comparing tool.id, tool.args_preview and result identity. Replace raw parseJsonObject(tool.args_preview) in cards and classifiers with a shared cached parse (module Map keyed by string).
  • Verifier: pickStartedAt and pickPrompt (ThreadMessages.tsx:215-226) build an array literal, so parseJsonObject(argsText) runs every time even when args already exist. Classifiers plus 14 card sites parse args_preview again, with no memo. argsText can hold uncapped _aoe_diffs. Group parts already memoize through useGroupPayload, but plain tool cards do not.
  • Measure: Wrap parseJsonObject with a counter and console.count it during one streamed chunk with 50 tool cards visible. Compare the count and total ms before and after memoizing toToolItem.

#83 EditToolCard recomputes diffPair for every top-level edit card each render because tool.diffs identity changes

  • Impact medium, effort S, verdict confirmed, evidence plausible-needs-measurement, area web-acp-render, category cpu
  • Where: web/src/components/acp/CoreToolCards.tsx:174-184, web/src/components/acp/ThreadMessages.tsx:260, web/src/lib/diffPreview.ts:13-21
  • Frequency: Per render of each non-grouped Edit/Write card, i.e. per streamed chunk while findings 1/3 hold. Scales with edit count and file size.
  • Problem: The adds/dels useMemo depends on tool.diffs, but toToolItem rebuilds tool from part.args, which assistant-ui reparses when a message is reconverted, so the array is new each time and the memo always misses. diffPair runs @pierre/diffs parseDiffFromFile on full old/new text just to show a +N/-M header, even for collapsed cards.
  • Fix: Key the memo on stable strings: depend on tool.args_preview (or a precomputed JSON.stringify key) instead of tool.diffs, or cache diffPair results in a module-level WeakMap/Map keyed by ${old}\0${new}. Better: compute adds/dels once in AssistantBuilder.appendToolCall and carry them as _aoe_diff_stats.
  • Verifier: activityToThreadMessages rebuilds every message on each displayActivity change (AcpRuntime.tsx useMemo), so toToolItem yields a fresh diffs array from pickDiffs and the memo at CoreToolCards.tsx:174-184 always misses. ACP structured diffs carry full old/new file text, so cost scales with file size. Keying on tool.args_preview plus legacy strings is a safe one-line fix.
  • Measure: React Profiler or console.count inside the EditToolCard useMemo during a streamed turn with 10+ large Edit/Write cards in the window.

#84 Running subagent payload re-serialized and re-parsed whole on every chunk (quadratic in child count)

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area web-acp-render, category cpu
  • Where: web/src/components/acp/activityMessages.ts:309-324, web/src/components/acp/ThreadMessages.tsx:289-300, web/src/components/acp/ThreadMessages.tsx:310-316, web/src/components/acp/GroupToolCards.tsx:134-136
  • Frequency: Per activity change: stringify per chunk for every subagent in the window; full re-parse whenever any child row changes. Scales with children per subagent times their args/result sizes.
  • Problem: subagentPart JSON.stringifies parent plus every child (args and full result text) into argsText. Each new child or completion changes the string, so useGroupPayload re-parses all children and fromInline rebuilds the record. A long Task with hundreds of child calls costs O(children) per event, O(children^2) over its life, plus stringify cost on every unrelated chunk.
  • Fix: Stop smuggling children through argsText. Put child ToolParts in message metadata.custom.subagentChildren[toolCallId] (object references, reused across builds when rows are unchanged) and have AssistantSubagent read them via useAuiState; keep argsText to the parent id only.
  • Verifier: build() runs for every AssistantBuilder on each activity change, so subagentPart JSON.stringifies parent plus all children (with full result text) for every subagent in the window per chunk; useGroupPayload re-parses all children when any child changes. Quadratic over a Task lifetime. Magnitude depends on child result sizes.
  • Measure: performance.mark around activityToThreadMessages and useGroupPayload during a Task with 200+ child calls; compare per-event ms.

#85 Shiki re-highlights the whole growing code block on every chunk, synchronously, with no cache

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area web-acp-render, category cpu
  • Where: web/src/components/acp/Markdown.tsx:166-198, web/src/components/acp/ToolCardChrome.tsx:329-365, web/src/lib/snippetHighlighter.ts:114-118
  • Frequency: Per streamed chunk while a fenced code block is open in the live message; per mount of every code block and expanded tool output (remounts on fold, /clear key change, load-earlier).
  • Problem: The effect keys on code, so each chunk runs codeToHtml over the entire block on the main thread: quadratic over a long block. Results are held only in component state, so any remount shows plain text then re-highlights. No size cap: 'Show N more lines' sets limit 1e6 and highlights megabytes synchronously.
  • Fix: Add a module-level LRU Map in snippetHighlighter keyed ${theme}\0${lang}\0${code} and read it synchronously in the useState initializer. In ShikiSyntaxHighlighter, skip highlighting while the parent Markdown is smooth (pass via context) or throttle to 250 ms. Render plain above ~100 KB.
  • Verifier: Effect keys on code; the smooth-revealed block grows per frame, each run calls synchronous codeToHtml on the whole block (cancel flag only drops setState, not the work). No result cache, so remount re-highlights and flashes plain. Show-all 1e6 case is a one-off user action, minor. LRU plus skip-while-smooth is cheap and safe.
  • Measure: Wrap codeToHtml in highlightSnippet with performance.now and log count and total ms while streaming a 300-line fenced block.

#86 ACP WebSocket dispatches one React render per message, no frame batching

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area web-data-layer, category render
  • Where: web/src/hooks/acpSession/useAcpConnection.ts:400-408, web/src/hooks/acpSession/useAcpConnection.ts:282-333
  • Frequency: Per ACP WS message (each text/tool delta during streaming), per open structured view
  • Problem: ws.onmessage parses and dispatches each message immediately. Each onmessage is its own task, so React commits a full useAcpSession render (and the transcript tree, plus the cacheSet effect above) for every chunk. Bursty streaming at tens of messages per second produces tens of renders per second where one per frame would do.
  • Fix: In useAcpConnection.connect, push parsed actions into a buffer and flush once per requestAnimationFrame (setTimeout fallback when document.hidden) as a single new reducer action {kind:'batch', actions} that folds them in reducer.ts. Keep immediate dispatch for lagged/handshake control messages if ordering requires.
  • Verifier: Confirmed: each onmessage dispatches immediately (useAcpConnection.ts:282-333, 400-408) and nothing batches it. No useDeferredValue or startTransition exists. A plural 'frames' action already exists for replay, so a batch path is partly there. The size of the win depends on render cost. Most of the per-chunk cost is finding 0, so fix that first.
  • Measure: React Profiler: record commits per second and the mean commit duration while a long reply streams, before and after rAF batching.

#87 Session list poll replaces every row object every 3s, re-rendering the whole sidebar

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area web-data-layer, category render
  • Where: web/src/hooks/useSessions.ts:12, web/src/hooks/useSessions.ts:107-157, web/src/hooks/useWorkspaces.ts:10-55, web/src/hooks/app/useSidebarModel.ts:58-68
  • Frequency: Every 3s (POLL_INTERVAL) for the tab lifetime; scales with session count
  • Problem: applyResult always installs freshly parsed row objects, a rebuilt observedById, and a new workspace_ordering array, even when the 304-revalidated body is identical. useWorkspaces, all five group builders in useSidebarModel (repo, session, status, nested, org, regardless of active axis) and every row re-run and re-render every 3s.
  • Fix: In applyResult, skip setState when cursor equals floorGet (same epoch and revision) and no push is held. Otherwise reuse the previous row object when its fields are equal (shallow compare or per-row JSON string cache), and keep the old workspaceOrdering array when element-equal. In useSidebarModel, compute only the builder for the active axis.
  • Verifier: Every 3s poll installs new rows and a new observedById. There is no ETag or 304 on /api/sessions, so the finding's 304 premise is wrong. Reusing rows alone will not help: useWorkspaces rebuilds every Workspace object, and observedById is a SessionRow prop, so memo(SessionRow) still fails. The fix must also keep the identity of observedById and Workspace objects stable.
  • Measure: React Profiler with 50 sessions and an idle dashboard: count SessionRow renders per poll, before and after.

#88 Every 3s poll re-renders all sidebar rows; SessionRow memo is defeated twice

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area web-other-components, category render
  • Where: web/src/hooks/useSessions.ts:98-153, web/src/components/sidebar/SessionActionProvider.tsx:157-237, web/src/components/sidebar/useSessionRowModel.ts:23-41, web/src/components/WorkspaceSidebar.tsx:244-272, web/src/hooks/useWorkspaces.ts:13-56
  • Frequency: Every 3s (POLL_INTERVAL) per open tab, plus every pushed status or mutation; cost scales with session count times per-row work (deriveRowModel, Tooltip, hooks)
  • Problem: applyResult stores freshly parsed session objects each poll, so useWorkspaces builds new workspace objects and every memo(SessionRow) sees a changed prop. Independently, SessionActionProvider builds a new owner object each render and every row reads it via usePendingSetting, so all rows re-render on any App render.
  • Fix: In applyResult keep the previous SessionResponse when a shallow field compare matches (structural sharing) and reuse Workspace objects by id in useWorkspaces. Wrap owner in useMemo/useRef-stable methods (or a useSyncExternalStore keyed per target) so context identity only changes when pending settings change.
  • Verifier: applyResult maps fresh rows each poll; useWorkspaces rebuilds every Workspace; rowProps also passes props.observedById, rebuilt every setState, so memo(SessionRow) always misses. owner in SessionActionProvider.tsx:149 is a new literal each render, re-rendering all usePendingSetting consumers. Fix must also stabilize observedById per row, not only sessions and owner.
  • Measure: React Profiler: record 30s idle with 50 sessions, count SessionRow commits per poll and total commit ms before and after.

#89 Any diff-list change remounts and refetches the open file, resetting scroll

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area web-other-components, category latency
  • Where: web/src/hooks/useDiffFiles.ts:38-50, web/src/components/diff/DiffFileViewer.tsx:68,123,307, web/src/hooks/useFileContents.ts:27-34,71, web/src/App.tsx:2242
  • Frequency: Each 10s diff poll in which any file in the session's diff changed, i.e. continuously while an agent edits; cost scales with the open file's size
  • Problem: revision is one global counter bumped when the whole file-list fingerprint changes. It is in the file cache key, viewKey and the Virtualizer key, so an edit to file A discards B's cache entry, refetches contents, remounts the virtualized view and re-highlights, and the scroll hold resets to the top.
  • Fix: Compute a per-file revision in useDiffFiles (hash of that file's additions, deletions, status entry) and pass it to DiffFileViewer and useFileContents instead of the global revision. Fall back to the global one only for refresh().
  • Verifier: Global revision (useDiffFiles.ts:49) feeds the cache key, syncKey (clears draft and selection) and Virtualizer key, so any list change remounts the open file. But a per-file revision built from additions/deletions/status misses same-count content edits that today refresh; needs a server per-file hash or mtime.
  • Measure: Open a large file diff while an agent edits another file; log useFileContents fetches and scrollTop resets across 10s polls.

#90 Structured create runs before_session host hooks twice

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area gap-create-launch-latency, category latency
  • Where: src/server/session_spawn.rs:778, src/session/instance/hooks.rs:322-331, src/session/instance/container.rs:1751-1771, src/acp/supervisor/launch.rs:383-393, src/acp/supervisor/launch.rs:1232-1283
  • Frequency: Once per structured session create (and per structured resume through run_pre_launch_hooks), only when host_hooks.before_session is set
  • Problem: run_pre_launch_hooks calls mint_host_session_env, which runs every before_session command and stores pending_host_env. The ACP spawn task then calls spawn_config, whose host_spawn_environment runs the same before_session commands again through before_session_env. These hooks usually mint credentials (vault, SSO) and can take seconds, so the critical path pays for them twice.
  • Fix: Carry the instance's pending_host_env from the create into SpawnRequest (for example a new minted_host_env: Option<Vec<(String,String)>> field set in spawn_structured_session) and have spawn_config skip before_session_env when it is Some. Or skip mint_host_session_env in run_pre_launch_hooks when instance.is_structured().
  • Verifier: Double run is real for unsandboxed structured creates: mint_host_session_env (container.rs:1751) then host_spawn_environment (launch.rs:1232) reruns before_session. Option 2 is unsafe: run_launch_hooks reads pending_host_env through resolved_host_environment (hooks.rs:560,658,748), for example for HOME. Carry the minted env into SpawnRequest instead. Only matters when before_session is configured.
  • Measure: Configure before_session as sleep 2; echo X=1, create a structured session, and compare tracing timestamps for the hook runs in the daemon log.

#91 ACP teardown liveness probe spawns ps -A (macOS) or scans /proc (Linux) on async workers every 50ms, under global mutexes

  • Impact medium, effort M, verdict partly, evidence proven-by-code, area gap-stop-delete-shutdown-latency, category cpu
  • Where: src/acp/supervisor/teardown.rs:1394-1403, src/acp/supervisor/teardown.rs:692-700, src/acp/supervisor/teardown.rs:1349-1358, src/acp/supervisor/teardown.rs:1484-1491, src/acp/runner_lifecycle.rs:724-751, src/process/mod.rs:1360-1469, src/process/macos.rs:291-301, src/process/macos.rs:702-712, src/process/linux.rs:1338-1363
  • Frequency: Each structured stop, delete, restart, and reap: one probe right after SIGTERM, then one every 50ms until exit, then more in shutdown_and_wait and settle. Cost scales with the total process count on the host. Concurrent teardowns serialize.
  • Problem: SystemProcessControl::is_alive calls RunnerProcessGuard::executing. On macOS that runs refresh (a ps -A census) and then runner_group_executing (another ps -A). On Linux it reads every /proc/*/stat. This runs synchronously on a tokio worker while the global guards std::Mutex is held. In settle_sweeping_if_owed it also runs while the lifecycle mutex is held, so all supervisor admission waits for each census.
  • Fix: Run is_alive and wait_for_exit polling in spawn_blocking. In with_guard, clone an Arc<RunnerProcessGuard> out of the map and release the map lock before probing. In settle_sweeping_if_owed, compute unproven_runner before calling lock_recover(lifecycle). Wait for root exit with pidfd (Linux) or kqueue NOTE_EXIT (macOS), then run one group census.
  • Verifier: with_guard holds the guards std::Mutex across executing(); macOS refresh plus runner_group_executing spawns ps -A twice per probe; settle_sweeping_if_owed calls is_alive under lock_recover(lifecycle) (teardown.rs ~1513). Only runs during teardown windows (TERM grace, 50ms poll), so cost is bounded latency and worker blocking, not steady CPU. Impact high is overstated.
  • Measure: Wrap is_alive with a tracing span timer; stop 5 structured sessions concurrently on macOS and sum probe time and lifecycle lock wait

#92 Plugin worker reap sleeps a fixed 2s, which delays every daemon shutdown and restart

  • Impact medium, effort S, verdict partly, evidence proven-by-code, area gap-stop-delete-shutdown-latency, category latency
  • Where: src/process/worker.rs:239-243, src/plugin/host.rs:33-37, src/plugin/host.rs:515-545, src/plugin/host.rs:867-873, src/server/startup.rs:1449-1466, src/server/startup.rs:1511-1519, src/cli/serve.rs:2820-2840
  • Frequency: Every SIGTERM, aoe serve --stop, TUI daemon restart, or update restart while at least one plugin worker runs. Also each plugin teardown during reconcile.
  • Problem: reap_group_escalating sends SIGTERM and then sleeps the full REAP_GRACE (2s) without checking whether the group already exited. run_shutdown_sequence awaits this reap, and the main path awaits signal_task before work.drain and detach_all. Every daemon stop therefore takes at least 2s even when workers exit in milliseconds, and the serve --stop poll loop waits for all of it.
  • Fix: In reap_group_escalating, poll killpg(pid, None) every 25ms until ESRCH or the grace deadline, and send SIGKILL only if the group survives. Optionally select! on the worker task's exit, which is already awaited in teardown_workers.
  • Verifier: reap_group_escalating sleeps the full REAP_GRACE (2s) unconditionally; host.shutdown runs inside run_shutdown_sequence awaited before drain. But polling killpg(pid,0) alone fails: an unreaped zombie leader keeps the group visible (child.wait runs after reap at host.rs:849). Fix must reap the leader concurrently or census non-zombie members.
  • Measure: time aoe serve --stop with one plugin enabled, before and after the change

#93 Structured view TUI blocks input and redraw during reconnect, then wakes every 200 ms forever after it gives up

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area gap-daemon-client-reconnect, category latency
  • Where: src/tui/structured_view/mod.rs:386-397, src/tui/structured_view/mod.rs:536-560, src/tui/structured_view/mod.rs:1089-1120, src/daemon/websocket.rs:105
  • Frequency: Per WS drop in a native or remote structured view. The dead-socket loop then runs at 5 Hz for the life of the view.
  • Problem: apply_ws_message awaits reconnect_with_backoff inside the select loop. With 3 attempts, each bounded only by the 15 s connect timeout, plus sleeps, a blackholed tunnel can freeze keys and redraw for up to about 46 s. After failure, ws is None, recv_ws returns None at once, and the arm sleeps 200 ms inline. That wakes 5 times per second and delays each keystroke by up to 200 ms.
  • Fix: In recv_ws, when state.ws is None, return std::future::pending().await (or guard the select arm with if state.ws.is_some()), and remove the 200 ms sleep. Run reconnect_with_backoff in a spawned task that sends the WsHandle back over a oneshot polled in the select. Cap each attempt with a short connect timeout, for example 3 s.
  • Verifier: apply_ws_message (mod.rs:536) awaits reconnect_with_backoff inline in the select arm. That is 3 attempts, each capped by the 15s timeout in websocket.rs:105, so a blackholed socket stalls about 46s. After the reconnect fails, ws stays None. The None arm at mod.rs:393-396 then sleeps 200ms inline, so the loop wakes at 5Hz and the biased key arm waits up to 200ms. The view also never retries. The 'reconnecting' toast is never drawn before the stall.
  • Measure: Open a structured view over a tunnel, blackhole the port with pfctl, and time keypress-to-redraw. Count loop wakes with a tracing counter on the recv_ws None arm.

#94 Every daemon-own sessions.json write echoes into a full all-profile reload

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area gap-session-store-service, category cpu
  • Where: src/server/disk_watch.rs:63-69, src/server/disk_watch.rs:265-336, src/session/storage.rs:2604,2624, src/file_watch.rs:344-353, src/file_watch.rs:920-940
  • Frequency: Once per Storage commit made by the daemon (each prompt touch, queue mutation, status persist, identity drain), debounced 75 ms
  • Problem: update_under_lock calls notify_local_change, the dispatcher delivers it (source=Local) and the forwarder ignores ev.source, so disk_watcher_consumer re-lists profiles, re-reads Config, workspace ordering, projects and re-parses every profile's sessions.json, then merges into state.instances. Memory already holds the committed rows (adopt_committed_profiles). While loading it holds reload_gate exclusively, stalling every mirrored mutation. Cost scales with total sessions across all profiles.
  • Fix: Make the forwarder in build_disk_watch_entry forward only events whose merged source is not purely Local, or record the DataFileStamp written by update_under_lock per profile and have disk_watcher_consumer skip reload_state_instances_from_disk when every profile's current stamp equals its last self-written stamp. Keep the 2s poll as the safety net.
  • Verifier: Echo is real: forwarder notifies on any event, and disk_reload_guard holds reload_gate write during the load. But the proposed source filter is unsound: arm_debounce makes Local sticky, so a foreign write coalesced in the 75 ms window would be dropped. Use the per-profile self-written stamp skip instead. status_poll already reloads every 0.5-2 s.
  • Measure: Enable trace on server.file_watch, count 'disk reload completed' lines and latency_us per prompt with 3 profiles x 50 sessions.

#95 Disk-watch reload bypasses ProfileSessionsCache and re-parses unchanged profiles

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area gap-session-store-service, category disk-io
  • Where: src/server/disk_watch.rs:285-291, src/server/reload.rs:302-306, src/server/reload.rs:317-325, src/server/status_poll.rs:459
  • Frequency: Every disk_changed wake (any write to any profile's sessions/groups.json, including self-writes)
  • Problem: disk_watcher_consumer calls load_profiles_for_reload, which passes cache=None, so every profile's sessions.json is read and serde-parsed even when only one profile changed. status_poll_loop already keeps a ProfileSessionsCache that skips unchanged files by DataFileStamp. Cost is O(total sessions across profiles) per wake instead of O(changed profile).
  • Fix: Give disk_watcher_consumer its own long-lived super::reload::ProfileSessionsCache (moved into the spawn_blocking closure and back, as status_poll_loop does) and call cache.load(&file_watch) instead of load_profiles_for_reload. Reset it on join error like status_poll does.
  • Verifier: disk_watcher_consumer calls load_profiles_for_reload (cache None), while status_poll_loop keeps a ProfileSessionsCache that skips files by DataFileStamp after a 2 s settle. Unchanged profiles get re-parsed on every wake. The changed profile always misses the cache, so the win scales with profile count only.
  • Measure: Time spawn_blocking load in disk_watcher_consumer (latency_us trace) with 5 profiles, before and after adding the cache.

#96 Changed-file scan uses libgit2 (no fsmonitor, untracked cache or sparse index) over the whole worktree

  • Impact medium, effort M, verdict partly, evidence plausible-needs-measurement, area gap-large-repo-git-scaling, category cpu
  • Where: src/git/diff.rs:86-96, src/git/cleanup.rs:198-212
  • Frequency: Per diff-files cache miss (cache TTL 1.5s), per session, per TUI diff open/refresh. Scales with tracked file count and untracked, non-ignored files.
  • Problem: compute_changed_files runs diff_tree_to_workdir_with_index with include_untracked + recurse_untracked_dirs and no pathspec. libgit2 ignores core.fsmonitor and core.untrackedCache, so each miss lstat()s every tracked file and walks every untracked dir, 100k+ stats in a monorepo. Git on the same repo would answer in ms.
  • Fix: In compute_changed_files, shell out to git diff --numstat -z <merge-base> plus git status --porcelain=v2 -z --untracked-files=normal via run_git_with_timeout, with GIT_OPTIONAL_LOCKS=0. This honors fsmonitor, untracked cache and sparse-index. Keep libgit2 as fallback.
  • Verifier: Scan is real: diff_tree_to_workdir_with_index with untracked recursion, and libgit2 ignores fsmonitor/untracked cache. Real trigger is the web useDiffFiles 10s poll (POLL_INTERVAL=10_000), so the 1.5s TTL almost never hits. list_dirty_files in cleanup.rs only runs on worktree-removal failure, so it is not hot. The win only applies to repos with fsmonitor or untracked cache enabled. A port must keep rename/copy detection and conflict listing.
  • Measure: In a 100k-file repo with fsmonitor on, compare a timed compute_changed_files call against time git status --porcelain=v2 -uall.

#97 TUI diff open and refresh run full repo scans on the UI thread

  • Impact medium, effort M, verdict confirmed, evidence proven-by-code, area gap-large-repo-git-scaling, category latency
  • Where: src/tui/home/input.rs:4254-4262, src/tui/diff/mod.rs:169-215, src/tui/app.rs:3361, src/tui/diff/input.rs:172
  • Frequency: Per d keypress, per refresh key, after every external editor exit. Scales with repo size and untracked file count.
  • Problem: DiffView::new_for_session calls is_git_repo, get_default_base_ref, check_merge_base_status and refresh_files (compute_changed_files) synchronously in the key handler. On a 100k-file repo this is seconds of frozen TUI. This is distinct from the already-reported compute_file_diff.
  • Fix: Open DiffView with empty files and spawn compute_changed_files plus base resolution on a worker thread, delivering the result over the existing TUI event channel. Show a 'scanning' row until it arrives. Do the same in refresh_files.
  • Verifier: new_for_session runs these synchronously in the key handler: get_default_base_ref (fallback only), check_merge_base_status and refresh_files, which calls compute_changed_files. The same blocking happens on 'r' (input.rs:172), on branch select (mod.rs:371) and after editor exit (app.rs:3361). There is no spawn or worker. On small repos this is tens of ms; on large repos it freezes the TUI noticeably.
  • Measure: Time DiffView::new_for_session with an Instant and a tracing log, in a 100k-file repo with 10k untracked files, after pressing d.

#98 Each runner owns its own file-watch service (inotify instance + 3 threads) to watch one file, and sees every process's log writes

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area gap-fleet-footprint-and-log-volume, category concurrency
  • Where: src/process/runner/mod.rs:154, src/logging.rs:948, src/file_watch.rs:269, src/file_watch.rs:286, src/file_watch.rs:299, src/file_watch.rs:871
  • Frequency: Setup once per runner. Event cost is per kernel event: every log line appended to app_dir/debug.log by the daemon or any runner reaches every runner. Scales as N runners x total log lines/s.
  • Problem: FileWatchService::new() creates a notify watcher plus file_watch_backend and file_watch_drain threads and a dispatcher task. watch_runtime_filter watches the whole app dir, which holds the shared debug.log (default file_path). Each append wakes two threads in all N runners, and dispatch_path takes a mutex only to discard it. On Linux each runner also uses one inotify instance (default max_user_instances is often 128), so runners past that limit fall back to noop with a warning.
  • Fix: Drop the watcher in the runner. Read runtime_filter mtime in the existing 10 s run_watchdog loop (runner/mod.rs:390), or have the daemon push the filter over the control channel. Keep watch_runtime_filter out of run().
  • Verifier: Each runner calls FileWatchService::new() (runner/mod.rs:154), which spawns 2 threads and a notify watcher. watch_runtime_filter watches app_dir non-recursively, and the Runner sink writes the shared app_dir/debug.log, so every log flush wakes all runners. On Linux that also uses one inotify instance per runner. The 10 s watchdog mtime check is a safe replacement.
  • Measure: On Linux with 50 runners: ls /proc/*/fd -l | grep -c inotify, and a perf stat -e context-switches sample on one runner while the daemon logs at debug level.

#99 Plugin UI poll hands React fresh entries/revisions every 3s, re-rendering all of AppContent

  • Impact medium, effort S, verdict confirmed, evidence proven-by-code, area gap-plugin-runtime-and-pages, category render
  • Where: web/src/hooks/usePluginUiState.ts:71, web/src/hooks/usePluginUiState.ts:72, web/src/App.tsx:534, web/src/App.tsx:680, web/src/lib/pluginUiContext.tsx:22, web/src/lib/api.ts:157
  • Frequency: every 3s per open dashboard tab (500ms for 15s after any plugin action), even with zero plugins installed; cost scales with AppContent tree size
  • Problem: fetchJson returns a freshly parsed body each tick (even on a 304 the browser replays the body), so setEntries/setRevisions always get new references, even for [] and {}. Only pages and attention are stabilized. AppContent itself calls usePluginUiEntries() and usePluginPanes(), so the whole ~2600-line root component re-renders every poll.
  • Fix: In usePluginUiState tick(), apply the same structural-equality guard already used for pages: setEntries(prev => deepEqual(prev, next) ? prev : next), and likewise for revisions. Move AppContent's two reads into small leaf components or memoized selectors so unrelated state changes do not re-render the root.
  • Verifier: usePluginUiState.ts:71-72 call setEntries/setRevisions unguarded with freshly parsed arrays; only pages (line 75) and attention (useStableAttention) are stabilized. AppContent (3005-line App.tsx) reads usePluginUiEntries at 534 and usePluginPanes at 680, so the root re-renders every 3s even with zero plugins. The 500ms boost lasts 15s.
  • Measure: React DevTools Profiler, record 30s idle with zero plugins: count AppContent commits (expect about 10) before and after a JSON-equality guard on entries/revisions.

4. Low impact, by area

4.session-instance

#100 Poller repair re-checks unsupported sessions every 2s without arming a reprobe, resolving config each time

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area session-instance, category cpu
  • Where: src/session/instance/polling.rs:664-684, src/session/instance/polling.rs:221-231, src/session/instance/accessors.rs:485-541, src/session/instance/execution.rs:1866-1869, src/server/session_identity.rs:121-125
  • Frequency: Every 2s maintenance tick (drain_session_id_updates_in_state), per live session whose agent cannot run a session-id poller (OpenCode, Preassigned context, shells/custom tools). Scales with such sessions.
  • Problem: When supports_session_poller() is false, reconcile_capture_poller returns false without calling capture_poller.reprobe(), so repair_due stays true forever. For rows without active_execution, supports_session_poller goes through resolved_session_support, which calls resolve_config two or three times (execution_agent, legacy_default_selector_agent, launch_can_carry_resume_selector).
  • Fix: In reconcile_capture_poller, call self.capture_poller.reprobe(now) before the return false on the !self.supports_session_poller() branch, matching the NotApplicable arm. Better still, cache the unsupported verdict per (tool, active_execution) in CapturePollerSlot so it is only recomputed when Held changes.
  • Verifier: At polling.rs:759, a false supports_session_poller() returns without reprobe, unlike the NotApplicable arm at 773. maintenance_loop calls drain_session_id_updates_in_state every 2s, so each unsupported live row runs 1 to 3 uncached resolve_config calls per tick. Each call reads files, parses TOML and recompiles regexes under write locks. A one-line reprobe fixes it.
  • Measure: Run with 5 shell sessions live. Count calls through the test-only RESOLVES counter or a trace in resolve_config over 60s, before and after the fix.

#101 Agent and capture-support accessors re-resolve the full config on every call

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area session-instance, category cpu
  • Where: src/session/instance/accessors.rs:218-223, src/session/instance/accessors.rs:485-516, src/session/instance/accessors.rs:560-566, src/session/instance/accessors.rs:691-708, src/session/instance/execution.rs:1866-1869, src/session/instance/polling.rs:354-371, src/session/config/profile_config.rs:183-195, src/tmux/status_rules.rs:86-119
  • Frequency: Many times per launch, per poller start or reprobe (5s to 30s backoff per row), per retroactive repair, and per contended_capture_cwds pass. Scales with sessions and with config file size.
  • Problem: resolved_agent() calls execution_agent(), which calls resolve_config: it reads config.toml, state.toml and the profile TOML, parses them, typechecks overrides, merges, then recompiles every status_rules regex under registry write locks and may log a shadowing warning. maybe_start_poller_since_in alone calls source_session_support twice plus capture_store_dir, so one start does roughly 4 to 8 full resolves.
  • Fix: Add _in(&Config) variants (resolved_session_support_in, source_session_support_in, resolved_agent_in already exists) and resolve once at the top of maybe_start_poller_since_in, reconcile_capture_poller and the launch path. Separately, make install_from_config skip recompiling when the agents/status_rules section is unchanged (compare a hash).
  • Verifier: Confirmed: resolve_config has no cache and every call reinstalls the status_rules regexes. maybe_start_poller_since_in calls source_session_support twice. But apart from finding 2, the callers run at launch, hook install, or a 5 to 30s reprobe. Fix finding 2 first. The _in variants save a few ms per launch, not per tick.
  • Measure: Time resolve_config with tracing spans and count calls per launch and per minute of steady state in the daemon.

#102 Sandbox container reuse makes about 8 to 10 sequential docker CLI calls

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area session-instance, category latency
  • Where: src/session/instance/container.rs:511-517, src/session/instance/container.rs:533-535, src/session/instance/container.rs:607-615, src/session/instance/container.rs:418-437, src/session/instance/container.rs:46-77, src/containers/mod.rs:203-245
  • Frequency: Per sandboxed session start, restart or reattach. Each docker CLI call costs about 50 to 150ms, and the jq exec check costs more.
  • Problem: ensure_container_with_hook_in calls is_running() up to twice, exists() twice, agent_tool_matches, sandbox_store_generation_matches and predates_shared_credential. finish_container_reuse then calls mount_fingerprint_matches, a docker exec sh -c command -v jq, id() and working_dir. Each one is a separate docker inspect/exec, all run serially on the launch path.
  • Fix: Call container.inspect() (containers/mod.rs:226) once at the top and derive running, exists, labels (agent tool, store generation, mount fingerprint), id and workdir from InspectedContainer. Memoize identity_publisher_dependencies_available per container id in a static map so the exec runs once per container.
  • Verifier: The serial calls are real. A running-container reuse makes up to about 9 separate container inspect probes plus one docker exec (runtime.rs:165-345, 637-712). The cost is paid once per launch or reattach, not per tick. The proposed fix does not work as written: InspectedContainer has no labels or workdir, and inspect() also runs volume inspect once per volume. Better: one -f template call, re-read after start() and remove().
  • Measure: Wrap ensure_container_with_hook_in in a tracing span. Count probe_output calls and total their wall time on Docker Desktop during a reattach to a running sandbox.

#103 Resume probe and pane-ready loops fork 3 to 6 tmux processes every 50ms

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area session-instance, category subprocess
  • Where: src/session/instance/resume.rs:259-292, src/session/instance/resume.rs:160-173, src/session/instance/ready.rs:204-222, src/tmux/utils.rs:412-414, src/tmux/utils.rs:443-458, src/tmux/utils.rs:486-536
  • Frequency: probe_settle runs per resume start and restart, for up to 3s at a 50ms interval (about 60 iterations). wait_for_pane_ready runs per send into a respawned pane, for up to 3s. Restart-all multiplies this by the session count.
  • Problem: Each iteration calls is_pane_dead (probe_pane) and is_pane_running_shell. The second resolves first_pane_id and runs display-message, then repeats both for pane_start_command, so one resume can spawn 200 or more tmux processes.
  • Fix: Add tmux::utils::pane_state(target) -> (dead, current_command, start_command_protected) that uses one display-message -p '#{pane_dead}\t#{pane_current_command}\t#{pane_start_command}'. Resolve the first pane id once before the loop in probe_settle and wait_for_pane_ready.
  • Verifier: Each probe_settle iteration forks session exists, list-panes, display-message (probe_pane), then first_pane_id and display-message, plus two more when the pane shows a shell. Roughly 5 to 8 forks per 50ms. Fix cuts CPU and fork churn only; latency stays bound by the 2s grace or 3s max. wait_for_pane_ready usually exits on its first iteration.
  • Measure: Run a resume against a shell-wrapper session with a tmux wrapper script that counts invocations; compare counts before and after the change.

#104 Legacy (non-manifest) detection captures the pane every tick with no activity skip

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area session-instance, category subprocess
  • Where: src/session/instance/status_update.rs:341-421
  • Frequency: Per session per status tick (500ms/2s) for agents without a detection manifest (custom tools, wrapper commands, kimi/kiro-style hook-less agents, prime-agent).
  • Problem: Only the manifest path consults window_activity. The legacy branch always runs capture_pane(50), and for prime-agent also prime_live_status, which walks the process tree. It does this even when tmux reports no output since the last capture.
  • Fix: Reuse skip_capture in the legacy branch: store detection.activity and captured_at after the legacy capture, and when activity is unchanged with no hook and no pending proposal, return and keep self.status. Gate prime_live_status behind the same check.
  • Verifier: The legacy branch does capture every poll with no activity skip, while the manifest path has skip_capture. But the manifests cover claude, codex, gemini, opencode, pi and others, so only kimi, prime-agent and custom tools take the legacy path. Time-based fallbacks (hook age, stale shell, pending) make a safe skip nontrivial.
  • Measure: Run a daemon with 20 idle prime-agent or custom-tool sessions and count capture-pane forks per minute using a tmux wrapper.

#105 Fixed 100ms sleep after every pane kill

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-instance, category latency
  • Where: src/session/instance/kill.rs:155-182
  • Frequency: Per kill_clean_locked call: restart, corpse-pane relaunch, resume fallback. Serial across sessions in restart-all.
  • Problem: After session.kill() the thread sleeps a fixed 100ms with no comment explaining what it waits for. It adds latency to every restart and blocks a blocking-pool thread.
  • Fix: Replace the sleep with a bounded poll on tmux::session_exists_live(name) (for example 10ms steps, 200ms deadline). Remove it if the following code already tolerates a lingering session.
  • Verifier: The 100ms sleep is real, uncommented, and present since the initial commit. tmux kill-session is synchronous (kill_session_if_present waits on output()), so it is likely vestigial. Poll replacement adds a tmux spawn; deleting it outright is better, if tests pass. Gain is 100ms per restart, serial in bulk.
  • Measure: Time aoe session restart before and after removing the sleep; run lifecycle and e2e restart tests for races.

4.session-storage

#106 Storage::update rewrites and fsyncs sessions.json even when the closure changed nothing

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area session-storage, category disk-io
  • Where: src/session/storage.rs:2569-2634, src/session/storage.rs:669-690, src/session/sync.rs:94-125, src/server/status_poll.rs:106-131
  • Frequency: Every Storage::update call: passive status flushes per status transition per profile, capture persistence, ACP session-id saves, deletion gates. Scales with sessions.json size and number of running aoe processes watching it.
  • Problem: update_under_lock compares groups before/after but always serializes, writes, fsyncs and notifies sessions.json. No-op closures (persist_pi_observation finding no row, passive flush where every row is structured, gate checks) still cost a full pretty-JSON write, F_FULLFSYNC on macOS, a dir fsync, and a file-watch event that makes every other TUI/daemon reload the profile. LockedDataFile::update already skips unchanged writes.
  • Fix: In update_under_lock keep the raw sessions content read by load_bundle (or serialize instances right after load), then skip replace_preserving_permissions/atomic_write, sync_parent and file_watch.notify_local_change when the new instances_buf equals it, mirroring LockedDataFile::update's content != before check.
  • Verifier: Confirmed at storage.rs:2586-2626: sessions.json is always serialized, written, fsynced and notified. But most of the ~530 update callers mutate rows, and the passive flush only runs for profiles that have patches, so no-op updates are rare. Compare against a re-serialization of the loaded rows, not the raw file, because load drops unknown fields and corrupt rows.
  • Measure: Add a debug counter in update_under_lock for instances_buf == serialize(loaded) and run the daemon for an hour with about 20 sessions.

#107 Every recover/readonly load parses sessions.json twice (Value DOM then typed)

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area session-storage, category cpu
  • Where: src/session/storage.rs:2197-2258, src/session/storage.rs:2171-2195, src/session/storage.rs:2447-2459
  • Frequency: Every Storage::load / load_with_groups / Storage::update (ReadPolicy::Recover) and every uncached readonly reload; scales with session count and Instance size.
  • Problem: load_rows parses the whole file into Vec<serde_json::Value>, then runs T::deserialize(&row) per row. Every string and map in every row is allocated twice and the DOM is walked again. Only the rare corrupt-row case needs the Value path, yet the common case always pays it, inside the storage flock on every write.
  • Fix: In load_rows try serde_json::from_str::<Vec<T>>(&content) first and validate rows; only on a decode error fall back to the existing Vec per-row path that quarantines corrupt rows.
  • Verifier: load_rows (storage.rs:2197-2258) parses Vec and then calls T::deserialize per row for every non-Complete read. A typed parse first, falling back to Value only on error, is safe and keeps quarantine. The win is about one parse of a file in the tens-of-KB range, likely under 1ms per update, but the parse runs under the flock.
  • Measure: Run a criterion bench of load_instances on a 100-session sessions.json, current path against typed-first.

#108 Each storage write issues F_FULLFSYNC on macOS while holding the profile flock

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area session-storage, category latency
  • Where: src/session/storage.rs:265-283, src/session/storage.rs:181-200, src/session/anchored_fs.rs:552-566, src/session/storage.rs:2605-2626
  • Frequency: Per Storage::update (one per written file, up to two per update) plus a directory fsync; passive status writes happen per status transition across all sessions of a profile.
  • Problem: replace_anchored_file and atomic_write_resolved call File::sync_all, which Rust maps to fcntl(F_FULLFSYNC) on Apple targets, a drive-cache flush typically costing several to tens of ms. It runs under the in-process mutex and cross-process flock, so all writers and the daemon status loop serialize behind it. Atomic rename only needs ordering, not a full cache flush, for derived state like status patches.
  • Fix: Add a durability flag to replace_anchored_file/atomic_write: use nix::unistd::fsync (plain fsync, no F_FULLFSYNC) for routine Storage::update writes, keeping sync_all only for migrations, profile moves and recovery journals that document power-loss requirements.
  • Verifier: True: sync_all maps to F_FULLFSYNC on Apple targets (storage.rs:194, 321; anchored_fs.rs:74, 902), and the anchored dir sync uses plain fsync. But sessions.json is the canonical session store, not derived state. Plain fsync on macOS gives no power-loss ordering against rename. Reducing write count (finding 0) or coalescing passive writes is safer.
  • Measure: Wrap update_under_lock with tracing spans and record write+sync_all time on the macOS APFS internal SSD over 1000 passive flushes.

#109 Capture persistence does three full read-modify-write cycles per observed session id

  • Impact low, effort M, verdict partly, evidence proven-by-code, area session-storage, category disk-io
  • Where: src/session/sync.rs:404-455, src/session/sync.rs:94-125, src/session/sync.rs:836-948
  • Frequency: Per new sid observation per session (launch, /clear, /new, resume), from TUI tick and daemon status loop; scales with sessions changing conversations and sessions.json size.
  • Problem: For each Update, drain_and_persist_session_ids_inner runs storage.update to reserve the lifecycle, persist_conversation_observation_to_store runs another, and the release runs a third, plus possibly persist_pi_observation. Each is a full load, double parse, pretty serialize, write, fsync and cross-process reload trigger, while the lifecycle flock is held.
  • Fix: Fold reservation, CAS write and release into one storage.update closure under the already-held acquire_instance_lifecycle_lock (reserve, apply persist_conversation_observation logic, release in the same mutation), and fold the Pi path write into that same closure.
  • Verifier: Three storage.update cycles are real (sync.rs ~415-455), but only on a new sid observation (launch, /clear), rare. Separate reserve/CAS/release commits are the lifecycle reservation protocol, visible to other processes; folding them defeats it. Fix is risky for a tiny win.
  • Measure: Count storage.update calls and wall time per capture in a test with a 200-session sessions.json; compare with the sid-change rate in logs.

#110 resolve_config reparses three TOML files and round-trips Config through JSON twice on every call

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area session-storage, category cpu
  • Where: src/session/config/profile_config.rs:183-197, src/session/config/profile_config.rs:46-89, src/session/config/profile_config.rs:226-248, src/session/config/mod.rs:4241-4268, src/session/storage.rs:1439-1471
  • Frequency: Per call with no cache: per GET /api/sessions per distinct profile (tie_workdir overlay in server/api/sessions/list.rs:209-222), per launch (local_launch_configuration resolves twice), per conversation_carry and accessor call.
  • Problem: Each resolve reads config.toml, state.toml and profile config.toml, parses TOML, then validate_overrides_typecheck serializes Config::default() to JSON, merges and deserializes, and merge_configs_generic does the same again for the real global config. Nothing is memoized even though the TUI already has a config file watcher as an invalidation signal.
  • Fix: Add a process-wide cache in profile_config keyed by profile plus (mtime, size, inode) stamps of the three files; return a clone on hit. Drop the separate validate_overrides_typecheck pass in resolve_config by making merge_configs_generic fallible and using its result.
  • Verifier: resolve_config reads three TOML files and round-trips Config through JSON twice, uncached. list.rs already has a TTL cleanup_defaults_cache; only the tie_workdir overlay (list.rs:207-222) resolves per request. Folding tie_workdir_to_name into that cache is the S fix. A stamp-keyed global cache would skip the install_from_config side effect.
  • Measure: Time resolve_config_or_warn with tracing in GET /api/sessions and count calls per minute with the dashboard open.

#111 write_tui_activity does directory create plus file write on every keypress and click

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area session-storage, category latency
  • Where: src/session/mod.rs:1168-1173, src/session/mod.rs:357-370, src/session/mod.rs:382-397, src/tui/app.rs:764, src/tui/app.rs:917, src/tui/app.rs:1191
  • Frequency: Per key press/repeat, per non-move mouse event (scroll ticks included), per paste, on the TUI event thread.
  • Problem: Each call resolves get_app_dir (env read, home lookup, 2-3 stat calls on macOS, exists check), create_dir_all, then fs::write truncating the activity file. Consumers (server/push.rs) only test a 30s freshness window, so per-event writes are pure overhead on the input path, notably during key repeat and wheel scrolling.
  • Fix: Throttle in write_tui_activity with a static AtomicU64 last-write timestamp and skip if written within the last 5 seconds; also cache the resolved tui-activity file path in a OnceLock.
  • Verifier: write_tui_activity runs per Press/Repeat key (app.rs:764) and does get_app_dir (exists stat), create_dir_all and a truncating write. Consumers use a 30s window, so a 1-5s throttle is safe. Cost is tens of microseconds per key, so the win is small; mouse sites at 917/1191 are similar.
  • Measure: Time write_tui_activity with a criterion bench or Instant around the call; or dtruss -c the TUI during held key repeat.

#112 flatten_tree_all_profiles deep-clones every Instance per profile and again per root group

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-storage, category memory
  • Where: src/session/groups.rs:754-830
  • Frequency: Per TUI flat-list rebuild in Manual grouping with more than one profile and no active profile filter; scales with sessions x root groups.
  • Problem: For each profile it collects Vec via .cloned(), then pushes profile_instances.clone() into all_roots for every root group. Instance is a large struct, so a rebuild does O(roots x instances) deep clones of strings, maps and bindings only to read fields for sort keys.
  • Fix: Change all_roots to Vec<(&str, &Group, Vec<&Instance>)> (or share one Rc<[&Instance]> per profile) and make created_at_bounds, last_activity_group_key, attention_group_key, has_live_favorite and flatten_group take &[&Instance].
  • Verifier: Confirmed at groups.rs:777-789: per-root profile_instances.clone(). Runs per refresh_projection_presentation (each daemon snapshot), twice when hide_stopped. Caller already deep-clones every Instance (rows.rs:252). Simpler fix: build one Vec per profile and store &Vec in all_roots; no helper signature changes. Win is roots x N clones, sub-ms to low ms.
  • Measure: Wrap build_flat_items in rows.rs with Instant timing, multi-profile Manual view with 200 sessions and 20 root groups, compare before and after.

#113 Group sort keys rescan all sessions on every comparison

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-storage, category cpu
  • Where: src/session/groups.rs:504-538, src/session/groups.rs:541-580, src/session/groups.rs:678-751, src/session/groups.rs:432-445, src/session/groups.rs:796-818
  • Frequency: Per TUI flat-list rebuild, per group level; scales as G log G x N (groups x sessions).
  • Problem: sort_by_key calls the key closure per comparison. created_at_bounds, last_activity_group_key and attention_group_key each filter all instances with a fresh format! prefix, attention_group_key also collects a Vec, and the favorites pass rescans again. sort_by_name allocates to_lowercase per comparison.
  • Fix: Use sort_by_cached_key in sort_groups_inner, flatten_tree_all_profiles and sort_by_name so each key is computed once per item, and build the members prefix string once per key call.
  • Verifier: Key closures call group_members per comparison (groups.rs:504-538), so G log G x N scans plus a format! each. Real, but G is tens and N hundreds, and the sort runs only on flat-list rebuild. sort_by_cached_key is a safe, trivial swap; the saving is microseconds.
  • Measure: Criterion bench of flatten_tree with 50 groups and 500 sessions for each sort order; confirm it is well under 1ms.

#114 flatten_group scans the full session list twice per group

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-storage, category cpu
  • Where: src/session/groups.rs:924-972, src/session/groups.rs:974-977
  • Frequency: Per group node per TUI flat-list rebuild; scales as groups x sessions.
  • Problem: Each flatten_group call runs count_sessions_in_group (prefix scan of all instances with a format! allocation) and a second scan filtering group_path == path. With nested groups this is O(G x N) on every rebuild.
  • Fix: Before recursion, bucket instances once into a HashMap<&str, Vec<&Instance>> by group_path and a descendant count map; pass it to flatten_group instead of rescanning instances.
  • Verifier: flatten_group does group_members(...).count() plus a filter scan per group node (groups.rs:924-977), so O(G x N) per rebuild. Accurate, but the same small scale as #8, and the fix adds bucketing code for sub-millisecond gain. Fold into #8 only if a bench shows cost.
  • Measure: Same flatten_tree bench as #8 with 50 nested groups and 500 sessions; compare time before and after bucketing.

#115 PathsInUse::covers canonicalizes every other session path per check

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-storage, category disk-io
  • Where: src/session/deletion.rs:1243-1279, src/session/deletion.rs:1309-1331
  • Frequency: Per cleanup root checked during deletion/trash; scales with total sessions and repos across all profiles.
  • Problem: covers() calls canonicalize_or_raw on each stored path whenever the raw prefix does not match, so every check is N realpath walks; a deletion checks several roots (worktree, workspace repos) against the same list.
  • Fix: Canonicalize each path once when building PathsInUse::Known in scan_paths_in_use (store raw and canonical pairs) and compare against the precomputed canonical list in covers.
  • Verifier: covers() canonicalizes every non-matching stored path per root checked: O(roots x paths) realpaths, quadratic across a bulk purge. Runs only in user-initiated delete/trash, dominated by file reads, fsyncs and git/docker work. Precomputing canonical paths in scan_paths_in_use is safe.
  • Measure: Time covers() with 1000 sessions' paths in a unit test, or tracing span around with_paths_in_use_locked during Empty Trash.

#116 Bulk purge and Empty Trash rewrite the whole registry four or more times per session

  • Impact low, effort L, verdict partly, evidence plausible-needs-measurement, area session-storage, category disk-io
  • Where: src/session/deletion.rs:309-340, src/session/deletion.rs:590-616, src/session/deletion.rs:646-706, src/session/deletion.rs:780-860, src/server/api/sessions/delete.rs:948-960
  • Frequency: Per deleted session; Empty Trash or bulk delete of N sessions loops this N times.
  • Problem: Each PurgeTransaction runs reserve, gate, begin_irreversible and complete as separate Storage::update calls, each a full load, parse, pretty serialize, fsync and watcher-triggered reload. Emptying a large trash is O(N x file size) bytes written with 4N fsyncs and 4N cross-process reloads.
  • Fix: For batch flows, reserve all selected rows in one Storage::update and commit all completed removals in one final update (PurgeTransaction batch variant), keeping per-row reservations only around the irreversible external effects.
  • Verifier: Empty Trash loops purge_session_artifacts serially, each doing several Storage::update calls (reserve, gate, begin_irreversible, complete). Real O(N x file size) fsyncs, but a rare manual action next to worktree and container teardown. Batching risks the per-row reservation and crash-safety invariants.
  • Measure: Time Empty Trash API with 200 trashed sessions; compare Storage::update total time against whole-purge wall time via tracing.

#117 Session-id poller spawns two tmux processes per tick per session

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area session-storage, category subprocess
  • Where: src/session/poller.rs:617-628, src/session/poller.rs:480-497, src/tmux/utils.rs:253-282, src/tmux/utils.rs:323-352
  • Frequency: Per poller tick per running session: 2s initially, backing off x1.5 every 3 stable ticks to 60s, reset on every change; up to 50 pollers.
  • Problem: poll_resolved_target calls probe_pane, which runs tmux list-panes to find the first pane and then a separate tmux display-message for #{pane_dead}. Two fork/execs per tick per session, roughly 50 extra spawns per session in the first 7 minutes after each change.
  • Fix: Add #{pane_dead} to the list-panes -F format in first_window_pane_ids_classified (or a probe-specific variant) and classify from that single output, removing the display-message call in probe_pane.
  • Verifier: probe_pane runs list-panes then display-message every tick; poll intervals 2s backing off x1.5 to 60s, max 50 pollers. Adding #{pane_dead} to the format removes one spawn, and classify_pane_probe takes the same 0/1 values. Steady state saves about 1 spawn/s fleet-wide.
  • Measure: Count tmux execs with a wrapper script as tmux binary over 5 minutes with 20 running sessions; compare before and after.

#118 Empty profile name re-reads config.toml and lists profiles on each resolution

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-storage, category disk-io
  • Where: src/session/config/mod.rs:4442-4479, src/session/mod.rs:491-530, src/session/storage.rs:1787-1806, src/tmux/status_rules.rs:122-128
  • Frequency: Every Storage::new(""), get_profile_dir(""), effective_profile("") call, including status_rules::has_rules/detect when an Instance has an empty source_profile.
  • Problem: resolve_default_profile runs Config::load (two TOML reads and parses) and list_profiles (read_dir) every time. Status detection calls effective_profile per pane check, so any row without source_profile pays a config parse on the status hot path.
  • Fix: Cache the resolved default profile in a OnceLock/RwLock invalidated by update_config/set_default_profile and the config watcher, or make status_rules take an already-resolved profile and keep effective_profile out of has_rules/detect.
  • Verifier: resolve_default_profile does re-read config and read_dir each call, and status_rules::has_rules/detect call effective_profile. But source_profile is persisted and set on stored rows; empty only for legacy or test instances. Hot-path cost applies only to that edge case.
  • Measure: Strace/dtrace file opens of config.toml during a status poll with a real session store; expect none when source_profile is set.

4.session-misc

#119 Every session-id poll tick forces a fresh tmux list-sessions plus two batched show-environment calls (O(N^2))

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-misc, category subprocess
  • Where: src/session/capture/mod.rs:108, src/session/capture/mod.rs:162, src/session/capture/codex.rs:283, src/session/capture/gemini.rs:104, src/session/capture/kimi.rs:142, src/session/capture/hermes.rs:185, src/session/capture/prime.rs:225, src/tmux/mod.rs:1062
  • Frequency: Per poller thread per tick (2s, backing off to 60s), one thread per capture-backed session (cap 50). Scales with N sessions squared: each tick's show-environment batch has a segment per aoe session.
  • Problem: compose_exclusion builds a new LiveSessionSnapshot, whose names() calls refresh_session_cache() unconditionally (spawn plus global cache write), then get_hidden_env_batch twice over all aoe sessions. It runs before checking whether any candidate exists, so idle steady-state ticks pay it.
  • Fix: Make the exclusion set lazy in codex/gemini/kimi/hermes/prime/omp poll closures: compute it only after a post-floor candidate is found. Build it from the existing SESSION_CACHE via refresh_session_cache_if_due instead of a fresh LiveSessionSnapshot.
  • Verifier: Real: compose_exclusion builds a fresh LiveSessionSnapshot (refresh_session_cache spawn) plus two chained show-environment calls each tick. Kimi/prime/hermes call it before any candidate check, codex before the floor filter. AdaptiveInterval backs off 2s x1.5 to 60s after 3 stable ticks, so the steady state is about 3 spawns per session per minute. Making it lazy is safe.
  • Measure: Count tmux execs over 5 min with 20 sandboxed codex sessions: sudo dtrace -n 'proc:::exec-success /execname=="tmux"/ { @[ppid] = count(); }'

#120 Poller liveness probe spawns two tmux subprocesses per tick per session

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-misc, category subprocess
  • Where: src/session/poller.rs:481, src/session/poller.rs:641, src/session/poller.rs:662, src/tmux/utils.rs:253, src/tmux/utils.rs:323
  • Frequency: Per poller thread per tick (2s initial, 60s ceiling), per capture-backed session, for the whole life of the pane. Scales with session count.
  • Problem: poll_tick calls probe_pane every tick: one list-panes plus one display-message #{pane_dead}. The daemon already refreshes session and pane metadata caches every 2s. The Stop command also triggers a final full poll_tick before join, so stop/delete waits on 5+ subprocesses and a store scan.
  • Fix: In poll_resolved_target, answer Alive/Missing from the batch pane-metadata cache (PANE_META_CACHE/LiveSessionSnapshot::pane_dead) and call probe_pane only when the cache says dead or is stale. Skip the final poll on Stop when the pane is already gone.
  • Verifier: probe_pane does list-panes then display-message #{pane_dead}, so 2 spawns per tick at 2s to 60s. Simpler fix: add #{pane_dead} to the list-panes -F format so one spawn does the job and Missing/Unknown stay precise. The final poll on Stop is one-shot and costs little. Using the cache risks stale Alive answers.
  • Measure: Count tmux list-panes plus display-message execs per minute with 30 idle captured sessions, before and after merging the format.

#121 Store-backed capture pollers rescan the whole agent store every tick with no change detection

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area session-misc, category disk-io
  • Where: src/session/capture/codex.rs:143, src/session/capture/codex.rs:274, src/session/capture/gemini.rs:84, src/session/capture/kimi.rs:23, src/session/capture/kimi.rs:144, src/session/capture/prime.rs:36
  • Frequency: Per poller tick (2s to 60s) per codex/gemini/kimi/prime session, forever after capture too. Scales with rollouts (up to 8192 entries), chat files (up to 4096), kimi index size (up to 8 MB, 8K sessions), prime files (256).
  • Problem: Codex walks the date tree with a stat per rollout and sorts every tick. Gemini stats every chat file. Kimi re-reads and JSON-parses the whole index, then canonicalize_or_raw()s each entry's work_dir (stat chain). Prime opens and reads a header from up to 256 files before the mtime filter.
  • Fix: Keep a per-closure stamp (sessions/ dir mtime, chats/ dir mtime, index file stamp) and return the last result when unchanged. Kimi: compare literal work_dir before canonicalizing. Prime: stat mtime before opening.
  • Verifier: Rescans are real but run at about 60s steady state against store-backed (managed or sandbox) stores, often per-session and small. The proposed directory-mtime stamp is wrong: codex rollouts are nested in date dirs, and appending to or resuming an existing chat does not change the parent dir mtime. Prime caps at 256 files in a private store. Kimi canonicalize is cheap.
  • Measure: Time each poll closure with tracing spans against a codex store holding 8000 rollouts. Compare against the 60s tick budget.

#122 Containerized Pi and OMP polls spawn docker exec every tick

  • Impact low, effort M, verdict partly, evidence proven-by-code, area session-misc, category subprocess
  • Where: src/session/capture/pi.rs:176, src/session/capture/pi.rs:234, src/session/capture/omp/mod.rs:550, src/session/capture/omp/mod.rs:641, src/session/capture/omp/container.rs:270, src/containers/execution.rs:404
  • Frequency: Per poll tick (2s to 60s) per sandboxed Pi/OMP session once a transcript path sidecar exists. Host OMP resolves identity twice per tick (3 tmux calls each).
  • Problem: read_pi_session_observation calls runtime.canonical_path (docker exec sh readlink -f) on every tick for the same sidecar path. OMP calls canonical_path twice per capture and resolve_omp_poll_identity twice per host tick, so a host OMP tick costs about 11 tmux subprocesses with exclusion.
  • Fix: Memoize canonical_path results per (container id, path string) inside pi_sidecar_poll_fn / omp pollers. Run the OMP post-capture identity recheck only when the captured observation differs from the last one.
  • Verifier: Confirmed: Pi runs runtime.canonical_path (a docker exec readlink -f) every tick, and sandboxed OMP runs 2 per capture. At 60s backoff that is about 1 to 3 execs per session per minute. Memoizing on the path weakens the symlink-escape check. Safer: skip the work when the sidecar bytes have not changed. The OMP identity recheck matters only when the observation changes, so it can be skipped otherwise.
  • Measure: Count docker exec calls per minute with 10 sandboxed Pi sessions: docker events --filter event=exec_start | wc -l over 5 minutes.

#123 One captured session id causes three full sessions.json rewrites

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-misc, category disk-io
  • Where: src/session/sync.rs:415, src/session/sync.rs:436, src/session/sync.rs:445, src/session/sync.rs:817, src/session/storage.rs:2569
  • Frequency: Per observed sid change per session (launch, /clear, restart) in the daemon and TUI drain. A batch launch of N sessions costs 3N rewrites of an N-row file.
  • Problem: For each Update the loop does storage.update to acquire the Capture lifecycle reservation, storage.update for the CAS, then storage.update to release it. Each update re-reads and re-parses the file, pretty-serializes every row and fsyncs file and directory under flock, so bytes written grow quadratically with fleet size.
  • Fix: In drain_and_persist_session_ids_inner, fold reservation acquire, persist_conversation_observation_to_store and release into one storage.update closure, since the instance lifecycle flock is already held. Group updates per profile into a single commit.
  • Verifier: Confirmed at sync.rs:406-456: acquire, CAS (one pure storage.update at ~833), release are three fsynced rewrites. Scoped and OMP-pin paths skip the reservation. The CAS has no side effects, so folding all three into one closure under the held lifecycle lock is safe. Frequency is per sid change (launch, /clear), not per tick.
  • Measure: Wrap storage.update in a tracing span; batch-launch 20 sessions and count and time sessions.json writes in aoe logs.

#124 Plugin lifecycle observer rebuilds JSON summaries for every row twice per storage update, under the flock

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area session-misc, category cpu
  • Where: src/session/storage.rs:2579, src/session/storage.rs:2619, src/session/lifecycle.rs:33, src/session/lifecycle.rs:51, src/plugin/host_api.rs:543
  • Frequency: Per Storage::update commit (sid capture, status patch, rename, archive) whenever a plugin host is installed. Scales with total rows N, twice per commit, while holding the storage flock.
  • Problem: update_under_lock calls rows_of() before and after the mutation; LifecycleRow::of builds a serde_json summary, clones strings, sorts checkouts and calls all_repos() for every instance in the profile, even when the mutation touched one row.
  • Fix: Snapshot a cheap per-row key (id, title, archived, trashed, project_path, repo paths) and build the JSON summary lazily only for rows whose key differs between before and after. Have notify_commit take the diff, not both full vectors.
  • Verifier: Confirmed: rows_of runs twice per update when plugin_host is Some (startup.rs:1380, true in any non-read-only daemon). But it is O(N) small JSON builds, microseconds per row, beside a pretty-serialize of all rows plus file and dir fsync in the same critical section. Lazy diffing saves little.
  • Measure: Time rows_of in update_under_lock with Instant over a 200-row sessions.json; compare against the replace_preserving_permissions plus sync_parent time.

#125 Disk reads of sessions.json and groups.json parse twice (Value then typed row)

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area session-misc, category cpu
  • Where: src/session/storage.rs:2197, src/session/storage.rs:2219, src/session/storage.rs:2504
  • Frequency: Per Recover/ReadOnly load: every Storage::update (read half), every daemon status tick (2s) when the file stamp changed or is within the 2s settle window, and each CLI load. Scales with file size.
  • Problem: load_rows deserializes into Vec<serde_json::Value>, then runs T::deserialize(&row) per row, allocating the full Value tree plus cloned strings for every row only to tolerate a corrupt-row case. The Complete policy already parses typed directly.
  • Fix: In load_rows try serde_json::from_str::<Vec>() first and fall back to the per-row Value path only on error. Alternatively parse Vec<Box<serde_json::value::RawValue>> and deserialize each row straight from the raw text.
  • Verifier: Confirmed at storage.rs:2219-2229: the Recover/ReadOnly path parses to Vec then T::deserialize(&Value). Daemon reads go through load_cached_instances (stamp cache, 2088-2137), so re-parse happens only after changes. Typed-first with Value fallback is safe. The win is about one extra parse of a KB-scale file, likely sub-millisecond.
  • Measure: Criterion bench: load_rows on a 200-row sessions.json, Value path vs from_str::<Vec>.

#126 Storage flock acquisition polls with a fixed 50 ms sleep

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-misc, category latency
  • Where: src/session/storage.rs:913, src/session/storage.rs:958, src/session/storage.rs:987
  • Frequency: Per contended flock acquisition (exclusive and shared): bursts such as batch launch, multi-session sid capture, TUI plus daemon writers. Each waiter loses up to 50 ms after the lock frees.
  • Problem: After the first try_lock fails, waiters thread::sleep(50ms) between attempts. The lock is usually held for a few ms, so with several waiters handoffs stall for tens of ms each. The doc comment justifies polling by the 1 s warning, which a backoff also supports.
  • Fix: In acquire_open_storage_flock and acquire_open_storage_shared_flock, use exponential backoff 1ms doubling to 50ms, keeping the 1 s warn logic. Or block in lock_exclusive on a helper thread and warn from a timer.
  • Verifier: Polling with 50 ms sleep confirmed (storage.rs:958, 983). But save_lock_for(profile) (line 690) is a process-wide per-profile Mutex taken first, so in-process waiters such as batch launch and sid capture block on the Mutex, not flock polling. Only cross-process contention (TUI, CLI, daemon) pays up to 50 ms. Backoff is cheap and safe.
  • Measure: Set AOE_E2E_STORAGE_LOCK_CONTENDED marker or add a counter; run TUI plus daemon plus aoe add loop and log waited durations.

#127 TUI snapshot application re-reads project registries and canonicalizes every project path

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area session-misc, category disk-io
  • Where: src/session/projects.rs:356, src/session/projects.rs:368, src/session/projects.rs:407, src/session/projects.rs:1002, src/tui/home/projects.rs:15, src/tui/home/status.rs:694, src/session/builder.rs:340
  • Frequency: Per daemon snapshot applied in the TUI (apply_canonical_projection, every runtime cursor change) and per session creation (project_base_branches). Scales with profiles x registered projects.
  • Problem: refresh_registered_projects runs load_merged per profile on the UI thread: two registry file reads plus canonical_key (canonicalize syscalls) per project per profile, repeated per snapshot, with no stamp check. merge_base_branches also canonicalizes each project up to three times and runs find_main_repo per create.
  • Fix: Cache load_merged results keyed by the registry files' DataFileStamp (as SessionsFileCache does) and memoize canonical_key per path string. In apply_canonical_projection call refresh_registered_projects only when a registry stamp changed.
  • Verifier: Confirmed: status.rs:694 calls refresh_registered_projects unconditionally on every applied snapshot, and the same path already reads workspace ordering from disk each time. Cost is 2 small file reads plus one canonicalize per project per profile, likely well under 1 ms. builder.rs:340 runs once per create beside git worktree work, so it is negligible.
  • Measure: Wrap refresh_registered_projects in Instant::now() with a tracing debug, run AGENT_OF_EMPIRES_DEBUG=1 with 5 profiles x 30 projects, log p99 per snapshot.

#128 write_tui_activity does path resolution, mkdir and a file truncate-write on every key, paste and mouse event

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-misc, category disk-io
  • Where: src/session/mod.rs:1168, src/session/mod.rs:357, src/tui/app.rs:764, src/tui/app.rs:917, src/tui/app.rs:1191
  • Frequency: Per keypress, key repeat, paste and non-move mouse event (wheel and drag fire hundreds per second) on the TUI event loop thread.
  • Problem: Each call runs get_app_dir (stats plus macOS dual-dir resolution), create_dir_all and fs::write, which opens with O_TRUNC and dirties the inode. The consumer, is_tui_active, only needs freshness within 30 s.
  • Fix: Throttle write_tui_activity with a static AtomicU64 last-write timestamp so it touches the file at most once per second, and cache the activity file path in a OnceLock.
  • Verifier: Claim holds: key, paste and non-Moved mouse events each do get_app_dir (exists stat), create_dir_all and truncating write (src/tui/app.rs:764,917,1191). Real cost is a few syscalls, tens of microseconds, on a local tmpfs-like path; no user-visible win. Throttle is safe given the 30 s window.
  • Measure: dtruss/strace -c the TUI while holding a key or scrolling the wheel; count syscalls per second from write_tui_activity.

#129 Auto conversation summary replays the entire event log on every turn, then usually discards it

  • Impact low, effort M, verdict partly, evidence proven-by-code, area session-misc, category cpu
  • Where: src/session/conversation_summary.rs:324, src/session/conversation_summary.rs:325, src/acp/event_store/replay.rs:38, src/session/conversation_summary.rs:340
  • Frequency: Per prompt_complete turn of every structured session when session.conversation_summary is on (default off), plus manual summaries. Scales with total event count, giving O(T^2) over a long session.
  • Problem: try_conversation_summary calls acp_event_store.replay_from(&session_id, 0) (SQLite scan plus decode of every event, run synchronously on the async worker), then last_summary and extract_transcript_delta, and only then applies the threshold that returns early on most turns.
  • Fix: Query the latest ConversationSummary row by type first, then replay_from(session, last_seq) for the delta only. Run the store read in spawn_blocking and apply delta_meets_threshold on a cheap count before decoding.
  • Verifier: Real O(T^2): conversation_summary.rs:321 replays from seq 0 every turn before the threshold check. The config gate at line 297 returns first, and the setting defaults to false, so default users pay nothing. The events table has no type column, only event_json, so the proposed by-type query needs a migration. A descending scan or a per-session cached last_seq works instead.
  • Measure: Time replay_from(session,0) in try_conversation_summary on a session with 20k events, with conversation_summary=true, using a tracing span.

#130 resolve_surface parses the large ~/.claude.json twice per MCP surface open

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area session-misc, category disk-io
  • Where: src/session/mcp/mcp_model.rs:172, src/session/mcp/mcp_model.rs:248, src/session/mcp/mcp_model.rs:328, src/session/mcp/mcp_model.rs:446, src/server/api/mcp.rs:60
  • Frequency: Per GET /api/mcp/servers or aoe mcp list, and once per ACP launch (resolve_effective). Scales with ~/.claude.json size (project history, often multi-MB).
  • Problem: resolve_surface calls resolve_effective (native read) and then load_native_mcp_servers_checked_from_home again for drift, each streaming the full file. resolved_profile_config re-reads config TOML 3 times in the same call chain.
  • Fix: Have resolve_surface read NativeRead once and pass it to both resolve_effective and reconcile_agent. Resolve profile config once and thread it through.
  • Verifier: Two native reads are real (mcp_model.rs:248 and 255), but they differ: the first passes Some(cwd) for disabled-server filtering, the second None, so the result is not directly shareable. Reads stream via serde_json::from_reader, and it only runs per surface open or ACP launch.
  • Measure: Time resolve_surface against a 20 MB ~/.claude.json with a criterion bench or tracing span.

#131 Single-session deletion deserializes every profile's full registry to build cleanup protection

  • Impact low, effort M, verdict partly, evidence proven-by-code, area session-misc, category disk-io
  • Where: src/session/storage.rs:1988, src/session/storage.rs:2036, src/session/deletion.rs:1422, src/session/deletion.rs:924
  • Frequency: Per perform_deletion and creation rollback outside the batched server path. Scales with total rows across all profiles and namespaces, per deleted session.
  • Problem: cleanup_protection_inner reads and typed-deserializes full Vec of every registry (profiles plus default plus sibling namespace) to extract resource paths, so deleting k sessions one by one in CLI/TUI loops costs k full reads.
  • Fix: Add a batch entry point used by CLI/TUI multi-delete (cleanup_protection_excluding already supports a slice). Parse only id, project_path, worktree_info and lifecycle_generation via a slim row struct instead of Instance.
  • Verifier: cleanup_protection_inner does read and typed-parse every registry per call (storage.rs:2036). But the server path is already batched via cleanup_protection_excluding (delete.rs:1336). Remaining callers are single user-initiated deletes, rare. Slim row struct risks drift from Instance semantics used by protection.extend.
  • Measure: Time cleanup_protection on 5000 rows across 10 profiles via a unit bench; compare to total perform_deletion time.

#132 Group sorting recomputes O(N) member scans inside sort_by_key comparators

  • Impact low, effort S, verdict partly, evidence proven-by-code, area session-misc, category cpu
  • Where: src/session/groups.rs:504, src/session/groups.rs:541, src/session/groups.rs:567, src/session/groups.rs:632, src/session/groups.rs:895
  • Frequency: Per flat-list rebuild in the TUI and wherever flatten_tree runs (each snapshot or sort change). Scales with groups G x sessions N x log G per level, with a format! allocation per member scan.
  • Problem: sort_groups_inner uses sort_by_key whose key calls created_at_bounds/last_activity_group_key/attention_group_key, each running group_members over all instances with a format!("{path}/") allocation. flatten_group also rescans instances per group.
  • Fix: Switch to sort_by_cached_key. Precompute a path to member-slice index in one pass over instances (HashMap<group_path, Vec<&Instance>> with ancestor roll-up) and reuse it for keys and counts.
  • Verifier: Claim holds: sort_by_key calls group_members (format! plus N scan) per comparison key. But G and N are tens to low hundreds, so ~tens of thousands of cheap checks. sort_by_cached_key is a one-line fix; the HashMap roll-up is overkill.
  • Measure: Criterion bench of flatten_tree with 50 groups and 500 instances, before and after sort_by_cached_key.

#133 Terminal smart-rename reloads and recovers the whole sessions file on every Running to Idle transition

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area session-misc, category disk-io
  • Where: src/session/smart_rename.rs:1269, src/session/smart_rename.rs:1275, src/session/smart_rename.rs:1408, src/server/status_poll.rs:636
  • Frequency: Per Running to Idle transition of each unnamed terminal session until a title lands (retried when the one-shot fails and attempted stays false).
  • Problem: prepare_terminal_rename opens Storage and calls storage.load() (Recover policy, full parse, may rewrite quarantine) before the cheap gates. The daemon already holds the row and config, and each failed one-shot repeats the load and a tmux capture.
  • Fix: Pass the in-memory row and resolved eligibility into try_terminal_smart_rename and run the config/override checks before opening storage. Use load_instances_readonly instead of load, and persist a bounded attempt counter on failure.
  • Verifier: prepare_terminal_rename does load() before gates, but status_poll already filters via terminal_smart_rename_candidate and fires only on Running to Idle for unnamed terminal sessions. One file read per transition, bounded by session lock. Real but rare.
  • Measure: Add tracing timing around storage.load() in prepare_terminal_rename; count calls per hour in a busy daemon.

#134 apply_auto_title holds the global publication write lock across flock, fsync and canonical adoption

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area session-misc, category concurrency
  • Where: src/session/smart_rename.rs:1737, src/session/smart_rename.rs:1743, src/session/smart_rename.rs:1790
  • Frequency: Once per auto-titled session (first turn of each structured session, terminal rename completion). Burst of N sessions serializes N such sections.
  • Problem: state.publication.write() is taken before the spawn_blocking commit and held through the full-file load, pretty-serialize, two fsyncs and adopt_committed_profiles, blocking every other publisher and reader of publication for tens of ms per title.
  • Fix: Take the storage flock and commit first, then acquire publication only for adopt_committed_profiles. If ordering requires early exclusion, restrict to a version check rather than holding it across the disk write.
  • Verifier: Publication write lock does span the spawn_blocking commit, but it is taken after the write transition and checks canonical health first; it orders commit and adopt against publishers. Reordering risks the invariant. Runs once per title, rare.
  • Measure: Log publication.write() hold duration in apply_auto_title; compare to publisher wait times under 20 concurrent titlings.

#135 Session-file cache hits still deep-clone every Instance each 2s status tick

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area session-misc, category memory
  • Where: src/session/storage.rs:2108, src/session/storage.rs:2138, src/server/reload.rs:149
  • Frequency: Every 2s daemon status tick per profile, even when sessions.json is unchanged. Scales with row count and row size (execution bindings, prior session ids).
  • Problem: load_cached_instances returns rows.clone() on a stamp hit and stores another rows.clone() on a miss, so each tick allocates a full copy of every Instance before the status reload overwrites a few fields.
  • Fix: Store the cached rows as Arc<Vec> and have the reload path clone-on-write only rows whose live status changes, or return &[Instance] to callers that only compare.
  • Verifier: Clone on stamp hit is real, but the cache exists to skip parse and the reload path needs owned rows to mutate. Cost is a Vec clone of hundreds of rows every 2s per profile, microseconds to low ms. Arc/COW refactor touches many callers.
  • Measure: Bench load_instances_readonly_cached hit path with 500 Instances; compare to 2s tick budget.

#136 aoe session import reads whole transcript lines and parses each as Value for every Claude jsonl

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area session-misc, category disk-io
  • Where: src/session/claude_import.rs:49, src/session/claude_import.rs:143, src/session/claude_import.rs:150
  • Frequency: Once per aoe session import invocation. Scales with number of Claude transcripts (thousands) x line size (single lines can be MBs).
  • Problem: scan_sessions_in opens every .jsonl, uses BufRead::lines() (unbounded line allocation) and serde_json::from_str:: for up to 400 lines per file until cwd and title are both found.
  • Fix: Read each file via a take()-bounded buffer (for example 64 KiB per line) and skip over-long lines. Stop scanning a file once cwd is found if title is not needed for ranking, and parse only needed keys.
  • Verifier: Loop already breaks once cwd and title are both found, and caps at 400 lines; typical transcripts hit both in the first few lines. Unbounded lines() is real but only matters for huge early lines. Runs on picker open in spawn_blocking and in CLI import. Skipping long lines could drop titles from pasted prompts.
  • Measure: Time scan_sessions() over a real ~/.claude/projects with thousands of jsonl files (hyperfine on aoe session import --list), and check bytes read per file via dtruss/strace.

4.tui-loop-home

#137 Spinner redraw fires at 8 Hz for any animated status, even when no spinner is visible

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area tui-loop-home, category cpu
  • Where: src/tui/app.rs:1495-1501, src/tui/home/rows.rs:136-144, src/tui/home/render.rs:408-428, src/tui/home/render.rs:1683-1690
  • Frequency: Every 120ms while any session in self.instances is Running/Waiting/Starting/Creating. Waiting sessions can sit for hours
  • Problem: has_animated_sessions scans every instance, including archived, snoozed, trashed, collapsed-group and scrolled-off rows, and rows whose icon agent_row_icon overrides. It also covers the collapsed sidebar and Terminal view, where spinners come from pane presence. Each hit forces a full frame every 120ms. The Waiting spinner only changes every 400ms and Running every 220ms, so at least half these frames repaint identical cells.
  • Fix: While building visible rows in render_list, record the earliest next spinner frame boundary (an Instant) of rows that actually paint a spinner, as next_spinner_deadline on HomeView. In App::run, replace the fixed SPINNER_REDRAW_INTERVAL and has_animated_sessions check with sleep_until(next_spinner_deadline). Leave it unset when no visible row animates.
  • Verifier: has_animated_sessions (rows.rs:136) scans all instances, including archived, snoozed, and offscreen rows. Spinner periods are 180/220/280/400ms with per-session phase offsets, so a per-row deadline rarely aligns. Ratatui diffs cells, so the cost is CPU frame building, not terminal output. A cheaper fix: check only visible rows.
  • Measure: Profile CPU of an aoe TUI process with one Waiting session hidden in a collapsed group, using samply for 60s, before and after.

#138 5s heartbeat reloads, re-parses, and rebuilds the whole projection from disk on the UI thread

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area tui-loop-home, category disk-io
  • Where: src/tui/app.rs:1418-1450, src/tui/home/lifecycle.rs:455-488, src/tui/home/status.rs:444-494, src/tui/home/status.rs:621-700, src/tui/home/input.rs:5932-5937, src/tui/home/projects.rs:15-32, src/tui/home/watchers.rs:60-71, src/session/storage.rs:2319-2348
  • Frequency: Every 5s while idle (DISK_REFRESH_INTERVAL), plus each sessions.json/groups.json watch event; scales with profile count x session count
  • Problem: FullHeartbeat runs refresh_shortcut_bar_tip (load_config) and reload_storage_only. That calls apply_canonical_projection(refresh_metadata=true), which takes a shared flock and fully reads and parses sessions.json and groups.json per profile. It then runs duplicate_reports, re-clones every Instance, rebuilds GroupTrees, rewires watchers (canonicalize+stat), reloads the project registries, and rebuilds flat_items. This runs even when nothing changed, and the file watcher already marks dirty on real changes.
  • Fix: In plan_tick_disk_refresh, skip the heartbeat when FileWatchService is live and no watcher reports an install failure. Otherwise raise the interval to 30s+. Keep a per-profile SessionsFileCache in HomeView and call load_complete_with_groups_cached in apply_canonical_projection and load_storage_projection. Run refresh_shortcut_bar_tip only on config watch events.
  • Verifier: Confirmed: FullHeartbeat every 5s runs load_config, reload_storage_only, and apply_canonical_projection(refresh_metadata=true), which re-reads sessions.json/groups.json with no cache, plus an extra resolve_config for mouse capture. SessionsFileCache exists but only server/reload.rs uses it. Dropping the heartbeat is risky because tips_seen lives in state.toml and other metadata may not be watched. Prefer the cached loader.
  • Measure: Add a tracing span around App FullHeartbeat handling and record its duration with 3 profiles and 100 sessions.

#139 Every runtime snapshot clones and rebuilds every row plus disk reads

  • Impact low, effort L, verdict partly, evidence plausible-needs-measurement, area tui-loop-home, category cpu
  • Where: src/tui/home/status.rs:780-860, src/tui/home/status.rs:516-610, src/tui/home/status.rs:633-649, src/tui/home/lifecycle.rs:575-604, src/tui/home/rows.rs:169-189, src/tui/home/rows.rs:231-262, src/tui/home/rows.rs:68-75, src/tui/home/projects.rs:15-32
  • Frequency: Per coalesced runtime WS snapshot, which arrives on any session status or activity change. With dozens of active agents this is several per second. O(n) in session count
  • Problem: apply_session_feed_with_dialogs reads workspace ordering from disk. apply_canonical_projection then clones every Instance into a new IndexMap, parses 8 RFC3339 timestamps per row, and clones every row again per profile only to feed GroupTree::new_with_groups, which only reads group_path. refresh_registered_projects re-reads the project files. refresh_projection_presentation then clones all instances again (twice more in Project/Org/Status modes, and twice the build when hide_stopped is on).
  • Fix: Mutate self.instances in place from SessionResponse rows instead of clone-and-replace. Rebuild group_trees with GroupTree::new_with_group_paths(next.values().filter(..).map(|i| i.group_path.as_str()), ..). Rebuild flat_items only when group, sort, title, or visibility fields changed. Change build_flat_items_* to take &Instance views. Cache workspace ordering and registered_projects behind the file watcher.
  • Verifier: Clone/rebuild churn is real (status.rs 444-680, rows.rs 231-262, projects.rs 15-32), but it is O(n) memcpy plus small JSON/TOML reads; dozens of rows cost well under 1ms. The larger hidden cost: every 5s heartbeat calls apply_canonical_projection(snapshot, true) (lifecycle.rs 473), reloading every profile's storage from disk. Target that first.
  • Measure: Wrap apply_session_feed_with_dialogs and reload_storage_only in tracing spans with elapsed time; run 50 sessions and log p50/p99 per call.

#140 Org grouping opens git repos on the UI thread after every projection

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tui-loop-home, category latency
  • Where: src/tui/home/rows.rs:362-376, src/tui/home/lifecycle.rs:575-576, src/tui/home/status.rs:676-679, src/git/remote.rs:337-342
  • Frequency: In GroupByMode::Org: every runtime snapshot and every 5s heartbeat, once per distinct repo path
  • Problem: refresh_projection_presentation clears remote_owner_cache unconditionally. The next build_flat_items_by_org then calls resolve_org, which calls git::get_remote_owner_with_key. That runs git2 Repository::open plus a config parse for every distinct repo, synchronously on the async runtime thread that also handles input. With 20 repos that is 20 repo opens several times a second.
  • Fix: Stop clearing remote_owner_cache in refresh_projection_presentation. Evict only entries whose repo_path left self.instances, and invalidate on explicit refresh. Better: resolve misses on the existing Worker pattern (crate::tui::worker::Worker) and show NO_ORG_GROUP_LABEL until the result lands.
  • Verifier: Confirmed: refresh_projection_presentation (lifecycle.rs 575-576) clears remote_owner_cache, and resolve_org (rows.rs 362) calls git2 open per distinct repo. Only GroupByMode::Org is affected, and each open is sub-ms on a warm cache. Keep the cache across projections and clear it on the 5s heartbeat. A Worker is overkill.
  • Measure: In Org mode with 20 repos, time build_flat_items_by_org with a tracing span before and after keeping the cache.

#141 Main loop polls at 30 Hz while idle instead of waking on events

  • Impact low, effort M, verdict confirmed, evidence plausible-needs-measurement, area tui-loop-home, category cpu
  • Where: src/tui/app.rs:671-674, src/tui/app.rs:1261-1530, src/tui/home/rows.rs:136-144
  • Frequency: Every 33ms for the whole TUI lifetime, including idle hours; each tick does O(n) scans (has_animated_sessions) and ~30 channel polls
  • Problem: The 33ms interval exists for live-send frame pacing (comment at 672). But the loop uses it outside live-send too, to poll session_feed (a watch channel), worker mpsc results, oneshots, and timers. That costs 30 wakeups per second per TUI even with nothing to do, which hurts idle CPU and laptop battery over long sessions.
  • Fix: Only arm refresh_interval while live_send.is_some(). Otherwise add select arms for the session_feed watch receiver's changed() and a shared tokio::sync::Notify that workers (metrics, plugin UI, serve probe) signal. Add sleep_until on the earliest pending deadline (status flash expiry, spinner deadline, heartbeat, dwell timer).
  • Verifier: 33ms interval (app.rs 673) drives the whole loop even when idle. Per-tick work is cheap: plugin UI and metrics requests are throttled (plugin_ui_poller.rs 143), and has_animated_sessions is an any() scan. The cost is mainly 30 timer wakeups per second. Event-driven wakeups need care for many deadline-based ticks.
  • Measure: Run TUI idle 10 minutes; compare top -pid <aoe pid> -stats cpu,idlew CPU and idle wakeups before and after gating the interval.

#142 Heartbeat resolves full config every 5s just to recheck mouse capture

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area tui-loop-home, category disk-io
  • Where: src/tui/app.rs:1426-1438, src/session/config/profile_config.rs:183-196, src/tmux/status_rules.rs:86-116
  • Frequency: Every 5s while not in live-send
  • Problem: After each FullHeartbeat, resolve_config(profile) reads and parses two TOML files and reinstalls the status-rule registry, which takes write locks and recompiles regexes. The only goal is to compare mouse_capture. The config watcher path (try_refresh_from_config_watcher) already re-resolves on real edits.
  • Fix: Store mouse_capture in apply_config_to_state (HomeView field). Have App compare it after take_config_refresh_kick instead of in the heartbeat. Delete the resolve_config call in the FullHeartbeat arm.
  • Verifier: app.rs 1426-1438 calls resolve_config every 5s FullHeartbeat only to compare mouse_capture. That means 2 small TOML parses plus install_from_config locks, and regex compiles only when status_rules exist. This is the only path that updates mouse_capture_allowed, so the fix must add the check to the config-watch kick. Small win next to the heartbeat's full storage reload.
  • Measure: Add a tracing span around the resolve_config call in the FullHeartbeat arm and log elapsed µs over 10 heartbeats.

#143 Update badge stats the agent binary per visible row per frame once flagged

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tui-loop-home, category disk-io
  • Where: src/tui/home/render.rs:2200-2203, src/session/update_restart.rs:86-99, src/session/update_restart.rs:33-37
  • Frequency: Per visible idle non-structured row per frame, after an agent binary upgrade (common after brew/npm updates)
  • Problem: is_stale serves the cached observation, but whenever the cached view says updated it confirms against observe(path). That is a live fs::canonicalize plus metadata every call, with no cache. Each such row costs several syscalls, a path.display().to_string() allocation, and a global mutex lock every frame, up to 30 fps in live-send.
  • Fix: In is_stale, run the live confirmation only when the cached entry's Instant is earlier than started_at. Otherwise trust the cache. Or memoize the confirmed-stale result in OBSERVED_CACHE per (path, started_at), since an updated binary stays updated until restart.
  • Verifier: Claim holds: is_stale calls observe(path) (canonicalize plus stat) every paint once cached view says updated, no cache. But it only affects idle non-structured rows with launch_executable after a binary upgrade; the cost is microseconds per row. Live confirm is deliberate, since the cache may predate launch.
  • Measure: Time binary_updated per row with a stale-flagged fixture (criterion or Instant around call), or dtruss -c the TUI after touching an agent binary.

#144 Passive fleet reconcile allocates and sorts per-session geometry every frame

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area tui-loop-home, category render
  • Where: src/tui/home/render.rs:2973-3020, src/tui/home/render.rs:2937-2955, src/tui/home/render.rs:3523-3525
  • Frequency: Every frame that renders the preview (8-30 fps when animated or live), O(n) sessions
  • Problem: reconcile_passive_fleet runs PreviewLayout::compute for every non-structured instance, clones each id into a Vec, and sorts it every frame to compare against passive_fleet_armed. invalidate_externally_resized_panes also builds a tmux name string per synced session per frame. The inputs (inner rect, compact, show_info, the instance set) rarely change.
  • Fix: Memoize on a key of (inner, compact, show_info, instances revision). Bump a counter when instances or their status/agent_info_height change. Return early from reconcile_passive_fleet when the key is unchanged and no passive-resize completions are pending. Run invalidate_externally_resized_panes only when the tmux snapshot time advances.
  • Verifier: Per-frame work is real: compute per non-structured instance, id clones, sort, and a name resolve plus RwLock read per synced session. All of it is cheap arithmetic and string work at tens of sessions. The memo key needs an instances revision counter, which adds invalidation risk to a delicate debounce design.
  • Measure: Wrap reconcile_passive_fleet in Instant timing with 50-100 sessions during live-send; compare against frame budget (33ms).

#145 Preview link painting re-scans every visible row each frame

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area tui-loop-home, category render
  • Where: src/tui/home/render.rs:3879-3930, src/tui/links.rs:47-75, src/tui/home/input.rs:6463-6472
  • Frequency: Every frame showing a tmux preview, per visible row (pane height ~30-60); also twice per mouse motion cell change
  • Problem: paint_preview_links calls link_spans_for_line for each visible row. Each call allocates a concatenated String of the row, scans every pane link with contains, and runs bare-URL detection, even when the parsed text, scroll position and width are unchanged since the last frame. update_hovered_link repeats this twice per motion event.
  • Fix: Cache the computed Vec<(row, LinkSpan)> in PreviewCache, keyed by (parsed_text identity/capture_generation, links_generation, first_line, pane.width, prefixes). Rebuild only on key change. Each frame just reapplies UNDERLINED/AlwaysUpdate and inserts hyperlink cells from the cache.
  • Verifier: Per visible row it allocates one concatenated String and runs a contains scan; link_spans_for_line already has a cheap reject before the column map and returns early without scheme or link. About 50 rows of short strings per frame is microseconds. A cache would add key-invalidation complexity.
  • Measure: Criterion bench of paint_preview_links on a 60x200 parsed Text with no links; expect well under 100 microseconds.

#146 ANSI parse of captured preview runs on the paint thread

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area tui-loop-home, category latency
  • Where: src/tui/home/preview.rs:134-152, src/tui/home/render.rs:3648-3652, src/tui/home/render.rs:2848-2858
  • Frequency: Once per new capture frame. In live-send that is every ~25-40ms; scales with capture_lines (grows with scrollback depth)
  • Problem: The capture worker hands raw content to the UI thread. ensure_parsed then runs parse_output_text over the whole capture inside render (timed as preview_timings.parse), and store_capture also counts lines. When the user scrolls back, the capture budget grows, so each streamed frame re-parses thousands of lines on the input/render thread.
  • Fix: Parse in LiveCaptureWorker before publishing. Add parsed Text<'static> and line count to CaptureFrame, and have store_capture accept them. ensure_parsed then only collects links on the UI thread.
  • Verifier: ensure_parsed does run parse_output_text on the UI thread, once per new content, and it is already timed in preview_timings.parse. It matters only with deep scrollback, where capture_lines grows. Moving parse to the worker is feasible but changes CaptureFrame and store_capture contracts. Measure first.
  • Measure: Log preview_timings.parse with capture_lines at 5000 during live-send scrollback; act if p95 exceeds a few ms.

#147 TUI forks tmux for display snapshots every second for its whole lifetime

  • Impact low, effort M, verdict partly, evidence proven-by-code, area tui-loop-home, category subprocess
  • Where: src/tui/app.rs:621-624, src/tmux/mod.rs:2610-2641, src/tmux/mod.rs:2106
  • Frequency: Every ~1s (CACHE_TTL/2), two tmux forks (session scan + pane meta), regardless of activity or session count
  • Problem: spawn_snapshot_poller refreshes the session and pane-meta caches nonstop, even when the TUI is idle, no preview is shown, and the daemon already observes the same panes. A user running the TUI all day pays about 170k tmux forks per day per TUI instance.
  • Fix: Spawn the poller on demand when a consumer needs pane meta (preview shown, Terminal view, passive fleet). Park it with a longer timeout (5s) when the view is idle or live-send is off. Or source pane presence and window size from the daemon's runtime rows instead.
  • Verifier: Poller exists as claimed (park_timeout CACHE_TTL/2, two forks, due-gated). But the session and pane caches feed list rows and status for every consumer, not just previews. Cost is two short forks per second, about 0.1 percent CPU. On-demand parking adds staleness risk.
  • Measure: Run sudo fs_usage -w -f exec or ps sampling against an idle aoe TUI for 60s; count tmux execs and CPU.

#148 Every printable keystroke waits 5ms for Mosh paste-burst detection

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tui-loop-home, category latency
  • Where: src/tui/app.rs:31-34, src/tui/app.rs:766-797, src/tui/home/overlays.rs:233-247
  • Frequency: Per printable key on the home view and in live-send (no-dialog or paste dialogs)
  • Problem: The burst detector exists because Mosh strips bracketed paste markers. But it runs for every user, holding each printable key for PASTE_BURST_INTER_KEY_MS before dispatch. That adds a fixed 5ms to live-send echo latency and to j/k navigation even on terminals with working bracketed paste.
  • Fix: Gate the burst branch in App::run on self.mosh_active (already known at startup), or on a config opt-in, so non-Mosh terminals dispatch keys immediately.
  • Verifier: 5ms hold per printable key is real (app.rs:766-797), but imperceptible. Gating on mosh_active would regress non-bracketed-paste terminals, since burst detection is a general fallback, not Mosh-only. Fix would need a safer signal; win is about 5ms.
  • Measure: Time key-event receipt to dispatch in App::run with Instant logging during typing in live-send; expect at most 5ms.

#149 Activity file rewritten on every key and mouse event

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area tui-loop-home, category disk-io
  • Where: src/tui/app.rs:763, src/tui/app.rs:919-921, src/tui/app.rs:1188, src/session/mod.rs:1168-1173, src/session/mod.rs:1188-1213, src/tui/app.rs:1473-1480
  • Frequency: Per keypress, paste, click and wheel tick; presence dir scan every 3s
  • Problem: write_tui_activity runs get_app_dir (stat), create_dir_all, and fs::write (open/truncate/close) synchronously on the UI thread for each input event, including fast wheel scrolling. The only consumer checks freshness against a 30s window, so writes more often than every few seconds are wasted. count_active_tuis also read_dirs and stats on the UI thread every 3s.
  • Fix: Track last_activity_write: Instant in App and call write_tui_activity at most once every 5s. Move presence counting and heartbeat writes onto the existing serve_probe-style Worker.
  • Verifier: write_tui_activity does stat, mkdir and open/truncate/write on the UI thread per key, paste, click and wheel tick (app.rs:763,919,1188). Cost is tens of microseconds each. Throttling to 5s is safe against the 30s window. Presence scan every 3s is trivial.
  • Measure: Use dtruss -c -p <pid> or perf during fast wheel scrolling; count open/write syscalls per second.

#150 Last-prompt footer spawns a thread and captures 4000 lines every 1.5s

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area tui-loop-home, category subprocess
  • Where: src/tui/home/last_prompt.rs:38-43, src/tui/home/last_prompt.rs:153-196, src/tui/home/render.rs:1171-1172
  • Frequency: Every 1.5s while Ctrl+L footer is on and frames render (8+ fps with animated sessions)
  • Problem: refresh_last_prompt is render-driven. Once the cache is 1.5s old it spawns a new OS thread that forks tmux capture-pane for 4000 scrollback lines and scans them, even when the pane content has not changed since the last scrape.
  • Fix: Re-scrape only when the preview capture worker's generation for the displayed pane advanced (PreviewCache.capture_generation changed) and 1.5s have passed. Run the scrape on a long-lived Worker instead of std::thread::spawn per scrape.
  • Verifier: Render-driven refresh_last_prompt_at spawns std::thread and runs capture-pane for 4000 lines every 1.5s whenever stale, regardless of content change (last_prompt.rs:153-196). Only when the Ctrl+L footer is on. Generation gating is feasible if preview capture covers scrollback; otherwise reuse a Worker.
  • Measure: Enable Ctrl+L footer on a long-scrollback pane; sample tmux capture-pane exec rate and CPU with fs_usage or ps for 60s.

#151 Plugin UI badges polled over HTTP every 3s with daemon rediscovery

  • Impact low, effort M, verdict partly, evidence proven-by-code, area tui-loop-home, category network
  • Where: src/tui/plugin_ui_poller.rs:10, src/tui/plugin_ui_poller.rs:55-100, src/tui/plugin_ui_poller.rs:141-156, src/tui/home/status.rs:12-14
  • Frequency: Every 3s while any session exists, for the TUI lifetime
  • Problem: request_plugin_ui_refresh is called every tick and fires a fetch every 3s. Each fetch runs locate_daemon (discovery file reads), builds a new HttpClient, and GETs the full plugin UI snapshot, even when plugins publish nothing. The TUI already holds a daemon WebSocket (session_feed) that could carry these changes.
  • Fix: Push plugin UI snapshot changes over the existing runtime WS feed, or add a revision or ETag to plugin_ui_state and skip apply on 304. At minimum, reuse one HttpClient and endpoint across fetches in PluginUiPoller instead of rediscovering per poll.
  • Verifier: Poll is already on a Worker thread, gated by 3s interval and pending flag (plugin_ui_poller.rs). Each fetch does discover, a new HttpClient, a health_check, then GET, so two loopback requests per 3s. Real but trivial. Reusing a client is S; WS push is M.
  • Measure: Run the daemon with request tracing; count GET /health and plugin UI requests per minute from an idle TUI, and daemon CPU.

4.tui-views

#152 Row reconcile is a linear scan per delta and O(N^2) on snapshot merge

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area tui-views, category cpu
  • Where: src/tui/structured_view/reducer.rs:256-271, src/acp/transcript.rs:1030-1054, src/acp/transcript.rs:328-335, src/tui/structured_view/mod.rs:488-491, src/tui/structured_view/mod.rs:1919-1930
  • Frequency: Per transcript_delta (per token chunk); per transcript_snapshot on connect/reconnect after the initial ?view=rows reseed
  • Problem: The daemon emits one row per message chunk, so rows reach tens of thousands. upsert/patch use rows.iter().position from the front comparing String ids, though new rows land at the tail. merge_server_rows on the full WS snapshot after the replay reseed is N upserts of O(N) each.
  • Fix: Use rposition (tail search) in upsert_transcript_row and patch_transcript_row; in AcpTranscript::merge_server_rows build a HashMap<String, usize> id index once (or keep one on AcpTranscript, rebuilt on Remove/drop_rows).
  • Verifier: upsert (transcript.rs:1032) uses position; new Append ids miss and scan all N, so rposition does not help appends, only tail patches. Per-delta cost is N string compares, dwarfed by the per-frame rebuild. Real issue is merge_server_rows on connect snapshot after replay: N^2/2 compares; fix with a one-shot HashMap id index there.
  • Measure: Time merge_server_rows in a unit bench with 20k msg-{seq} rows merged over an identical 20k-row vec.

#153 Disconnected structured view stalls input 200 ms per loop

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area tui-views, category latency
  • Where: src/tui/structured_view/mod.rs:388-397, src/tui/structured_view/mod.rs:1089-1092, src/tui/structured_view/embedded.rs:474-484
  • Frequency: Every loop iteration while state.ws is None (after a failed reconnect), indefinitely
  • Problem: recv_ws returns None immediately when there is no socket, and the arm body sleeps 200 ms inside the select, so keystrokes and redraws wait up to 200 ms and the loop wakes 5 times a second for nothing. EmbeddedView::next_event already handles this with pending().
  • Fix: In recv_ws, return std::future::pending().await when state.ws is None, and drop the sleep in the None arm (keep it only for a closed channel, or set state.ws = None there as embedded apply_event does).
  • Verifier: After a failed reconnect (mod.rs:549) ws stays None forever; recv_ws returns None instantly and the arm sleeps 200ms. With biased select the ws arm also starves the plugin and redraw_ticker arms. Only reached when daemon is down, so user impact is limited. embedded.rs already uses pending.
  • Measure: Kill daemon with a structured view open, wait for reconnect failure, then time keypress to redraw via tracing on handle_terminal_event.

#154 Diff view runs git2 diffs synchronously in the draw path and retries failures every frame

  • Impact low, effort M, verdict partly, evidence proven-by-code, area tui-views, category latency
  • Where: src/tui/home/render.rs:1159-1164, src/tui/diff/mod.rs:262-283, src/tui/diff/mod.rs:286-305, src/tui/diff/mod.rs:148-180, src/tui/diff/mod.rs:225-241, src/git/diff.rs:86-120
  • Frequency: Diff open, refresh, branch change, first view of each file; on error every draw (keystrokes, 120 ms spinner ticks)
  • Problem: get_current_diff/get_current_file_contents are called inside draw and compute git diffs plus TextDiff on the UI thread; compute_changed_files prints a full patch of every changed and untracked file just to count lines. On Err nothing is cached, so a failing file recomputes the repo open and diff on every frame.
  • Fix: Store Err results in diff_cache (HashMap<PathBuf, Result<FileDiff, String>>). Move compute_file_diff and compute_changed_files into tokio::task::spawn_blocking with the existing "Loading diff..." placeholder, polling a oneshot in DiffView. In git/diff.rs count lines with git2::Patch::line_stats instead of DiffFormat::Patch printing.
  • Verifier: Ok results are cached in diff_cache, so git2 work runs once per file per refresh, not per frame. Err is not cached and retries per draw, but draws only happen on input or 120ms spinner when sessions animate, and errors are rare. Caching Err is an S fix; spawn_blocking is optional.
  • Measure: Time compute_changed_files and compute_file_diff with tracing spans on a repo with 500 changed files and a 10k-line file.

#155 Diff pane rebuilds every line of the file diff (or re-renders whole Markdown) per frame

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area tui-views, category render
  • Where: src/tui/diff/render.rs:311-316, src/tui/diff/render.rs:328-392, src/tui/diff/render.rs:418-437, src/tui/markdown.rs:15-21
  • Frequency: Every draw while the diff view is open (keystrokes, scroll, 120 ms spinner ticks)
  • Problem: render_diff_content formats every hunk line (number strings, content clones, split-row pairing) into a Vec and then keeps only visible_lines. Rendered-Markdown mode reparses and rewraps the whole file every frame. Cost is O(file diff size) per frame, so scrolling a large diff stutters.
  • Fix: Cache the built Vec<Line<'static>> in DiffView keyed by (selected path, split_view, inner.width, markdown_rendered), cleared in refresh_files and select_branch; slice the visible window from the cache in render_scrolled_lines.
  • Verifier: render.rs:328-392 formats every hunk line then render_scrollable_lines keeps only visible ones; Markdown mode calls render_wrapped on the full file each draw. Draws happen per key/scroll and every 120ms when any session animates (app.rs:1498). Cache key must also include theme and selected_file.
  • Measure: Add an elapsed trace around the diff content render; scroll a 5000-line diff and compare per-frame ms.

#156 Plugin UI polling rebuilds HTTP clients and health-checks every 3 s, duplicated per view

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tui-views, category network
  • Where: src/tui/plugin_ui_poller.rs:10, src/tui/plugin_ui_poller.rs:55-101, src/tui/plugin_ui_poller.rs:107-124, src/acp/client/daemon_manager.rs:41-60, src/tui/structured_view/mod.rs:51, src/tui/structured_view/mod.rs:268-318
  • Frequency: Every 3 s while the home TUI has sessions; plus every 3 s per open structured view (embedded or full-screen)
  • Problem: fetch_plugin_ui calls locate_daemon (file discovery, new reqwest Client, /health request) then builds a second HttpClient, so each poll creates two clients and new loopback connections. The structured view runs its own parallel poller fetching the same snapshot plus plugin_commands, which rarely change.
  • Fix: Keep one HttpClient inside PluginUiPoller and re-run locate_daemon only after a transport error. Feed EmbeddedView from the home PluginUiState instead of spawning its own task. Fetch plugin_commands only when UiSnapshot.revisions changes.
  • Verifier: Claim holds: fetch_plugin_ui calls locate_daemon (discover, new client, /health) then HttpClient::new again, every 3s. But it is loopback, off-thread, ~ms cost. Structured view's separate poller already reuses state.http and plugin_commands is cheap. Only the home poller is worth a small fix.
  • Measure: Run aoe with a session, strace/dtrace connect() counts on daemon port over 60s; expect about 20 polls with 2 connections each.

#157 Settings search rebuilds every category's fields (with disk reads) per keystroke

  • Impact low, effort M, verdict confirmed, evidence proven-by-code, area tui-views, category latency
  • Where: src/tui/settings/input.rs:435-441, src/tui/settings/mod.rs:1010-1059, src/tui/settings/fields.rs:699-720, src/tui/settings/fields.rs:464-505, src/tui/settings/fields.rs:509-525, src/tui/styles/mod.rs:74-133
  • Frequency: Per keystroke in the settings search box
  • Problem: recompute_search_hits calls build_fields_for_category for every category; each serializes Config and ProfileConfig to serde_json twice and clones and merges them. Building the Theme row scans the themes dir twice plus the plugin registry, and the smart-rename row runs Config::load_or_warn (disk read and TOML parse) plus an agent availability snapshot.
  • Fix: Build the search corpus once when search opens (Vec of category, ident, lowercased title/full, label, value), rebuilt only after apply_field_to_config; filter that per keystroke. At minimum, compute base_json/over_json/effective_json once and pass them into a build_fields_for_category variant.
  • Verifier: recompute_search_hits calls build_fields_for_category per tab per keystroke, each re-serializing Config twice. smart-rename row calls Config::load_or_warn (disk+TOML parse) plus agent snapshot. Real redundancy, but keystroke-bound on UI thread; likely a few ms to tens of ms total.
  • Measure: Wrap recompute_search_hits in Instant::now() with tracing::debug; type in settings search with a large config and read elapsed.

#158 Preview info header canonicalizes paths on every frame

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area tui-views, category disk-io
  • Where: src/tui/components/preview.rs:588-603, src/tui/components/preview.rs:192-196, src/tui/components/preview.rs:319-322, src/tui/components/preview.rs:392-397
  • Frequency: Every home draw with the preview info header visible (120 ms spinner tick, per key); 2 to 4 realpath calls per frame
  • Problem: shorten_path calls dirs::home_dir plus canonicalize on the project path, the home dir, and the worktree main repo path in render. Each is a chain of lstat syscalls on the UI thread. On slow or network filesystems this stalls the frame.
  • Fix: Canonicalize home once in a OnceLock, and memoize shorten_path results in a HashMap<String, String> on HomeView (or store the display path on Instance when it is loaded).
  • Verifier: shorten_path canonicalizes path and home with no cache, called 2 to 3 times per preview render (lines 185/337/397). Syscalls hit warm dentry cache locally, microseconds. Only matters on network or slow filesystems; a small memo or OnceLock for home is trivial and safe.
  • Measure: dtruss/strace -c on aoe TUI idle with a session selected; count lstat/readlink per second; or time shorten_path on an NFS path.

#159 Trashed-session reader re-polls the retained replay every 2 s indefinitely

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area tui-views, category network
  • Where: src/tui/structured_view/embedded.rs:40, src/tui/structured_view/embedded.rs:150-198, src/tui/structured_view/embedded.rs:206-213
  • Frequency: Every 2 s while a trashed ACP session is selected in the home list
  • Problem: RetainedView::tick starts an HTTP identity probe every RETAINED_REFRESH_INTERVAL even though a trashed session's history is normally frozen; on rediscover, start_read also runs the synchronous discover() on the UI thread.
  • Fix: Back off the interval (2 s doubling to 30 s) while replays come back unchanged (Ok(None) or changed == false), resetting on change or error; run discover inside the spawned load task.
  • Verifier: The 2 s poll holds, but it is one tiny page request (limit 1) over local HTTP, and only while a trashed session is selected. Backoff would be sound. The sync discover() runs only after an error (rediscover=true), and it is a pid-file check plus env reads, so it is not a UI-thread problem.
  • Measure: Select a trashed ACP session and count daemon requests/s in the daemon access log; expect 0.5 small requests per second.

#160 Diff file-list resize rewrites state.toml on every h/l keypress

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tui-views, category disk-io
  • Where: src/tui/diff/mod.rs:481-494, src/session/config/mod.rs:4403-4413
  • Frequency: Per h/l keypress (key repeat when held)
  • Problem: shrink_file_list/grow_file_list call update_app_state each time, which locks, parses, re-serializes and rewrites the whole TOML state file synchronously on the UI thread.
  • Fix: Only update file_list_width in memory on h/l and call save_file_list_width once when the diff view closes (DiffAction::Close handling).
  • Verifier: Claim true: each h/l runs flock, parse and rewrite of a small state.toml on the UI thread. Cost is sub-millisecond for a small file, even at key repeat. Save-on-close would also lose the width on a crash, and the close path has multiple exits. Real but negligible.
  • Measure: Time update_app_state with strace/dtruss or a tracing span while holding l in the diff view; expect sub-ms writes.

#161 Plugin pane overlay re-wraps all pane lines every frame

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tui-views, category render
  • Where: src/tui/structured_view/render.rs:285-310
  • Frequency: Every redraw while the plugin pane overlay is open (8.3 Hz tick plus events)
  • Problem: render_pane_panel rebuilds pane_lines and home_pane_lines from JSON payloads and wraps every line at panel width each frame, though the snapshot only changes every 3 s.
  • Fix: Cache the wrapped lines on StructuredViewState keyed by (plugin snapshot revisions, inner.width, theme), invalidated in ingest_plugin_ui.
  • Verifier: Code does rebuild and wrap every frame with no cache. But this is an opt-in overlay with a small payload, and the structured view only redraws on events or ticks. Each frame costs tens of microseconds for typical payloads. Cache needs invalidation on width and theme.
  • Measure: Add a tracing timer around pane_lines plus wrap loop in render_pane_panel with a large plugin snapshot; compare to frame budget.

#162 Session command writer awaits non-preparation mutations serially

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area tui-views, category concurrency
  • Where: src/tui/session_feed.rs:433-505, src/tui/session_feed.rs:507-516
  • Frequency: Per queued session mutation (rename, trash, purge, access, unread)
  • Problem: run_command_writer awaits run_queued_command inline for every non-creation, non-preparation request, so a slow trash or purge for one session delays an unrelated Access/Unread or rename for another session. The only parallel lanes are creations and preparations. No comment says that cross-session ordering is required.
  • Fix: If only per-session ordering matters, spawn non-preparation commands into a JoinSet keyed per session id (serial per id, parallel across ids), keeping the existing grant/lease checks inside run_queued_command.
  • Verifier: Serial await of non-creation, non-preparation commands is real (session_feed.rs:496-508). Serial order is probably deliberate: it preserves per-session ordering and grant/lease checks, and the commands are quick daemon HTTP calls. Parallelizing risks reordering rename, trash and purge. Only worthwhile if slow purges are measured.
  • Measure: Log latency of run_queued_command per kind in the writer; look for Access/Unread waiting behind a trash or purge.

4.server-api-sessions

#163 Runtime snapshot rebuild runs ~7 SQLite queries per structured session on the writer connection, under the instances read lock, every 500ms

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area server-api-sessions, category cpu
  • Where: src/server/api/sessions/list.rs:40-129, src/server/runtime.rs:787-803, src/acp/event_store/turns.rs:127-134, src/acp/event_store/turns.rs:417-441, src/acp/event_store/wakeups.rs:13-90, src/acp/event_store/mod.rs:196-198
  • Frequency: publish_loop: every 500ms with any WS subscriber, every 2s with none (idle daemon too); also every mutation response
  • Problem: project_sessions calls latest_plan, latest_pending_wakeup, latest_active_monitor (up to 4 queries) and pending_approval_requests per live structured row, each via conn() (the writer mutex), with format!-built SQL and full JSON decode of the event row. It runs on an async worker while holding state.instances.read(). Cost scales with session count and contends with event writes.
  • Fix: Move the per-row event-store overlay into one spawn_blocking batch after cloning row ids, use reader() instead of conn(), and replace the per-session queries with one grouped query per kind (WHERE session_id IN (...) GROUP BY session_id, MAX(seq)). Better: cache these overlays per session keyed on EventStore highest_seq and recompute only when it advances.
  • Verifier: Claim holds: latest_plan/wakeup/monitor use conn() under instances.read() every publish. But each is an indexed point lookup (idx session_discriminant_seq), approvals only run for Running workers, archived rows skip wakeup/monitor. reader() exists, so switching is S; seq-keyed overlay cache is the real win.
  • Measure: Wrap the sessions map in project_sessions with Instant timing, log at 500ms ticks with 50+ structured sessions while an agent streams events.

#164 Every session mutation and several GETs force a full synchronous publish

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area server-api-sessions, category latency
  • Where: src/server/runtime.rs:541-559, src/server/runtime.rs:278-288, src/server/api/projects.rs:110, src/server/api/acp/view.rs:20-24, src/server/api/sessions/ensure.rs:326, src/server/api/groups.rs:688
  • Frequency: Per mutation request (pin, favorite, unread, rename, group, archive, ensure, view switch) and per GET /api/projects
  • Problem: session_mutation_response and peers call runtime.publish, which takes publish_lane and rebuilds every SessionResponse (all SQLite and config work above) just to return one row. list_projects, a read, also calls publish instead of snapshot. Requests serialize on publish_lane with the 500ms loop, so mutation latency scales with total session count.
  • Fix: In list_projects use runtime.snapshot(). For mutations, once the overlays above are cached, publish becomes cheap; alternatively let publish reuse the previous snapshot's rows for unchanged sessions by tracking a dirty set of ids from the mutation path.
  • Verifier: Mutations and list_projects do call runtime.publish, serialized on publish_lane. But publish gives read-your-writes cursor semantics; snapshot() can be up to 500ms stale after a project mutation. Mutations are user-paced. Fixing findings 0 and 1 makes publish cheap; switching to snapshot risks stale reads.
  • Measure: Measure p50/p95 latency of POST pin/rename with 100 sessions via curl -w time_total before and after config caching.

#165 Diff files poll recomputes full working-tree diff every 10s; 1.5s cache TTL never hits

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area server-api-sessions, category cpu
  • Where: src/server/api/sessions/diff.rs:254-344, src/server/state.rs:98, src/server/state.rs:432-462, web/src/hooks/useDiffFiles.ts:6, web/src/hooks/useDiffFiles.ts:88-92
  • Frequency: Every 10s per open diff panel, per repo in a workspace session
  • Problem: Each poll loads config.toml (Config::load_or_warn), opens the repo 3-4 times (is_outside_repository, get_default_base_ref, check_merge_base_status, compute_changed_files) and recomputes changed files with line stats. CHANGED_FILES_TTL is 1.5s, so the 10s poll always misses. The body is built via serde_json::to_value then reserialized, and the client dedupes with JSON.stringify.
  • Fix: Open the git2 Repository once per repo and pass it to the helpers. Return an ETag over the response (hash of files and bases) and honor If-None-Match to return 304. Use Json(resp) directly instead of to_value. Optionally raise CHANGED_FILES_TTL to cover the poll interval with invalidation on HEAD/index mtime.
  • Verifier: 10s poll does miss the 1.5s TTL, but the TTL is documented as burst dedup only; raising it serves stale lists. Dominant cost is the inherent workdir diff scan; extra repo opens and to_value are minor. ETag still requires computing the diff, saving only payload and React work.
  • Measure: Time compute_changed_files versus the whole spawn_blocking body in session_diff_files on a large repo with tracing spans.

#166 Transcript cold open fetches each replay page twice and decodes it on the async runtime

  • Impact low, effort M, verdict partly, evidence proven-by-code, area server-api-sessions, category latency
  • Where: src/server/api/acp/history.rs:448-531, web/src/hooks/acpSession/replay.ts:33-34, web/src/hooks/acpSession/replay.ts:9-11
  • Frequency: Per session open and per WS lag recovery; up to 5 pages x 2 requests of 1000 events
  • Problem: getReplayPair requests the same window twice (frames and view=rows), so the server scans and JSON-decodes up to 1000 events twice per page. acp_replay runs replay_page, prior_message_marker (which can walk backward through all history) and the TranscriptModel fold directly in the async handler, without spawn_blocking.
  • Fix: Add a view that returns both frames and rows from one page read (e.g. view=both), or have the rows request include the control frames. Wrap the page read, prior_message_marker and fold in tokio::task::spawn_blocking.
  • Verifier: Only the tail page (replay.ts:86) and forward legs="both" pages are fetched twice. The up-to-5 older cold-open pages are rows-only. acp_replay (history.rs:420-503) does run synchronous SQLite scans, JSON decoding and the fold on the async worker, with no spawn_blocking. prior_message_marker rarely walks far because before-pages are trimmed to user-turn boundaries. Win: one fewer 1000-event decode per open.
  • Measure: Add tracing span timing around replay_page plus fold in acp_replay, then cold-open a 50k-event session and compare p95 latency for view=rows vs frames.

#167 Context primer and attachment reads run synchronous SQLite on the async runtime

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area server-api-sessions, category concurrency
  • Where: src/server/api/acp/history.rs:337-363, src/server/api/acp/prompt.rs:629-652, src/acp/event_store/replay.rs:24-34, src/acp/event_store/attachments.rs:41-47
  • Frequency: Context primer: after a failed session/load; attachment: per image in an opened transcript (immutable cached afterwards)
  • Problem: acp_context_primer calls replay_before, which decodes the whole retained history below before_seq, inline in the handler. acp_attachment loads up to 10 MB blobs through conn() (the writer mutex) inline. Both block a Tokio worker and the attachment read also stalls event writes.
  • Fix: Wrap both in spawn_blocking. Add a reader()-based load_attachment. For the primer, scan only the tail the primer's max_chars can use (page backward with replay_page_before until the budget fills).
  • Verifier: Code matches. Primer already uses reader(), not the writer, and fires only after a failed session/load. Attachment read uses the writer conn() inline, but is immutable-cached by the browser, so it is one-time per image. Worth spawn_blocking only for very large histories.
  • Measure: Time acp_context_primer on a session with 100k events; log tokio worker block time.

#168 Queue enqueue loads full attachment blobs just to sum their sizes

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-sessions, category memory
  • Where: src/server/api/queue.rs:178-221, src/acp/event_store/attachments.rs:51-98
  • Frequency: Per enqueue or queued prompt carrying attachments, and per re-enqueue of an existing id
  • Problem: buffer_and_enqueue calls load_pending_attachments_for_ref to compute existing bytes (reads every blob, up to 64 MB per session), then calls it again for replaced_blobs. Each record_pending_attachment is a separate write on the writer mutex. All run inline on the async runtime.
  • Fix: Add EventStore::pending_attachment_bytes_for_ref (SELECT SUM(length(data))) for the cap check; only load blobs when the row is actually being replaced. Insert blobs in one transaction inside spawn_blocking.
  • Verifier: Confirmed: existing_for_prompt loads full blobs (queue.rs:~184) just to sum sizes, even when the prompt id is not queued, and a SUM query would suffice. It only runs on enqueue with attachments, and the per-session cap is 64 MB. Rare, human-rate path.
  • Measure: Enqueue 10 x 6 MB images with a re-post; time buffer_and_enqueue and writer-mutex hold.

#169 File viewer provenance fallback replays and decodes the whole event log per request

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-sessions, category cpu
  • Where: src/server/api/sessions/diff.rs:665-697, src/server/api/file_provenance.rs:50-91, src/server/api/file_provenance.rs:162-172
  • Frequency: Per file-viewer read or version check of a path outside the project roots (e.g. plan files, /tmp)
  • Problem: The touched closure pages through every event in the session and decodes each one, including large message chunks, to find tool-call paths, then canonicalizes every touched path (one syscall each). A ponytail comment accepts this; TextFileEditor also calls the endpoint with version_only before saves, so it repeats on the same path.
  • Fix: Query only ToolCallStarted/ToolCallUpdated discriminants in SQL. Check exact-string matches before canonicalizing, and cache the touched set per session keyed on highest_seq so repeated reads pay only for new events.
  • Verifier: Closure is lazy and runs only for paths outside all roots; the code itself carries a ponytail note. Full replay plus a canonicalize per touched path is real, but it is a rare miss path. A per-session cache keyed on highest_seq is a sound fix.
  • Measure: Time GET file endpoint for /tmp path on a session with 50k events; log elapsed around the touched closure in SessionFileScope::confine.

#170 Single-file diff builds a serde_json::Value copy of up to 5 MB of file contents

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area server-api-sessions, category memory
  • Where: src/server/api/sessions/diff.rs:463-512, src/server/api/sessions/diff.rs:515-516
  • Frequency: Per file opened in the diff panel
  • Problem: RichFileContentsResponse (old_content, new_content, patch, up to 5 MB) is converted with serde_json::to_value, which copies every string into a Value tree, and is then serialized again by Json. Peak memory is about doubled and an extra full pass runs per request.
  • Fix: Return the typed struct from the blocking closure and respond with Json(resp) directly; same for session_diff_files and list_branches, which also use to_value.
  • Verifier: to_value at diff.rs:463 and 511 copies strings into a Value tree, then Json serializes it again. Payload is capped by MAX_CONTENTS_BYTES, and it is a user-click-driven request. Returning the typed struct is trivial and safe. Also applies at diff.rs:338 and git.rs:291.
  • Measure: Open a 4 MB changed file in the diff panel and compare handler peak RSS and latency, before and after, with dhat or a timing log.

#171 list_branches spawns a git subprocess beside the libgit2 listing

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-sessions, category subprocess
  • Where: src/server/api/git.rs:243-256
  • Frequency: Per branch picker open (wizard base branch, extra repos, diff BasePicker)
  • Problem: Each call forks git branch --show-current even though the same blocking closure then opens the repo through libgit2 to list branches.
  • Fix: Read the current branch with git2 (repo.head()?.shorthand()) inside list_branches_with_remotes/list_branches, or open the repo once and derive both from it.
  • Verifier: The git branch --show-current fork at git.rs:250 is real, but it runs once per picker open inside spawn_blocking, costing a few ms. Replacing it with repo.head() shorthand is easy. Detached HEAD gives empty string with git, so shorthand must be handled to match.
  • Measure: Time the list_branches handler with and without the fork, using a tracing span around the Command call.

4.server-api-system

#172 GET /api/agents runs full adapter probing twice per agent, and is hit at every page load for display names

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area server-api-system, category latency
  • Where: src/server/api/system.rs:247-490, src/session/builder.rs:1514-1590, src/acp/acp_client/resolve_command.rs:34-170, web/src/lib/agentDisplayName.ts:17-25
  • Frequency: Every dashboard load and tab, plus wizard, settings agent widgets and usage-limit banner. Scales with agent count (~30) x 2 calls.
  • Problem: list_agents calls adapter_installed for acp_installed and again for acp_create_ready per agent. Each rebuilds AgentRegistry::with_defaults, walks PATH, and via resolve_agent_command may spawn <adapter> --version (up to 2s, path_copy_below_floor) or scan nvm/fnm dirs. The caller agentDisplayName only needs names.
  • Fix: Memoize list_agents per (profile,path,scratch) for ~5s and the version probe per (path,mtime). Skip the second adapter_installed when create_config is None and hooks closure is false. Give agentDisplayName a names-only query (?fields=names) that skips probing.
  • Verifier: Double adapter_installed per agent is real (system.rs:431,439). But agentDisplayName fetches once per page load (requested flag), not per tab or poll. The 2s --version probe runs only when an agent has both a PATH copy and a bundled copy with a version gate. Reusing acp_installed when no project and hooks are false is safe. A TTL cache would break the documented uncached nvm behavior.
  • Measure: Run time curl -s localhost:8081/api/agents with the bundled claude adapter plus a PATH copy installed, and count --version spawns with dtrace or execsnoop.

#173 system_health deep-clones all Instances twice and does a full uncoalesced sample per request

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-system, category cpu
  • Where: src/server/api/system.rs:2114-2150, src/process/metrics.rs:176-215, src/process/metrics.rs:330-345, web/src/hooks/useSystemHealth.ts:5-60
  • Frequency: Every 500ms per client while the drill-down is open, every 15s collapsed; per client, so N dashboards multiply it. Scales with session count and host process count.
  • Problem: Handler clones the whole instances Vec under the read lock, then aggregate_agents clones the eligible ones again. Every request also does a process-table scan, tmux list-panes subprocess, worker_registry::list() disk read and container stats, with no shared snapshot between concurrent clients.
  • Fix: In system_health filter with eligible_instance under the read lock and pass only needed fields (id,title,status,sandbox name) instead of clone(). Cache the last MetricsSnapshot in AppState and reuse it when younger than ~400ms so concurrent pollers share one sample.
  • Verifier: Cloning about 30 Instances costs microseconds next to the process scan and the tmux subprocess, so that part is negligible. The client already polls one request at a time, at 500ms only while the detail is open and 15s collapsed, and stops on a hidden tab. Sharing one cached snapshot under ~400ms helps only when several dashboards have the detail open at once.
  • Measure: Add a tracing span around sampler.sample in system_health, then compare p50 sample time with clone time while 2 dashboards have the drill-down open.

#174 Sandbox image status re-parses config once per profile on every request

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-system, category latency
  • Where: src/server/api/sandbox_image.rs:225-250, src/server/api/sandbox_image.rs:340-380, web/src/hooks/useSandboxImageBanner.ts:6-94, src/session/config/profile_config.rs:183-196
  • Frequency: Each status request: hourly poll, every 2s during an image pull, per wizard image change. Scales with profile count.
  • Problem: load_configured runs Config::load then resolve_config(profile) for each profile, and resolve_config reloads global config.toml, state.toml and the profile file each time (plus installs status rules). It runs before the 15-minute status cache is consulted, so cached answers still cost P+1 full config parses.
  • Fix: In load_configured load Config once, then use load_profile_config + merge_configs(global.clone(), &pc) per profile, or read only sandbox.default_image. Optionally cache Configured keyed on config mtimes.
  • Verifier: Claim holds: load_configured calls resolve_config per profile (reloads global each time) before the image cache. But it runs in spawn_blocking, hourly or every 2s only during a pull, and parses small TOML. Fix must keep status-rule install side effect.
  • Measure: Time load_configured with 10 profiles via a tracing span or criterion bench; expect well under 5 ms.

#175 Plugin update check runs serially and builds a new GitHub client per plugin

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area server-api-system, category network
  • Where: src/plugin/update_check.rs:23-42, src/plugin/update_check.rs:68-95, src/plugin/fetch.rs:262-289, src/server/api/plugins.rs:409-414
  • Frequency: Per click of Check for updates, plus the auto-update sweep and TUI/CLI. Latency is the sum over installed external plugins.
  • Problem: outdated() awaits check_one per plugin in a for loop. Each does a GitHub release API call through a freshly built GitHubClient (new connection pool and TLS handshake) and a git ls-remote subprocess, so total time grows linearly with plugin count.
  • Fix: In update_check::outdated use futures::stream::iter(targets).map(check_one).buffer_unordered(4). Build one GitHubClient in outdated() and pass it to latest_release_tag.
  • Verifier: outdated() awaits check_one serially (update_check.rs:37). latest_release_tag builds a new GitHubClient per plugin (fetch.rs:278). Callers are on-demand only: the dashboard button, the TUI manager, the CLI, and the auto_update sweep. Plugin count is usually a handful, so the win is a few seconds per check. buffer_unordered(4) is safe because the results are sorted after.
  • Measure: Run time aoe plugin outdated with 5 GitHub-sourced plugins installed, before and after adding buffer_unordered.

#176 GET /api/system/logs reads up to 4 MB and collects every line to return 500

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-system, category disk-io
  • Where: src/server/api/logs.rs:105-135, web/src/components/settings/LogsSettings.tsx:5-30
  • Frequency: Per open and refresh of the Logs settings tab. Scales with log file size (up to MAX_TAIL_BYTES) rather than requested lines.
  • Problem: read_tail always seeks back MAX_TAIL_BYTES, read_to_end into a Vec, from_utf8_lossy converts all of it, and text.lines().collect() builds a Vec of every line, then discards all but the last lines.
  • Fix: In read_tail read backwards in 64 KB chunks, counting b'\n' until lines+1 are found or MAX_TAIL_BYTES is hit, then decode only that slice.
  • Verifier: Code matches: always seeks back up to 4 MiB, read_to_end, lossy decode, collects all lines. Only on user opening or refreshing the Logs tab, so a few ms. Chunked backward read is safe but the win is negligible.
  • Measure: Time read_tail on a 4 MiB log with lines=500 in a unit test via std::time::Instant.

#177 Sync config/disk reads on async workers in frequently polled handlers (about, update-status, settings, tips, web-ui-state)

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-system, category latency
  • Where: src/server/api/system.rs:2304-2312, src/server/api/system.rs:2384-2390, src/server/api/system.rs:530-545, src/server/api/system.rs:1620-1630, src/server/api/mcp.rs:36-44
  • Frequency: /api/about on load, reconnect, visibility (30s throttle), by several hooks; update-status hourly; settings GET per settings view. Each parses config.toml, state.toml and the profile file.
  • Problem: get_about, get_update_status, get_settings and mcp resolve_agent call resolve_config_or_warn / resolve_config directly in the async handler (std::fs plus TOML parse and schema-wide merge_configs). Under load these stall a runtime worker. get_tips and get_web_ui_state parse the whole Config only to read state.toml.
  • Fix: Wrap those calls in tokio::task::spawn_blocking as update_settings does. In get_tips and get_web_ui_state use AppStateConfig::load() instead of Config::load(). Cache the ACP fields of get_about in AppState, invalidated in save_settings_patch.
  • Verifier: get_about, get_update_status, get_settings call sync resolve_config in async handlers (true). get_tips and get_web_ui_state already use spawn_blocking; Config::load already loads AppStateConfig, so the swap only skips the main parse. Small files, throttled polls; stall is sub-millisecond.
  • Measure: Hit /api/about in a loop with wrk while tokio-console or tracing shows poll duration of get_about.

#178 Settings PATCH clones the full runtime schema twice and holds the global write gate across I/O

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-system, category cpu
  • Where: src/server/api/system.rs:759-765, src/server/api/system.rs:810-815, src/session/config/settings_schema/registry.rs:17-56, src/server/api/system.rs:857-900
  • Frequency: Per settings save (each toggle) and per GET /api/settings/schema. Scales with descriptor count (hundreds) and plugin count.
  • Problem: runtime_schema() builds schema().to_vec(), deep-cloning every FieldDescriptor, plus plugin descriptors, and update_settings calls it twice (split_patch_by_layer and validate_patch_with). split_patch_by_layer then linearly scans descriptors per leaf. write_gate, one global mutex, is held across both spawn_blocking writes and emit_settings_changed.
  • Fix: Call runtime_schema() once per request and reuse it for split and validate. Use schema_ref() when no plugin sections are involved. Cache the merged plugin descriptors keyed on registry generation. Drop the gate before emit_settings_changed.
  • Verifier: runtime_schema is cloned twice per profile-targeted PATCH (split plus validate), true, and write_gate is held across emit_settings_changed. But the clone is a few hundred small structs, once per user toggle. Reusing one clone is trivial; gain is microseconds.
  • Measure: Criterion bench of runtime_schema() plus validate_patch_with; expect tens of microseconds per call.

#179 resolve_all is O(n^2) with per-field registry walks

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-system, category cpu
  • Where: src/session/config/settings_schema/resolved.rs:54-130, src/server/api/system.rs:1197-1205
  • Frequency: Per GET /api/settings/resolved (settings pages). Scales with descriptors squared.
  • Problem: resolve_all calls resolve_with per descriptor, which does schema.iter().any over all descriptors again, formats a key string, clones Values, and resolve_core calls plugin::registry().active() and serializes plugin defaults per field.
  • Fix: In resolve_all call resolve_core/resolve_plugin_own directly for each descriptor (the schema match is already known) and hoist the active-plugin setting_defaults lookup out of the per-field loop.
  • Verifier: resolve_all does schema.iter().any per descriptor (O(n^2)) and calls plugin registry active() per core field; true. But n is a few hundred, so about 10^5 cheap string compares, under a millisecond, inside spawn_blocking, only on settings page load.
  • Measure: Criterion bench of resolve_all() with default config and 0 or 5 active plugins.

#180 Plugin ui-state serializes the whole snapshot twice per poll just to compute an ETag

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area server-api-system, category cpu
  • Where: src/server/api/plugins.rs:355-405, src/plugin/ui_state.rs:571-604, web/src/hooks/usePluginUiState.ts:5-7
  • Frequency: Every 3s per open dashboard (500ms for 15s after an action), including when nothing changed. Snapshot holds up to 1024 entries per plugin with payloads up to 64 KB, plus 200 notifications.
  • Problem: Each poll clones every UI entry and notification in snapshot(), converts to serde_json::Value, then to_vec, then hashes the bytes. A 304 saves bandwidth only, not the clone or serialization.
  • Fix: Add a monotonic mutation counter to UiState and the registry generation, derive the ETag from them, and return 304 before calling snapshot(). Serialize UiSnapshot straight to bytes on a miss.
  • Verifier: Code matches: snapshot clone, to_value, to_vec, hash every poll, before the 304 check. But typical state is a few small entries on loopback, so microseconds. The 1024x64KB worst case is theoretical. A counter must also cover pages and notifications.
  • Measure: Time plugin_ui_state with a criterion bench on a realistic snapshot (50 entries, 2KB each) and on a 1024x64KB worst case.

#181 browse_filesystem stats .git for every directory before applying the limit

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area server-api-system, category disk-io
  • Where: src/server/api/system.rs:1936-2005
  • Frequency: Per directory-picker navigation or filter change. Scales with entries in the directory (home or ~/code can hold thousands).
  • Problem: For each entry it calls entry_path.is_dir() (a stat following symlinks) then entry_path.join(.git).exists() (a second stat), sorts, and only then truncates to limit (default 100). Up to 2N stats where 100 results suffice.
  • Fix: Use entry.file_type() for the dir test (stat only for symlinks). Sort and truncate first, then compute is_git_repo for the surviving entries only.
  • Verifier: Stats .git per matching dir before sort and truncate(limit). Plus entry_path.is_dir() stat. Runs inside spawn_blocking, only on user navigation. Deferring is_git_repo until after truncate is correct and trivial. The win only appears in dirs with thousands of subdirs.
  • Measure: Run the endpoint with strace/dtruncate or hyperfine against a dir with 5000 subdirectories, before and after.

#182 Plugin discovery has no cache, so each click spends GitHub search quota and up to 30 HEAD probes

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-system, category network
  • Where: src/plugin/discover.rs:73-88, src/plugin/discover.rs:114-150, src/plugin/discover.rs:378-430, src/server/api/plugins.rs:428-442
  • Frequency: Per Search GitHub click and per detail modal open. Unauthenticated search limit is about 10 requests per minute.
  • Problem: discover() always runs search_repositories(30) then HEAD-probes every unvetted repo, with no memoization even for an identical query. details() issues get_repo_file and then list_releases sequentially.
  • Fix: Add a small TTL map (60s) keyed by query in plugin::discover for discover() and details(). Run the two details() requests with tokio::join!.
  • Verifier: No cache in discover.rs (grep for cache/TTL empty) and details() awaits two requests sequentially. But calls are click-driven, probes already concurrent with a phase timeout, and the rate-limit concern is real only for rapid repeats. tokio::join! is a clean win; TTL cache is optional.
  • Measure: Log wall time of discover() and details() with tracing around the awaits; count GitHub requests per click.

#183 Dashboard presence heartbeat POSTs every 10s even when hidden or unfocused

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-system, category network
  • Where: web/src/hooks/useDashboardPresence.ts:5-40, src/server/api/system.rs:45-66, src/server/state.rs:495-515
  • Frequency: Every 10s per open tab for the page lifetime, including idle background tabs (browser-throttled but still firing).
  • Problem: update() runs on an interval and POSTs {active:false} each tick while the tab is hidden, though the server already removed the entry on blur or pagehide. Each POST goes through auth and takes the presence mutex plus a sha256 of the binding header.
  • Fix: In useDashboardPresence keep the last reported active value and skip the interval POST when active is false and unchanged. Keep the heartbeat only for active=true.
  • Verifier: Interval POSTs active:false while hidden, confirmed. Server cost is a tiny mutex sweep plus sha256, and browsers throttle background timers to about 1/min. Skip-if-unchanged is safe but tiny; keep a retry if the clear POST failed, since errors are swallowed.
  • Measure: Open a hidden tab for 5 minutes and count POST /api/presence in the browser network log or server access logs.

#184 Blocking filesystem and lock work in async handlers (themes, telemetry, plugin job prune, log-level persist)

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-api-system, category concurrency
  • Where: src/server/api/system.rs:1759-1766, src/server/api/system.rs:1262-1272, src/server/api/telemetry.rs:30-40, src/server/api/telemetry.rs:75-100, src/server/api/plugins.rs:973-985, src/server/api/log_level.rs:96-100
  • Frequency: Theme list and update per theme picker use; telemetry status and consent rare; plugin begin per install; log-level per change. All run on async worker threads.
  • Problem: list_themes and update_theme call available_themes() inline (read_dir, and discover_custom_themes runs twice). set_telemetry_consent, get_telemetry_status and reset_telemetry_id call update_config/update_app_state/Config::load (flock plus file writes) without spawn_blocking. PluginJobRegistry::prune removes files under a std Mutex. persist_runtime_filter writes inline.
  • Fix: Wrap each in tokio::task::spawn_blocking. Make discover_plugin_themes take the custom list instead of rediscovering it. Collect stale log paths in prune and delete them after dropping the lock.
  • Verifier: Inline blocking calls are real (available_themes read_dir, update_config flock, prune remove_file under std Mutex, persist_runtime_filter). All are rare, user-triggered, small fs ops on local disk. Worker-stall risk is negligible. Tidiness fix via spawn_blocking is cheap but not a perf win.
  • Measure: Run tokio-console or tracing on handler poll durations during theme picker use; flag polls longer than 10ms.

#185 Skills list reads every SKILL.md fully on each request

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area server-api-system, category disk-io
  • Where: src/session/skills_model.rs:283-330, src/server/api/skills.rs:60-90, web/src/hooks/useSkillIndex.ts:8-24
  • Frequency: Per page load via useSkillIndex (cached per page) and each Skills manager open. Scales with skill count across all roots.
  • Problem: collect_from_dir does symlink_metadata plus read_file_capped plus parse for every skill directory and marker_at per external entry, though only name and description from the frontmatter are returned.
  • Fix: In collect_from_dir read only the first ~4 KB or until the closing frontmatter delimiter. Optionally cache the result keyed on root directory mtimes.
  • Verifier: Claim is accurate: collect_from_dir reads whole SKILL.md (1 MiB cap) per skill, run in spawn_blocking. But the web index is fetched once per page via a module-level promise, so frequency is low. Typical skills are a few KB; the win is microseconds to a few ms.
  • Measure: Time skills_model::discover_all with tracing::Instant on a home with ~100 skills; compare against a 4 KB-capped read.

#186 get_setup rebuilds default Config table and re-runs agent detection on every settings change

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area server-api-system, category cpu
  • Where: src/server/api/setup.rs:140-165, src/server/api/setup.rs:208-235, web/src/hooks/useSetupStatus.ts:30-45
  • Frequency: On dashboard load and after every settings save (onSettingsChanged triggers refresh). Roughly 40 KB of TOML table conversion each time.
  • Problem: load_inputs converts the whole Config to a toml::Table and also parses an empty string into default Config and converts that to a table per call. It also runs detect_with_custom_agents and a full resolve_config for the profile.
  • Fix: Hold the default toml::Table in a OnceLock inside setup.rs. Skip refresh in useSetupStatus when setup_finished is already true and the banner is dismissed.
  • Verifier: Code matches: load_inputs reparses empty Config and runs Config::load plus resolve_config plus detect_with_custom_agents per call, on spawn_blocking. Refresh fires only on dashboard load and settings save, so rare. Agent probe appears memoized. OnceLock for defaults is safe but saves little.
  • Measure: Wrap load_inputs in Instant timing and log elapsed; save a setting in the dashboard and read the log.

4.server-streaming

#187 Raw ACP frames and per-connection folds are duplicated per subscriber

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area server-streaming, category cpu
  • Where: src/server/acp_ws.rs:230-256, src/acp/protocol.rs:60-69
  • Frequency: Per ACP event per open structured-view socket (web uses frames=1)
  • Problem: Each socket serializes the same AcpBroadcastFrame (serde_json::to_string, including strip_transcript_path), deep-clones the Event for reduced.apply_event, and folds its own TranscriptModel. N viewers of one session do N identical serializations and folds that the daemon's control cache already performs.
  • Fix: Have the publisher attach a lazily computed Arc wire JSON to AcpBroadcastFrame, using OnceLock so it is serialized once. Compute transcript deltas once in the shared fold proposed for the replay fix, and broadcast them pre-serialized. Sockets then forward bytes.
  • Verifier: Per-socket to_string, Event deep clone (acp_ws.rs:246) and TranscriptModel fold are real, but N viewers of one session is usually 1, so no N-fold duplication. Remaining waste is one extra fold and clone per event versus the daemon control cache; serialize-once via OnceLock only pays off with multiple viewers.
  • Measure: Time the rx.recv arm in acp_ws.rs with tracing spans during a large tool-output turn; compare against socket.send latency.

#188 Status poll publishes a full runtime projection every tick on top of publish_loop

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-streaming, category cpu
  • Where: src/server/status_poll.rs:428-441, src/server/status_poll.rs:612-615, src/server/runtime.rs:278-327, src/server/runtime.rs:787-801
  • Frequency: Every status tick: 500ms with runtime subscribers, 2s without; scales with session count
  • Problem: status_poll_loop always calls state.runtime.publish(). publish rebuilds project_sessions, compute_merged_ordering and full RuntimeContents, then PartialEq-compares the result with the previous snapshot before deduping. publish_loop does the same on its own 500ms/2s timer, so an idle daemon builds two full projections per period.
  • Fix: In status_poll_loop, call publish only when reload_state_instances_from_disk reported changes or mutation_epoch moved since read_epoch. Otherwise call state.runtime.request_publish(), or nothing, and let publish_loop coalesce.
  • Verifier: status_poll.rs:623 publishes every tick and publish_loop (runtime.rs:787) does too, so projection runs twice per period. project_sessions is not trivial: read_tui_fullscreen file read and per-structured-session SQLite lookups. But gating on changes is unsafe: worker states, approvals, plans change outside that list. Use request_publish instead, or drop publish_loop's timer. Tick's tmux spawn dominates.
  • Measure: Wrap runtime.publish in a tracing span with duration; count calls per minute on an idle daemon with 30 sessions, before and after.

#189 Status tick forks tmux twice and flocks the retirement journal every time

  • Impact low, effort M, verdict partly, evidence proven-by-code, area server-streaming, category subprocess
  • Where: src/server/status_poll.rs:463-482, src/tmux/mod.rs:652-659, src/tmux/mod.rs:1434-1443, src/tmux/tool_session.rs:122-124
  • Frequency: Every 500ms with subscribers, 2s without, forever
  • Problem: Each tick runs refresh_session_cache (show-options + list-sessions fork), batch_pane_metadata (list-panes -a fork, plus another on the tool server when unmarked tool panes exist) and LockedJournal::open (flock + read of the retirement journal), even when nothing changed. That is a constant fork and file-I/O floor that never stops.
  • Fix: Merge session_scan_command and the list-panes -a format into one tmux invocation with a separator line, then parse both. Cache LockedJournal targets keyed by the journal file's mtime/len and re-open only when it changes.
  • Verifier: Forks (show-options+list-sessions, list-panes -a) and journal flock are real per tick (status_poll.rs:512-514), but run in spawn_blocking off the runtime. 2s idle floor is cheap. Merging two tmux calls risks error and timeout semantics; journal mtime cache is the safer small win.
  • Measure: Idle daemon: sudo fs_usage -w -f exec $(pgrep -f 'aoe serve') or count tmux execs per minute via a PATH-shim wrapper logging argv.

#190 Grid live viewers each fork tmux for pane count and size-owner checks

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area server-streaming, category subprocess
  • Where: src/server/live_ws.rs:1185-1194, src/server/live_ws.rs:1290-1385, src/server/live_ws.rs:1966-1985
  • Frequency: Per grid viewer: window_pane_count every 1s; refresh_size_owner, or claim_size_owner plus size_owner, every 1.5s
  • Problem: window_pane_count forks display-message per viewer every second, although VtChannel::reconcile_grid already runs a display-message for the same pane once a second. A visible non-owner forks twice per 1.5s, once for a reclaim attempt and once to refresh the holder. With several tabs or devices on one session, the per-viewer forks add up while the pane is idle.
  • Fix: Add #{window_panes} to pane_size_cursor's format in VtChannel::reconcile_grid and expose a cached pane_count() on VtChannel, so viewers read it instead of calling window_pane_count. Merge the reclaim and holder check into one tmux call that returns the current holder.
  • Verifier: Per-viewer forks are real but already throttled to 1s (PANE_COUNT_PROBE_INTERVAL) and 1.5s heartbeats, each in spawn_blocking. Owner branch is else-if so non-owner does reclaim plus holder check. Cost only scales with multi-viewer on one session; sharing needs cross-viewer cache.
  • Measure: Open 4 grid tabs on one idle session; count tmux execs/min with a PATH-shim wrapper logging display-message and show-options invocations.

#191 Blocking SQLite queries on the async runtime inside the serial ACP listener

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-streaming, category concurrency
  • Where: src/server/acp_events.rs:177-182, src/server/acp_events.rs:372-376, src/acp/event_store/wakeups.rs:95-130, src/acp/event_store/turns.rs:195-215
  • Frequency: fired_wakeup_for_prompt on every UserPromptSent; first_turn_context on every Stopped of a default-named session
  • Problem: The listener calls fired_wakeup_for_prompt (2 queries) and first_turn_context (a streamed scan) synchronously on a tokio worker under the event store's connection Mutex. If a replay or hydrate holds that mutex, the worker thread and the single listener stall, which risks broadcast lag for all sessions.
  • Fix: Wrap both calls in tokio::task::spawn_blocking with an Arc of acp_event_store, as fold_control_state already does. Better, move the wake-fire lookup and smart-rename context read into the spawned runtime.work task so the listener loop never touches SQLite.
  • Verifier: Calls are synchronous on the listener task under the store conn Mutex (event_store/mod.rs:196). Queries are indexed single-row and cheap; first_turn_context stops at first Stopped, only default-named sessions. Stall only if a long replay holds the mutex. spawn_blocking is a trivial, safe fix.
  • Measure: Hold the store conn during a large hydrate and measure listener recv lag via tracing around fired_wakeup_for_prompt call duration.

#192 Runtime read WS rebuilds every profile from disk per CLI call, serialized by a global mutex

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area server-streaming, category disk-io
  • Where: src/server/runtime_ws.rs:146-161, src/server/runtime_ws.rs:395-640, src/server/runtime_ws.rs:648-670
  • Frequency: Every aoe list/status/group list/project list/session show routed to the daemon; scales with profiles and sessions
  • Problem: build_snapshot runs selectable_profiles(), load_profile_projects and load_profile_groups for every profile, projects::load_global and Config::load_or_warn, all under RUNTIME.flight, so concurrent reads serialize. canonical_metadata already holds profiles and global projects. Per-profile scoped filters rescan all sessions, which is O(profiles x sessions). Scripts or statuslines polling aoe status pay this every call.
  • Fix: Source projects, groups, global projects and default_profile from state.canonical_metadata, refreshed by the reload path, and keep disk reads only for alias/unaccepted profiles. Group sessions by profile once (HashMap<&str, Vec<&SessionRead>>) before the per-profile loop.
  • Verifier: build_snapshot does run in spawn_blocking under runtime.flight and re-reads profile disk state per call, but sessions come from memory cache. Per-profile scoped filter is O(P x S) with tiny P. Swapping to canonical_metadata risks staleness and health-reporting invariants; it is deliberate.
  • Measure: Time aoe status over 20 profiles and 500 sessions with hyperfine against the daemon, plus a tracing span on build_snapshot.

#193 Push consumer stats TUI activity files every 500ms even with nothing to send

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-streaming, category disk-io
  • Where: src/server/push.rs:559-563, src/server/push.rs:634-672, src/session/mod.rs:1221-1223
  • Frequency: Every 500ms for the daemon's lifetime when push is enabled
  • Problem: fire_due_pushes calls crate::session::is_tui_active (readdir + stat of activity files) on the async runtime before checking whether any dwell entry is armed or any subscription exists. The timer and directory scan run forever on an idle daemon.
  • Fix: In fire_due_pushes, return early when no DwellState has a *_since set or when push.store is empty, before is_tui_active. Better, sleep_until the earliest dwell deadline instead of a fixed 500ms interval, and run is_tui_active via spawn_blocking only when a push is due.
  • Verifier: Claim holds: fire_due_pushes (push.rs:693) calls is_tui_active every 500ms before checking dwell, only when push is enabled. It is a readdir+stat on the runtime thread; negligible cost. Early return when dwell is empty is trivial and safe, but benefit is tiny.
  • Measure: Run sudo fs_usage -w -f filesys $(pgrep -f 'aoe serve') idle with push enabled; count readdir calls on the tui activity dir.

#194 Live-view keystrokes fork one tmux send-keys per WS message on the fallback input path

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area server-streaming, category latency
  • Where: src/server/live_ws.rs:1745-1771
  • Frequency: Per Binary WS message (keystroke or paste chunk) when no tmux 3.8 input channel exists
  • Problem: Each keystroke is awaited serially through spawn_blocking and send_raw_bytes, one tmux fork each. Fast typing or held keys queue behind fork latency, which delays echo, and the recv loop cannot read control messages in the meantime.
  • Fix: In the recv loop, after a Binary frame, drain further ready Binary frames with ws_receiver.next().now_or_never(), concatenate the bytes, and do one pane_input_bytes plus one send_raw_bytes call.
  • Verifier: Claim holds: each Binary frame is awaited through spawn_blocking and send_raw_bytes, which also resolves the pane target before send-keys. Only the fallback path when no vt input channel exists. Human typing rate makes it small, and pasted data is already batched by raw_byte_batches. Coalescing helps held keys only.
  • Measure: Time send_raw_bytes under tracing while holding a key in the fallback path; compare echo latency with and without coalescing.

#195 Live frame publish copies the frame several times per publish

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-streaming, category memory
  • Where: src/server/live_ws.rs:1574-1626, src/server/live_ws.rs:2093-2111, src/daemon/live.rs:95-111
  • Frequency: Per published frame per viewer (up to ~60/s, window up to 4000 lines)
  • Problem: Each publish allocates last_sent as Vec of every line, clones the content into LiveServerMessage::Frame { content: String }, and keeps the full content again in last_published. For a 4000-line scrollback window that is three copies of a large frame per publish per viewer.
  • Fix: Keep only last_published content and derive prev lines with frame_lines(&prev) inside plan_patch. Change LiveServerMessage::Frame.content and Patch.lines to Cow<'a, str> or &'a str so frame_json and patch_json borrow.
  • Verifier: Copies are real: last_sent clones every line (line 1616), frame_json does content.into(), and last_published holds the content. Frames publish only on change, and JSON serialization plus deflate cost more than these copies. Fix is safe but last_sent must handle the transport-change reset.
  • Measure: Run the live capture with a 4000-line window under dhat or heaptrack and compare allocation bytes per publish.

#196 Every paired-shell live connect runs a full ensure, pane scrape and runtime publish

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area server-streaming, category latency
  • Where: src/server/live_ws.rs:897-928, src/server/pane.rs:631-683
  • Frequency: Every paired host/container live-ws connect or reconnect
  • Problem: respawn_paired_if_dead always takes the namespace and instance locks, opens NativeSessionStore, runs start_terminal_with_size_indexed_in, runs batch_pane_metadata (list-panes -a), and awaits state.runtime.publish, even when the shell is alive. Reconnect storms (mobile resume, several tabs) pay this serially per tab before the upgrade.
  • Fix: In respawn_paired_if_dead, first probe the indexed terminal with one has-session/pane_dead check via spawn_blocking, and return tmux_name directly when it is alive. Take the lifecycle path only when it is absent or dead.
  • Verifier: Code matches: locks, store open, ensure, runtime.publish on every connect. Cost is per connect, not per frame. The ensure also samples auxiliary ownership and publish validates Healthy and non-Superseded, so a bare alive probe could skip those checks. Effort is more than S.
  • Measure: Instrument respawn_paired_if_dead duration with tracing spans over 10 reconnects of a live shell and see how much the publish costs.

#197 Readiness probe forks a redundant has-session before list-panes

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area server-streaming, category subprocess
  • Where: src/server/pane.rs:916-947
  • Frequency: Per live-ws connect, up to 40 probes in 2s while a pane warms up
  • Problem: probe_tmux_readiness runs tmux has-session and then tmux list-panes -t name. list-panes fails on a missing session by itself, so has-session doubles the forks on every probe.
  • Fix: Drop the has-session call. Treat a failed list-panes as NotReady and parse stdout as before.
  • Verifier: probe_tmux_readiness forks has-session then list-panes, though list-panes -t fails on a missing session by itself. The happy path (first probe) forks twice instead of once. The code comment calls it cheap. The saving is a few ms per live connect.
  • Measure: Time 100 probe_tmux_readiness calls before and after, or strace -c -f for execve count per connect.

#198 ACP attention pushes build a new reqwest client and send sequentially

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area server-streaming, category network
  • Where: src/server/acp_ws.rs:741-779, src/server/push.rs:839-848, src/server/push.rs:991-997
  • Frequency: Per approval/question request and clear, wake-fire and sandbox-login push
  • Problem: send_acp_push, fire_wake_fired_push and fire_sandbox_login_push each call build_client(), which builds a fresh TLS config and connection pool, so no connection is reused. send_acp_push also awaits deliver() for each subscription in turn, outside the shared send_semaphore.
  • Fix: Store one reqwest::Client in PushState, built in PushState::init, and reuse it everywhere. In send_acp_push, spawn per-subscription deliveries gated by push.send_semaphore, as fire_due_pushes does.
  • Verifier: build_client is called per send in acp_ws.rs:763, push.rs:538, 874, 992 and 1387, so there is no connection reuse. send_acp_push also delivers sequentially without send_semaphore, unlike the wake push. Pushes are rare events and the subscription count is small, so the win is small.
  • Measure: Time a send_acp_push call with 5 subscriptions before and after sharing a client and parallelizing deliveries.

#199 Named tunnel startup sleeps 3s without checking anything

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area server-streaming, category startup
  • Where: src/server/tunnel.rs:157-187
  • Frequency: Once per aoe serve --remote with a named Cloudflare tunnel
  • Problem: spawn_named runs a fixed tokio::time::sleep(3s) after spawning cloudflared and never checks the child's state, so it adds 3s of startup latency and still misses an early exit.
  • Fix: Replace the sleep with tokio::time::timeout(3s, child.wait()). An exit inside the window returns an error, and a timeout means it is running. Better, read stderr for the 'Registered tunnel connection' line, as spawn_quick does for its URL.
  • Verifier: tunnel.rs:178 sleeps a fixed 3s and never checks the child, so an early exit goes unnoticed and the URL is printed anyway. stderr is Stdio::null, so the 'Registered' line fix needs piping stderr. timeout(3s, child.wait()) fixes the missed exit but not the 3s.
  • Measure: Time aoe serve --remote with a named tunnel to the URL print; test with a bad tunnel name to see the missing early-exit error.

4.server-state

#200 Global instances write lock held across disk rewrites of sessions.json during reload

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area server-state, category concurrency
  • Where: src/server/reload.rs:1321-1381, src/server/status_poll.rs:85-135
  • Frequency: Each status tick that produces passive transitions (tmux session status changes or unread marks) and each live-worker repair. Scales with tmux session activity.
  • Problem: reload_state_instances_from_disk takes publication.write and then instances.write. Only after that does it await persist_structured_row_repairs and flush_passive_transition_writes, which spawn_blocking a full read-modify-write of each affected profile's sessions.json. Every reader blocks for the whole disk write: API lists, MCP auth session_is_live, reconciler, fold lookups, prompt handlers.
  • Fix: Check mutation_epoch under a short instances.read. Run the passive/repair writes while holding only publication.write and the reload guard. Then take instances.write, re-check the epoch, and merge. A mismatch after the write is harmless because the next tick re-reads disk. If not, at least drop the lock before awaiting each spawn_blocking.
  • Verifier: reload.rs:1323-1381 holds instances.write across persist_structured_row_repairs and flush_passive_transition_writes, which spawn_blocking sessions.json rewrites. This runs only on ticks with passive transitions or repairs, and publication.write already blocks publish. The extra stall hits only direct instances readers (MCP, reconciler) for a small-file write, about milliseconds.
  • Measure: Time from instances.write acquisition to merge_loaded_rows in reload.rs during an active agent session; log write-lock hold duration histogram.

#201 merge_loaded_rows deep-clones every prior Instance on every reload tick

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-state, category memory
  • Where: src/server/reload.rs:1166-1186, src/server/reload.rs:1492-1505, src/server/reload.rs:1600-1613
  • Frequency: Every status tick (500ms/2s) and every disk-watch reload. Scales with session count times Instance size (queued prompts, worktree info, panes).
  • Problem: PriorById owns the drained rows, but the loop calls prior_by_id.get(&row.id).cloned() for each row because apply_acp_overlay_inplace later needs the same map. Each tick therefore allocates a full copy of every session row only to move it into merge_runtime_fields.
  • Fix: Before the loop, collect the overlay inputs (status, last_accessed_at, idle_entered_at) for structured rows into a small map. Give PriorById a take(id) that moves the row out. Apply the overlay from the small map. external_session_changes needs only title, group, archive, snooze and trash, so snapshot those too.
  • Verifier: The clone at reload.rs:1502 is real. PriorById has no remove, by documented invariant, because apply_acp_overlay_inplace and the second loop need prior status, lifecycle_generation and timestamps. A snapshot of small fields plus a take() is feasible. The cost is tens of Instance clones every 500ms, which is microseconds next to the disk and JSON reload work.
  • Measure: cargo bench or Instant timing around merge_loaded_rows with 200 synthetic Instances carrying queued prompts.

#202 Reconciler reads and parses every worker-registry JSON synchronously on the async runtime every 2s

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-state, category disk-io
  • Where: src/server/acp_reconciler/mod.rs:608-624, src/server/acp_reconciler/mod.rs:642-655, src/process/worker_registry.rs:423-440, src/process/worker_registry.rs:458-485, src/process/worker_registry.rs:598-608
  • Frequency: Every maintenance_loop tick (2s), always, even when idle. Scales with the live worker count.
  • Problem: sweep_orphan_workers calls worker_registry::list(), which does read_dir plus a read and serde parse of every record, on an async worker. It then discards records whose session is live or owned. readopt_orphan_runners calls load() and is_record_live() for each attempted-but-unowned id: a file read, a process birth-identity syscall, and a socket stat.
  • Fix: Add worker_registry::list_ids() that returns filename stems only. Filter out live and owned ids first, then load only the remaining orphans. Run both passes inside one spawn_blocking.
  • Verifier: Real: maintenance_loop ticks every 2s (status_poll.rs:350) and list() reads plus parses every workers/*.json on the runtime. But there is one tiny file per live worker, capped by max_concurrent_workers, so this is tens of sub-KB reads. readopt only probes attempted ids that are not owned, usually zero. Cost is microseconds. list_ids is cheap tidying, not a measurable win.
  • Measure: Wrap sweep_orphan_workers and readopt_orphan_runners in Instant timing and log at trace level with 20 live workers; expect under 1ms per tick.

#203 fold_control_state clones the full AcpState and hops to the blocking pool even on a cache hit

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area server-state, category cpu
  • Where: src/server/session_service.rs:1902-1940, src/acp/control_cache.rs:82-98, src/server/acp_reconciler/mod.rs:568-586, src/server/session_service.rs:2044-2047, src/server/api/sessions/list.rs:400
  • Frequency: Per reconciler tick (2s) for each session with queued prompts (twice when drained), per list request per queued session, per prompt dispatch.
  • Problem: Callers often need one bool (accepts_queue_drain, queue_hold). Every call still does a spawn_blocking round-trip and clones an AcpState that holds recent_diffs, todos, available_commands, config_options and subagents, which can be large for active sessions.
  • Fix: Add ControlCache::with_cached(id, |&AcpState| -> R) -> Option that runs the closure under the slot lock with no clone. Have fold_control_state-style helpers (accepts_queue_drain, queue_hold, dispatch decide) use it synchronously, and fall back to spawn_blocking hydrate only on a miss.
  • Verifier: Cache hit still clones AcpState and hops to the blocking pool (session_service.rs:1930, control_cache.rs:89). Callers are only sessions with queued prompts, at a 2s tick or per list request, so the load is small. A with_cached closure is feasible; the win is small.
  • Measure: Bench fold_control_state on a hit with a 20k-event AcpState, or count spawn_blocking per second under 50 queued sessions.

#204 Up to three Argon2 operations at startup, plus Argon2 login verify on async workers

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-state, category startup
  • Where: src/server/login.rs:97-150, src/server/login.rs:660-676, src/server/login.rs:897, src/server/login.rs:1018-1021, src/server/passkeys.rs:229-243, src/server/startup.rs:607-626
  • Frequency: Once per start in passphrase mode, plus per login and elevate attempt.
  • Problem: LoginManager::with_persistence hashes the passphrase with a new salt and verifies it against the sessions file. PasskeyManager::with_persistence verifies it again (and may hash again). That is 2-3 Argon2 runs of tens of ms each in release, much longer in debug, executed inline in async start_server. verify_passphrase also runs Argon2 directly on an async worker per login request.
  • Fix: Verify once against the stored hash and reuse that hash when it matches instead of re-salting. Share the result between LoginManager and PasskeyManager. Wrap login and elevate verify_passphrase in spawn_blocking.
  • Verifier: Two or three Argon2 runs at startup (login.rs:110 hash, :150 verify, passkeys.rs:236) happen only in passphrase mode, once per start, before binding. Login and elevate verify_passphrase (login.rs:897, :1020) run inline on a worker; rate limiting bounds them. spawn_blocking there is a cheap, valid hardening.
  • Measure: Time hash_passphrase and argon2_verify in a release build, then run concurrent login POSTs and watch request latency on other routes.

#205 Each queued-prompt mutation and prompt touch rewrites the profile's whole sessions.json

  • Impact low, effort L, verdict partly, evidence proven-by-code, area server-state, category disk-io
  • Where: src/server/session_service.rs:1525-1600, src/server/session_service.rs:960-985, src/server/session_service.rs:1610-1630
  • Frequency: Per enqueue, edit, remove, drain and retire, and per prompt touch. Scales with sessions in the profile plus total queued text.
  • Problem: mutate_instance_persisted_with and the prompt touch do Storage::update, which reads, deserializes and atomically rewrites every session row to change one session's queue or recency. A code comment acknowledges this and caps queue depth and text size to bound it. The cost is still O(all sessions) per prompt, and the global storage flock serializes these writes against the status-tick passive writer.
  • Fix: Store queued_prompts and queued_prompt_next_seq in the event store's SQLite (it already holds pending attachments keyed by prompt id) as per-row inserts and deletes. Keep sessions.json for lifecycle fields only. last_accessed_at can be coalesced into the next passive status write.
  • Verifier: Each queue mutation does a full Storage::update, but it already runs in spawn_blocking (session_service.rs:1563) and the code caps queue depth and text to bound it (check_queue_room). It fires per user gesture, not per tick. Moving the queue to SQLite is a large change for little gain.
  • Measure: Time Storage::update with 500 sessions and a full queue, and count enqueue writes per minute in a busy session.

#206 Auth middleware takes global write locks on every authenticated request

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-state, category concurrency
  • Where: src/server/rate_limit.rs:72-82, src/server/rate_limit.rs:188-191, src/server/auth.rs:732-735, src/server/auth.rs:799-802, src/server/login.rs:215-262
  • Frequency: Every HTTP request and WS upgrade through the token or session path.
  • Problem: record_success takes failures.write() on every successful request even when the IP has no entry. check_locked_any linearly scans the whole failures map, up to 10,000 entries under attack. In passphrase mode, validate_session takes sessions.write() per request just to slide expires_at. These are short but serialize all requests.
  • Fix: In record_success, check contains_key under read() first and take write() only when an entry exists. Key failures as HashMap<IpAddr, [FailureRecord; 2]> so check_locked_any is O(1). In validate_session, take a read lock and slide expires_at only when it moved more than about 60s, or store it in an AtomicU64.
  • Verifier: Locks are real (record_success write lock per request, validate_session write lock per request) but held for nanoseconds; no await inside. Scan in check_locked_any is only large under attack, bounded at 10k. Read-first in record_success is a trivial valid win; the rest is overengineering.
  • Measure: wrk against an authenticated /api endpoint with 64 connections; compare req/s with and without the read-first change, check tokio-console lock wait.

#207 MCP read_output and wait_for do synchronous SQLite replays and repeated re-renders on the async runtime

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-state, category latency
  • Where: src/server/mcp/control.rs:355-397, src/server/mcp/control.rs:698-758, src/server/mcp/wait.rs:195
  • Frequency: Per MCP read_output call, and per wait_for with after_seq. Scales with page size (up to 2000 events).
  • Problem: replay_page loads and deserializes up to 2000 events on an async worker while holding the event store connection. When the page exceeds TEXT_PAGE_BYTES, text_page bisects by rendering the prefix about 11 times, each a full render_transcript_delta.
  • Fix: Run replay plus render in spawn_blocking. Replace the bisection with one pass that renders event by event, tracks cumulative length, and stops at the first event that would exceed TEXT_PAGE_BYTES.
  • Verifier: Sync SQLite replay_page runs on the async worker in read_output and wait_for, and text_page bisects with ~11 full renders only when the page exceeds 48 KB. Real but an infrequent, agent-driven MCP call; a single-pass cumulative render is feasible, spawn_blocking likely ok.
  • Measure: Time read_output on a session with 2000 large events using tracing spans around replay_page and text_page.

#208 persist_locks map grows forever

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area server-state, category memory
  • Where: src/server/session_service.rs:297, src/server/session_service.rs:2160-2172
  • Frequency: One entry per session id that ever had a queue or dormancy mutation, kept for the daemon lifetime.
  • Problem: persist_lock auto-creates per-id mutexes and never prunes them, unlike instance_lock_in and prompt_gate, which run retain(strong_count > 1) on a miss. Deleted sessions leak an entry each.
  • Fix: Use the same retain(|_, l| Arc::strong_count(l) > 1) on the write-miss path in persist_lock, or reuse state::instance_lock_in for this map.
  • Verifier: persist_lock never prunes, unlike instance_lock_in which retains strong_count>1 on write miss. Each entry is a String plus an Arc Mutex, roughly 100 bytes. Negligible leak, but reusing instance_lock_in is a one-line fix.
  • Measure: Log persist_locks.len() after creating and deleting 10k sessions; expect about 1 MB at most.

#209 Idle session reap spawns tmux and clones all instances even when no profile enables auto-stop

  • Impact low, effort S, verdict partly, evidence proven-by-code, area server-state, category subprocess
  • Where: src/server/idle_reap.rs:17-56
  • Frequency: Every 60s from maintenance_loop, for the daemon lifetime.
  • Problem: reap_idle_sessions first forks tmux for attached_session_names and clones the whole instances Vec. Only then does it resolve per-profile auto_stop_idle_secs, which defaults to 0 (disabled), so the usual result is no candidates.
  • Fix: Collect the distinct profiles under a read lock and resolve the thresholds first. Return early if all are 0. Only then call tmux and clone the rows that are candidates.
  • Verifier: Order is as claimed: tmux attached_session_names and a full instances clone run before thresholds, once per 60s. Already in spawn_blocking and throttled. Reordering saves one tmux fork and a Vec clone per minute; trivial win, though thresholds need the clone or a read-lock pass.
  • Measure: Count tmux subprocess spawns per minute on an idle daemon with auto_stop_idle_secs=0 via a spawn counter or dtruss.

4.acp-client

#210 Every session/update is fully re-serialized to a Value in AoeIngress::ingest just to read _meta.aoe

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area acp-client, category cpu
  • Where: src/acp/acp_client/aoe_ingress.rs:79-113, src/acp/aoe_meta/mod.rs:233-247, src/acp/acp_client/session_identity.rs:172-175
  • Frequency: Per inbound session/update frame (every token chunk, every tool update), per session
  • Problem: ingest() calls serde_json::to_value(&notification.update), which builds a full Value tree of the update, including large tool content, diffs and raw_input, only to read /_meta/aoe. Cost scales with payload size and token rate across all sessions. is_adapter_frame repeats the same thing for discarded frames.
  • Fix: Add fn update_meta(&SessionUpdate) -> Option<&Meta> that matches the known variants' meta field. Then is_anchored and Envelope::from_meta read it by reference. Fall back to to_value only for the non-exhaustive unknown variant. Use it in both AoeIngress::ingest and session_identity::is_adapter_frame.
  • Verifier: aoe_ingress.rs:84 and session_identity.rs:173 both call to_value(&notification.update) on every frame just to read _meta.aoe. On large tool updates this is a full deep copy. Text chunks are cheap. The fix is feasible because the known SessionUpdate variants carry a meta field.
  • Measure: Run a criterion bench of to_value on a 1MB ToolCallUpdate, or profile with samply during a large file-write turn and look at the AoeIngress::ingest share.

#211 Daemon relay decodes, re-encodes and re-parses each runner notification before the SDK sees it

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area acp-client, category cpu
  • Where: src/acp/control_protocol.rs:250, src/acp/acp_client/control.rs:569-589, src/acp/acp_client/control.rs:111-123, src/acp/acp_client/session_identity.rs:94-116, src/acp/acp_client/session_identity.rs:124-146
  • Frequency: Per runner Notify frame (the production path, socket_path is always set in supervisor/launch.rs:608), per token chunk, per session
  • Problem: read_frame_with_size parses into ControlBody with a params Value. The reader adds a field, wraps it with json!, serializes it with to_vec and writes it to the duplex. The SDK parses the line again, parse_message clones the whole params Value (params.clone()), and decode_update runs from_value. That is 2 full parses, 1 serialize, 1 deep clone and 1 typed conversion per frame.
  • Fix: Decode Notify params on the daemon side as Box (a daemon-only struct mirroring ControlBody::Notify). Build the line by splicing text: {"jsonrpc":"2.0","method":M,"params":{"__aoe_control_frame_bytes":N, plus raw[1..]. In SessionIngressNotification::parse_message, deserialize SessionNotification straight from &Value (SessionNotification::deserialize(params)) and read the byte count with params.get(), so the clone goes away.
  • Verifier: Confirmed: read_frame_with_size parses into a Value, the reader rebuilds it with json!, to_vec re-serializes it, parse_message clones params (session_identity.rs:115), and decode_update runs from_value. Dropping the clone is S. RawValue splicing is harder because params can be an Array (control.rs:578). Per-frame payloads are mostly small, so the real CPU share is unproven.
  • Measure: Profile the daemon with samply during multi-session streaming and sum the serde_json time under the control.rs reader and parse_message.

#212 Full SessionUpdate deep-cloned per notification for the tool-context cache, and raw_input cloned three times per ToolCall

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-client, category memory
  • Where: src/acp/acp_client/connection/notifications.rs:462, src/acp/acp_client/connection/notifications.rs:565-569, src/acp/acp_client/connection/subagents.rs:429, src/acp/acp_client/tool_context.rs:191-207, src/acp/acp_client/update_events.rs:359
  • Frequency: Per root or child session/update, including every text chunk; heavy on tool calls whose raw_input carries file contents
  • Problem: notification.update.clone() copies every update, including multi-MB tool content and diffs, only so update_tool_context_cache can read raw_input on ToolCall and ToolCallUpdate. map_update_to_events clones raw_input again into raw_args, and raw_input_for_tool_event clones it a third time into the cache. Text chunks pay the clone for nothing.
  • Fix: Before map_update_to_events, take Option<(String id, Value raw_input)> from ToolCall or ToolCallUpdate only, moving it out where possible, and pass that to update_tool_context_cache instead of a &SessionUpdate. In map_update_to_events ToolCall, use tc.raw_input.as_ref() for extract_plan_from_switch_mode and wake_tool_event instead of cloning raw_args. Apply the same change to subagents.rs source.
  • Verifier: notifications.rs:462 clones the full update for every frame, subagents.rs:429 clones source, raw_args clones raw_input (update_events.rs:359), and tool_context.rs:199/204 clones it again. Text-chunk clones cost little. The waste matters only for tool updates with large raw_input or content. The Event still needs one owned raw_args.
  • Measure: Run a dhat or heaptrack allocation profile of the daemon during a turn that writes a 1MB file and compare bytes allocated in handle_notification.

#213 Tool raw_input serialized to a string up to three times per update to compute the preview and the prompt cap

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-client, category cpu
  • Where: src/acp/acp_client/tool_output.rs:32-46, src/acp/acp_client/tool_output.rs:53-63, src/acp/acp_client/update_events.rs:452-463, src/acp/acp_client/update_events.rs:395-401, src/acp/acp_client/tool_context.rs:136-143
  • Frequency: Per ToolCall and per ToolCallUpdate that carries raw_input, per session
  • Problem: preview_args serializes the whole raw_input, even a 1 MB Write payload, then walks chars up to 16 KiB. full_prompt serializes it again only to compare its length with 16 KiB. update_tool_context_cache clones the cached raw_input and runs full_prompt on it a third time to dedupe the prompt.
  • Fix: Serialize once into a capped writer (like session_identity's PendingByteCount) that stops after 16 KiB plus 1 byte. Return both the preview and an exceeded flag, and let full_prompt take that flag. In update_tool_context_cache, store the computed full_prompt next to the raw_input in ToolCallContextCache, so the dedupe compares strings without cloning or reserializing.
  • Verifier: Overstated. full_prompt returns early unless raw_input has a string prompt key (Task/Agent calls only), and the cache dedupe runs only when prompt.is_some(). Usual cost is one full to_string in preview_args plus 2-3 Value clones (raw_args, raw_input_for_tool_event, cache.get). A capped writer still saves serializing big Write payloads. Win is a few ms per large tool call.
  • Measure: Criterion bench of preview_args and full_prompt on a 1 MB Write raw_input; count ToolCallUpdate frames carrying raw_input in a real claude-agent-acp session log.

#214 Between-prompt idle tick wakes every idle session once per second forever

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-client, category cpu
  • Where: src/acp/acp_client/connection/command_loop.rs:148-149, src/acp/acp_client/connection/command_loop.rs:190-195, src/acp/acp_client/connection/command_loop.rs:333-342, src/acp/acp_client/between_prompt.rs:17, src/acp/acp_client/between_prompt.rs:222-250, src/acp/acp_client/connection/subagents.rs:79-122
  • Frequency: 1 Hz per established session while no prompt runs, which is the normal state; scales with session count
  • Problem: between_prompt_idle_tick runs every second even when the tracker is inactive and no subagent is active. It locks the subagent maps (expire_silent_subagents walks all records), takes bg_agents and tracker locks, and checks leases, then returns None. N idle sessions give N wakeups per second for nothing.
  • Fix: Short-circuit in between_prompt_idle_tick: return when !tracker.state.active && !shared.has_active_subagent(). Better, gate the idle_tick select arm with if shared.between_prompt.is_active() || shared.has_active_subagent(), and add a Notify that BetweenPromptTracker::observe and publish_subagent fire on arming, so the loop re-polls when it changes.
  • Verifier: The 1 Hz tick is real per connection. But each tick is a few uncontended mutex locks over small maps plus now_ms, microseconds. Skipping the tick when idle is trivial, but the gain is a negligible CPU wakeup. A Notify gate adds risk for little benefit.
  • Measure: Run 50 idle sessions; compare wakeups per second via sudo powermetrics or perf stat -e context-switches on the daemon.

#215 Agent version and Node probes run synchronously on the async runtime for every session spawn, sometimes twice

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-client, category subprocess
  • Where: src/acp/acp_client/resolve_command.rs:41-56, src/acp/acp_client/resolve_command.rs:69-90, src/acp/acp_client/resolve_command.rs:136-151, src/acp/acp_client/resolve_command.rs:171-210, src/acp/acp_client/runner.rs:250-260, src/acp/acp_client/spawn.rs:489, src/acp/adapters.rs:138-148, src/acp/adapters.rs:166-183, src/acp/node.rs:58-89
  • Frequency: Per agent spawn or respawn (daemon restore starts many at once); each probe is a Node process start of about 50-300 ms
  • Problem: resolve_agent_command is sync and is called from async spawn_runner_detached and spawn_subprocess. When both a PATH copy and a bundle exist, it runs <adapter> --version with std::thread::sleep polling for up to 2 s. aoe-agent runs node --version twice (runtime_too_old_for, then bundled_resolution). installed_copy_is_stale SHA-256s every embedded source on each spawn. All of this blocks a tokio worker.
  • Fix: Call resolve_agent_command through tokio::task::spawn_blocking in spawn_runner_detached and in the caller of spawn_subprocess. Resolve Node once in resolve_agent_command and pass the ResolvedNode to both runtime_too_old_for and bundled_resolution. Memoize install_digest per BundledAdapter in a static OnceLock, since its inputs are compile-time constants. This keeps the 'uncached so nvm use applies' behavior.
  • Verifier: Confirmed: sync resolve_agent_command runs inside async spawn_runner_detached (runner.rs:250) and before spawn_subprocess (mod.rs:608), with no spawn_blocking. The adapter --version probe runs only when a PATH copy and a bundle both exist. Node is probed twice only on the bundled path. install_digest hashes small embedded sources in under 1 ms, so a OnceLock barely helps. The spawn_blocking part is the real fix.
  • Measure: Wrap resolve_agent_command in a tracing span and log elapsed ms during a daemon restore with 10+ structured sessions.

#216 Serve startup probes adapter versions serially while holding the instances read lock

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-client, category startup
  • Where: src/server/startup.rs:822-826, src/acp/version_probe.rs:221-246, src/acp/version_probe.rs:103-160
  • Frequency: Once per aoe serve start; one Node process launch per gated adapter, up to 2 s timeout each
  • Problem: warn_for_structured_sessions awaits probe_binary_version for each gate in sequence, about 200-500 ms per Node adapter start, before the daemon continues startup. instances.read() stays held for the whole time. Daemon readiness is delayed by the sum of the probes, and with timeouts by several seconds. The probes only produce warnings.
  • Fix: Compute gates_needed_by_instances under the lock, drop the guard, then run the probes concurrently with futures::future::join_all. For the daemon case (print_to_stderr == false), tokio::spawn the whole warning task so startup does not wait. Keep the stderr path awaited for foreground serve if the message must print before the banner.
  • Verifier: Serial awaits under instances.read() at startup.rs:822-826 are real. But version_gate_for allows at most 2 gates (claude-agent-acp, opencode), so join_all saves one probe at most. Spawning the daemon-path task off startup saves about one Node launch (~200-400 ms) of readiness. Writers contending with the read lock this early are unlikely.
  • Measure: Time warn_for_structured_sessions with Instant around startup.rs:825 on a daemon start where both adapters are gated.

#217 Tool completion output blocks cloned and then discarded when no media is present

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area acp-client, category memory
  • Where: src/acp/acp_client/tool_output.rs:104-182, src/acp/acp_client/update_events.rs:416-421, src/acp/acp_client/update_events.rs:440-449, src/acp/acp_client/lifecycle.rs:233-256
  • Frequency: Per ToolCallUpdate with status Completed or Failed, per session; scales with tool output size
  • Problem: extract_tool_output_blocks clones every text block into ToolOutputBlock::Text and returns an empty Vec when has_media is false, which is the common case for text-only output. A completion therefore copies its output twice (content_text plus the throwaway copy). detect_off_protocol_work_completed also scans all output lines twice (lifecycle classification and mapping).
  • Fix: In extract_tool_output_blocks, first test blocks.iter().any(is_media_or_terminal) and return Vec::new() before cloning anything. Compute detect_off_protocol_work_completed once in handle_adapter_notification and pass the result to both classify_lifecycle_signal and map_update_to_events.
  • Verifier: extract_tool_output_blocks clones every text block, then drops them when has_media is false. A pre-check for media is trivial and safe. Cost is one extra memcpy per completed tool, small next to content_text. The double marker scan stops at the first match and is negligible.
  • Measure: Criterion bench of extract_tool_output_blocks with a 1 MB text block; or count allocations with dhat.

#218 Runner control frames read without buffering, two syscalls per frame

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area acp-client, category cpu
  • Where: src/acp/control_protocol.rs:236-251, src/acp/acp_client/control.rs:393-399, src/acp/acp_client/control.rs:448-450
  • Frequency: Per runner-to-daemon control frame (every token chunk), per session
  • Problem: The reader loop passes the raw OwnedReadHalf to read_frame_with_size, which does read_exact for the 4-byte length and then read_exact for the body. Each small frame costs at least two recv syscalls and a zero-filled Vec allocation. A burst of chunks cannot be batched into one read.
  • Fix: Wrap read_half in tokio::io::BufReader::with_capacity(64 * 1024, read_half) before the reader loop in connect_runner_control_v3. read_frame_with_size is already generic over AsyncRead, so nothing else changes.
  • Verifier: Claim holds: reader loop (control.rs:454) passes raw OwnedReadHalf, so 2 recv per frame plus a zeroed Vec. read_half is not reused after, so BufReader is safe. But frames are small and each goes on to JSON parse and a duplex write, so the syscall share is minor.
  • Measure: strace -c -f -e recvfrom on the daemon during a streaming turn, or a criterion bench of read_frame_with_size on Cursor versus a socketpair.

#219 WebSocket client parses each frame twice, once to probe kind and once fully

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-client, category cpu
  • Where: src/acp/client/ws.rs:309-383
  • Frequency: Per WS text frame on the TUI structured view and aoe acp tail; reduced_state frames carry the full AcpState after every event
  • Problem: parse_text deserializes the whole text into KindProbe, which lexes and skips every field, and then deserializes the same text again into the target type. reduced_state arrives after every event and holds the whole AcpState, so the lexing cost doubles for the largest and most frequent frame.
  • Fix: Parse once into HashMap<&str, &RawValue> (borrowed) or a struct with kind: Option<&RawValue> plus state, rows, delta, seq, unchanged as Option<&RawValue>. Then deserialize only the selected field from its raw slice. For event frames (no kind), keep the direct AcpBroadcastFrame parse.
  • Verifier: Double parse is real (ws.rs:309-383). KindProbe skips fields as serde_json::Value, not a full lex-skip, and builds a Value for kind only. Event frames (no kind) also pay the probe. Cost is microseconds per frame. Fix works, but needs RawValue enabled.
  • Measure: criterion bench of parse_text on a realistic 50 KB reduced_state frame, current versus single-pass; check serde_json raw_value feature.

#220 Config files read from disk on the async runtime at the start of every prompt

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-client, category disk-io
  • Where: src/acp/acp_client/connection/prompt.rs:192, src/acp/acp_client/watchdog.rs:234-250
  • Frequency: Per prompt, per session
  • Problem: run_prompt calls silent_orphan_grace, which calls resolve_config_or_warn(profile) or load_config(), a synchronous file read plus TOML parse on a tokio worker before the prompt is sent. It adds prompt-start latency and blocks a worker. The value only changes when config changes.
  • Fix: Resolve base_grace once in establish (store it on Session next to source_profile), or take it from a config cache the daemon already invalidates on config writes. If live reload per prompt is required, wrap the call in spawn_blocking.
  • Verifier: Sole caller is prompt.rs:192, per prompt. It does a sync file read plus TOML parse on a tokio worker, but the cost is sub-millisecond against a multi-second LLM turn. Caching on Session would lose live config reload; spawn_blocking is the safer fix.
  • Measure: Time silent_orphan_grace with Instant in prompt.rs under a 10 KB config; expect well under 1 ms.

#221 Node tarball xz-decoded and extracted synchronously on the async runtime

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-client, category latency
  • Where: src/acp/node.rs:263-313
  • Frequency: Once per machine (first structured session with no usable Node); 20-30 MB tarball
  • Problem: node::download is async but runs XzDecoder plus tar::Archive::unpack, create_dir_all, remove_dir_all and rename inline. It holds a tokio worker for seconds of CPU-bound decompression and disk I/O and stalls other tasks on that worker, such as WS streaming for running sessions.
  • Fix: Move the SHA check, decompression, unpack and rename into tokio::task::spawn_blocking inside node::download, then call verify_path in the same blocking closure.
  • Verifier: Sync xz decode and unpack run inline in async download (node.rs:296-311), yet it is a once-per-machine path. Callers are plugin/mod.rs:122 and cli/acp.rs:555, and the CLI case has no other tasks to starve. Daemon-side plugin install is the only real concern. spawn_blocking is a trivial fix.
  • Measure: Run a tokio-console or a 50 ms ticker task during node::download on a fresh app dir and log the maximum tick lag.

#222 Control pump clones request params and response results out of the parsed Value

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-client, category memory
  • Where: src/acp/acp_client/control.rs:682-728
  • Frequency: Per daemon-to-runner request and per reverse-call reply (fs read responses carry whole files)
  • Problem: The pump parses each crate output line to a Value, then .get("params").cloned() or .get("result").cloned() deep-copies the payload into ControlBody before encoding. For read_text_file replies this copies whole file contents a second time.
  • Fix: Parse into serde_json::Value, then take ownership through value.as_object_mut().and_then(|o| o.remove("result")) (and likewise for params and error) instead of get().cloned().
  • Verifier: get().cloned() on params/result/error deep-copies (control.rs:690-722), including whole files for read_text_file replies. Real but per request, not per token, and the frame is then re-serialized anyway. Fix by making value mutable and using remove() is safe; win is one copy of large payloads.
  • Measure: Bench the pump with a 5 MB read_text_file result line; compare peak RSS and time with and without the clone.

4.acp-supervisor

#223 Redundant idx__events_session_seq duplicates the primary key index

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area acp-supervisor, category disk-io
  • Where: src/events/mod.rs:98-110
  • Frequency: Every event insert and every delete; scales with event volume
  • Problem: acp_events is a rowid table with PRIMARY KEY (session_id, seq), so SQLite already keeps sqlite_autoindex on exactly (session_id, seq). idx_acp_events_session_seq on the same columns doubles that b-tree: an extra page write per insert, extra WAL frames, and duplicate disk space for the whole log.
  • Fix: Drop the CREATE INDEX idx_{events}_session_seq statement from events::open and add a migration in src/migrations/ that runs DROP INDEX IF EXISTS idx_acp_events_session_seq. Queries keep using the PK autoindex.
  • Verifier: acp_events is a rowid table with PRIMARY KEY (session_id, seq) at events/mod.rs:107, and idx_{events}_session_seq at line 109 indexes the same columns. Dropping it saves one of five b-tree writes per insert and roughly 45 bytes per row. events::open is shared by every topic prefix, so the migration must drop the index for each prefix.
  • Measure: sqlite3 acp_events.db "SELECT name, SUM(pgsize) FROM dbstat GROUP BY name" to compare the duplicate index size with sqlite_autoindex_acp_events_1.

#224 Hot-path SQL is re-formatted and re-prepared on every call

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-supervisor, category cpu
  • Where: src/events/mod.rs:219-241, src/acp/event_store/rate_limit.rs:363-394, src/acp/event_store/turns.rs:248-266, src/acp/event_store/turns.rs:510-546
  • Frequency: insert_event once per event on the writer; turn probes per reconciler/list call per session
  • Problem: insert_event builds the INSERT string with format! and calls conn.execute, which parses and plans the statement every time. Most turns.rs probes (unresolved_*_nonces, latest_prompt_state, has_open_agent_turn, has_unhandled_finish) do the same with prepare/query_row. Statement compilation on the per-event path is pure overhead.
  • Fix: Precompute the INSERT SQL once in events::Schema (e.g. an insert_event_sql field) and use conn.prepare_cached(...).execute(...) in insert_event. Switch the query_row/prepare calls in turns.rs, wakeups.rs and rate_limit.rs to prepare_cached, as workflow_agents already does.
  • Verifier: insert_event and rate_limit use format!+execute, uncached; real but SQLite parse of a tiny INSERT is microseconds, dwarfed by fsync/commit. Turns.rs probes already use prepare_cached (lines 101,322-352); finding overstates the scope. Only insert/budget upserts remain.
  • Measure: criterion bench of insert_event in a batch of 10k events, execute vs prepare_cached; or perf/flamegraph the persister thread.

#225 Read-only probes run on the writer connection and contend with event persistence

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area acp-supervisor, category concurrency
  • Where: src/acp/event_store/turns.rs:127-170, src/acp/event_store/turns.rs:246-712, src/acp/event_store/wakeups.rs:12-90, src/acp/event_store/mod.rs:188-221, src/server/api/sessions/list.rs:55-110
  • Frequency: project_sessions per sessions-list poll x structured sessions (latest_plan, latest_pending_wakeup, 3-4 monitor queries, pending_approval_requests); reconciler probes every 30-60 s per candidate
  • Problem: latest_plan, latest_pending_wakeup, latest_active_monitor, pending_approval_requests, all unresolved_* and turn probes call self.conn(), the writer Mutex. Each list poll takes the writer lock about 6 times per session while the writer thread needs it per event, so streaming writes and dashboard polls serialize. A pooled reader (reader()) already exists.
  • Fix: Change these methods in event_store/turns.rs, wakeups.rs and latest_plan/latest_prompt_capabilities to use self.reader(). WAL readers see every committed write, and ChannelSink::flushed_store already flushes before read-after-write probes.
  • Verifier: Confirmed: latest_plan, latest_pending_wakeup, latest_active_monitor and the turn probes take self.conn(). Only replay, search and seq bounds use reader(). But project_sessions runs per runtime.publish (event-driven, not a fixed poll), and each probe is an indexed lookup well under 1 ms. The bigger issue is a sync mutex wait on a tokio worker. reader() is a safe swap after flushed_store.
  • Measure: Wrap project_sessions and EventStore::record lock acquisition in tracing spans and log p99 lock-wait time while 5 sessions stream with the dashboard open.

#226 BackgroundAgentProgress persists the full tools snapshot every 1.5 s and old snapshots are kept forever

  • Impact low, effort M, verdict partly, evidence proven-by-code, area acp-supervisor, category disk-io
  • Where: src/acp/background_agent.rs:16-17, src/acp/background_agent.rs:380-397, src/acp/background_agent.rs:656-666, src/acp/state.rs:1488-1510
  • Frequency: Every PROGRESS_THROTTLE (1.5 s) while each background sub-agent's transcript grows; scales with agents x tools per agent (up to 250)
  • Problem: Each progress event clones and serializes the whole tools Vec (up to 250 entries with ids, titles, timestamps) plus last_text, persists it, broadcasts it, and every WS client re-serializes it. Storage is quadratic in tool count per agent, and only the latest snapshot is ever used by the fold.
  • Fix: In the writer (Persister::publish_tagged or EventStore::record), delete earlier BackgroundAgentProgress rows for the same agent_id when a new one or BackgroundAgentCompleted lands, or emit only tools appended/changed since the last progress and have AcpState::apply_event merge by tool id.
  • Verifier: Progress is sent only on growth plus 1.5 s throttle, tools capped at 250 (MAX_TOOLS). Default acp.replay_events=0 means unlimited, and Progress is not swept by prune_completed_background_work, so rows persist. Fold keeps only latest (state.rs:1376). Real but bounded per agent; deltas would break the replace semantics, so prefer deleting superseded rows in the 64-seq sweep.
  • Measure: sqlite3 acp.db "SELECT COUNT(*), SUM(LENGTH(event_json)) FROM acp_events WHERE discriminant='BackgroundAgentProgress'" on a real long-lived DB

#227 Sub-agent tailer splits lines with drain(..=nl) per line, quadratic in chunk size

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-supervisor, category cpu
  • Where: src/acp/background_agent.rs:441-462
  • Frequency: Each 500 ms tick per tailed sub-agent; worst on a Resumed tailer that reads the whole transcript from offset 0 after daemon restart
  • Problem: read_new_lines pushes the whole new chunk into line_buf, then for each newline calls line_buf.find and drain(..=nl).collect::(), which memmoves the remaining buffer and allocates a String per line. A multi-MB transcript read in one chunk costs O(lines x bytes) memmove.
  • Fix: Iterate with a cursor: scan line_buf by byte offset, fold each &line_buf[start..nl] slice in place, then call line_buf.drain(..last_nl+1) once per chunk. Also read with a bounded buffer like task_transcript::scan instead of read_to_end.
  • Verifier: Per-line drain memmoves the remaining buffer, so it is quadratic only for a large first read. offset starts at 0 for every tailer, Live and Resumed, but steady 500 ms chunks are small. Cost matters only for multi-MB transcripts read at once on a tokio worker. The cursor fix is trivial and safe.
  • Measure: Unit bench read_new_lines on a 10 MB, 5k-line JSONL fixture with Instant timing, before and after the cursor rewrite

#228 Sandboxed sub-agent tailing spawns docker exec tail every 500 ms per agent

  • Impact low, effort M, verdict partly, evidence proven-by-code, area acp-supervisor, category subprocess
  • Where: src/acp/background_agent.rs:47-96, src/acp/background_agent.rs:337-350, src/acp/background_agent.rs:376-418
  • Frequency: Every POLL_INTERVAL (500 ms) per running background sub-agent in a container session, including idle ticks until ABORT_AFTER (300 s)
  • Problem: TranscriptSource::Container::read_from runs <runtime> exec <container> tail -c +N path each tick, and exists() runs test -e every 500 ms while waiting. Each docker exec goes through the daemon API and forks inside the container, about 2 process spawns per second per agent even when nothing changed.
  • Fix: Read the transcript through the host bind mount when the Claude home is mounted, or keep one long-lived docker exec tail -c +N -F path child per agent and read its stdout as a stream, replacing the poll loop in run_tailer.
  • Verifier: Confirmed: read_from runs one docker exec tail per 500 ms tick per running sandboxed agent, up to 300 s idle. That is about 2 execs/s per agent. exists() runs only during the first 30 s wait, not alongside reads. This is niche: sandboxed sessions with background sub-agents only. A host-path read needs mapping /root/.claude to the sandbox config mount, which is unverified.
  • Measure: Run a sandboxed session with 3 background agents; count execs via docker events --filter event=exec_start over 60 s

#229 Workflow agent progress tailers poll at 500 ms for the whole run even though the directory is already watched

  • Impact low, effort M, verdict partly, evidence proven-by-code, area acp-supervisor, category cpu
  • Where: src/acp/background_agent.rs:221-276, src/acp/workflow_journal.rs:71-80, src/acp/workflow_journal.rs:258-268
  • Frequency: Every 500 ms per workflow agent until the run ends; no idle abort in run_progress_tailer
  • Problem: run_progress_tailer does metadata + File::open + seek + read_to_end every 500 ms per agent, forever while the run lasts. Agent transcripts live in the same dir the WorkflowJournal already subscribes to via FileWatchService, so a run with 20 agents does about 80 syscalls/s while idle.
  • Fix: Give spawn_progress_tailer the shared FileWatchService and subscribe with FileMatcher::Exact(agent transcript path) and WATCH_DEBOUNCE, falling back to SAFETY_REREAD/FALLBACK_POLL as task_transcript::TaskTailer::follow does.
  • Verifier: 500ms POLL_INTERVAL loop per agent confirmed (background_agent.rs:15,280). But the loop also drives stall detection and last_growth timers, so it needs a timer anyway; watcher swap adds complexity for ~2 syscalls per tick per agent, negligible.
  • Measure: Run a 20-agent workflow and use dtruss/strace -c -f on the daemon for 30s; compare open/read counts.

#230 One transcript row per agent message chunk inflates row count, snapshots and per-connection memory

  • Impact low, effort L, verdict partly, evidence plausible-needs-measurement, area acp-supervisor, category memory
  • Where: src/acp/transcript.rs:315-336, src/acp/transcript.rs:337-367, src/server/acp_ws.rs:248
  • Frequency: Per AgentMessageChunk/AgentThoughtChunk; each WS connection keeps its own TranscriptModel; transcript_snapshot sends every row on connect
  • Problem: apply_event appends a new TranscriptRow (msg-{seq}) for every chunk, each with id, group_id, timestamp and empty vecs. Row count scales with streamed chunks rather than messages, multiplying memory per connected client, snapshot JSON size and every linear scan above.
  • Fix: Coalesce chunks of the open message/thought group into one row: in TranscriptModel::apply_event, append text to the open group's row and emit a new TranscriptDelta::AppendText { id, text } (or Patch) instead of a new row; clients concatenate into the existing row.
  • Verifier: apply_event pushes msg-{seq} or thought-{seq} rows per chunk (transcript.rs:315-365), and each WS connection folds its own TranscriptModel (acp_ws.rs:128). Overhead is about 90 JSON bytes per chunk because empty fields are skipped. acp_events already stores one row per chunk. Coalescing changes the delta protocol for web, TUI and http replay plus id-based idempotency, so the win is small for L effort.
  • Measure: For a long real session, compare the transcript_snapshot frame size with the summed row text length to get the per-row overhead ratio.

#231 Per-event clones and block_in_place on the worker drain path

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-supervisor, category cpu
  • Where: src/acp/supervisor/mod.rs:889-901, src/acp/supervisor/drain.rs:323-326, src/acp/supervisor/sink.rs:272-281, src/acp/supervisor/sink.rs:452-458
  • Frequency: Every event pumped from every worker
  • Problem: Drain::pump owns each Event but passes &event, so publish_from_worker deep-clones it into Publication, and publish_tagged clones it again for Arc::new(event.clone()). publish_with_next_seq also wraps each publish in block_in_place, which hands the runtime core to another thread, although the closure only does try_send unless the 4096-slot queue is full.
  • Fix: Add publish_from_worker_owned(session_id, seq, event: Event, generation) and pass the owned event from pump. Make Persister::publish_tagged take Event by value and wrap it in Arc without cloning. In publish_with_next_seq, try_lock the counter and call publish inline, using blocking_io only when contended or the queue is full.
  • Verifier: Double clone confirmed (sink.rs:276, 455), but events are small JSON structs and the queue then does SQLite writes per event, so clones are minor. block_in_place is deliberate: counter lock holder can block on store I/O, per the comment.
  • Measure: Benchmark pump with a synthetic stream of 100k events using criterion or dhat to count allocations; compare clone vs owned.

#232 Retained history pages serialize on the single read_conn mutex instead of the reader pool

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-supervisor, category concurrency
  • Where: src/acp/event_store/replay.rs:106-160, src/acp/event_store/mod.rs:200-221
  • Frequency: Per retained history page request (web/TUI scrollback paging); scales with concurrent clients
  • Problem: retained_page locks self.read_conn(), one shared connection, for its whole snapshot transaction, so concurrent page reads from different clients and sessions wait on each other while the pooled reader() with up to MAX_IDLE_READERS idle connections sits unused.
  • Fix: Use self.reader() in retained_page (the ReadConn deref gives a Connection; use unchecked_transaction as page() does), keeping read_conn only where a fixed connection is required.
  • Verifier: retained_page does hold the single read_conn mutex (replay.rs:106), shared with search. But the call is rare (history paging, one indexed LIMIT query, ms). reader() pool is a simple swap, though tests use pause hooks tied to this path.
  • Measure: Fire N concurrent GET retained history requests at the server across sessions and compare p99 latency before and after the swap.

#233 Task transcript and workflow journal readers allocate a zeroed 256 KB buffer per wakeup

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-supervisor, category memory
  • Where: src/acp/task_transcript.rs:425-445, src/acp/workflow_journal.rs:200-228
  • Frequency: Per file-watch change (debounced 50 ms) or 30 s safety reread, per background task tailer and per workflow journal; the session transcript changes on almost every agent step
  • Problem: scan() and Follower::read_new each run vec![0u8; READ_CHUNK_BYTES], allocating and zeroing 256 KB even when only a few hundred bytes were appended. With several background tasks per active session that is several MB of memset per second.
  • Fix: Store the buffer in Cursor / Follower and reuse it across calls, or size it to min(READ_CHUNK_BYTES, file_len - offset) from the metadata already fetched.
  • Verifier: vec![0u8; 256KB] per scan/read_new confirmed (task_transcript.rs:432, workflow_journal.rs:217). But vec![0;n] uses calloc, so large zeroed pages are lazily mapped by the OS, not memset; cost is small. Reuse buffer is trivial but win negligible.
  • Measure: dhat or heaptrack on a session with several background tasks; or criterion bench of scan() on a tiny appended file.

#234 Retention prune runs an O(cap) OFFSET scan plus deletes on every event when a cap is set

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-supervisor, category disk-io
  • Where: src/events/mod.rs:255-318, src/acp/event_store/mod.rs:254-271, src/acp/event_store/mod.rs:417-490
  • Frequency: Every event when acp.replay_events != 0 (default 0 = unlimited); completed-work sweep every 64 seqs
  • Problem: prune_retention walks max_events index entries (LIMIT 1 OFFSET cap) on every insert, then runs a DELETE with NOT LIKE filters that rescans every pinned row below the cutoff and an attachments DELETE with a NOT IN subquery. prune_completed_background_work adds O(k^2) correlated json_extract EXISTS checks.
  • Fix: In EventStore::record, prune only when seq is a multiple of a batch size (e.g. 256) or count exceeds cap + slack, so the OFFSET walk and deletes amortize across many inserts.
  • Verifier: prune_retention returns at once when max_events==0, which is the default (v006 migration forces 0). Only opt-in caps pay the LIMIT 1 OFFSET cap index walk per insert; sweep already runs every 64 seqs. Batching is safe but only helps capped users.
  • Measure: Set acp.replay_events=5000, stream 50k chunks, time EventStore::record with and without batching (criterion or tracing span around prune_retention).

#235 Unresolved background task query is quadratic in task starts per session

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area acp-supervisor, category cpu
  • Where: src/acp/event_store/turns.rs:54-77, src/acp/event_store/turns.rs:318-336
  • Frequency: Every try_in_flight_turn (first step) and unresolved_background_task_* call; scales with BackgroundTaskStarted rows squared, never pruned at default retention
  • Problem: For each BackgroundTaskStarted row, two correlated NOT EXISTS subqueries scan later starts and finishes and compare json_extract results, parsing JSON on both sides. A session that ran hundreds of background shells pays tens of thousands of JSON parses per probe.
  • Fix: Rewrite as one pass: SELECT task ids with MAX(seq) per json_extract(task_id) for starts and finishes via GROUP BY, then join, or persist task_id in a generated column with an index on (session_id, discriminant, task_id).
  • Verifier: Query is quadratic in BackgroundTaskStarted rows, but indexed on (session_id, discriminant, seq) and short-circuits on first unresolved; the all-resolved case scans fully. Callers are event-driven reconciler/sink probes, not a tick. Dozens to hundreds of starts per session is cheap.
  • Measure: Seed a session with 1000 started/finished tasks, run try_has_unresolved_background_tasks in a loop and time it, or EXPLAIN QUERY PLAN.

#236 AcpState keeps every background agent, subagent and workflow run for the session's lifetime

  • Impact low, effort S, verdict partly, evidence proven-by-code, area acp-supervisor, category memory
  • Where: src/acp/state.rs:663-674, src/acp/state.rs:1572-1577, src/acp/state.rs:1583-1600
  • Frequency: Grows per launched sub-agent; state is cloned and serialized for each reduced_state push and control cache fold
  • Problem: background_agents (each with prompt, up to 250 tools, result up to 256 KB), subagents and workflow_runs are never trimmed, unlike background_shells (MAX_FINISHED_BACKGROUND_SHELLS) and recent_diffs. Long sessions with many subagents keep growing every per-connection AcpState and every snapshot serialization.
  • Fix: In AcpState::apply_event on BackgroundAgentCompleted and BackgroundTaskFinished, keep at most N ended records (as for background_shells) and drop the oldest ended ones; do the same for ended subagents and finished workflow_runs.
  • Verifier: background_agents, subagents and workflow_runs are never trimmed (only shells at 20 and diffs). But records are small per sub-agent, and trimming could drop UI history the replayed log still rebuilds, causing inconsistency. Real growth only in very long sessions.
  • Measure: Run a session with 500 background agents, then measure serialized AcpState size and the reduced_state push payload bytes.

#237 Per-insert history-version trigger adds a random-blob upsert to every event write

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area acp-supervisor, category disk-io
  • Where: src/acp/event_store/identity.rs:28-35
  • Frequency: Every insert and every deleted row (FOR EACH ROW), including bulk session deletes
  • Problem: acp_history_insert runs an upsert into acp_history_versions with randomblob(16) per event, an extra b-tree page write per streamed chunk. Deleting a 50k-event session fires 50k upserts for one logical change.
  • Fix: Bump the version once per transaction instead: drop the insert/delete triggers and have EventStore::record (or record_batch) and delete_session_checked run one explicit UPSERT per touched session_id inside their transaction.
  • Verifier: Trigger upserts one hot row per event inside the same transaction, so it hits the same cached page; cost is small. Triggers also guarantee version bumps for prune and update paths. Replacing them with explicit upserts risks missing a writer and stale history identity.
  • Measure: Benchmark inserting 50k events and deleting a session with and without the triggers on a temp DB; compare wall time.

#238 Context primer decodes the entire history to keep only the last 20 turns

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area acp-supervisor, category memory
  • Where: src/acp/context_primer.rs:114-218, src/server/api/acp/history.rs:345-346
  • Frequency: Per context-primer request (session load failure / resume); scales with full session length
  • Problem: history.rs loads replay_before(id, before_seq), every event deserialized, and fold_turns accumulates every turn's full assistant_text and tool map, while build_context_primer keeps only turns.len() - max_turns onward.
  • Fix: Read events newest-first in pages (replay_page_before) until max_turns UserPromptSent boundaries are collected, then fold only that suffix; or keep only the last max_turns turns in a VecDeque inside fold_turns.
  • Verifier: Handler decodes every event via replay_before and fold_turns builds all turns before keeping the last max_turns. Cost is O(session) memory and CPU, but it is a rare on-demand endpoint (failed session/load). Note included_event_count semantics would change under suffix folding.
  • Measure: Seed a 200k-event session, call GET /api/sessions/{id}/acp/context-primer and compare latency and peak RSS.

4.tmux

#239 strip_ansi is quadratic and runs twice per status detection

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tmux, category cpu
  • Where: src/tmux/utils.rs:12-33, src/tmux/status_detection.rs:11-24, src/tmux/status_detection.rs:79-91, src/tmux/session.rs:833-852, src/session/instance/status_update.rs:569-572
  • Frequency: Per captured session per daemon status tick (500ms with subscribers, 2s otherwise; skipped only when window_activity is unchanged, so every streaming/spinner session pays it). Also per CLI/MCP/smart-rename capture.
  • Problem: strip_ansi rebuilds the whole String with format! for every CSI and BEL-OSC escape, so cost is escapes x length. A coloured 50-line Claude capture (5-15KB, hundreds of SGRs) copies megabytes per call. detect_status_from_content_in strips once, then the manifest fn pointer (detect_via_manifest) strips the already-clean text again. Captures use -e only to have escapes removed afterwards.
  • Fix: Rewrite strip_ansi as one forward pass pushing non-escape spans into a single preallocated String (skip CSI to final byte 0x40-0x7E, OSC to BEL/ST). For detection, add Session::capture_text(lines) without -e so no stripping is needed. In detect_status_from_content_in call super::detect::detect on the clean text directly instead of (a.detect_status)(&clean).
  • Verifier: strip_ansi (utils.rs:12-33) does rebuild the String with format! for every CSI and BEL-OSC escape, so the cost is quadratic. But the main daemon path (update_status_from_manifest, status_update.rs:569-572) strips once and calls plan.detect(&clean). The double strip only happens in the legacy non-manifest path (status_update.rs:390) and in smart_rename/CLI. Captures are skipped when the screen is unchanged. Expect under 1ms per capture.
  • Measure: Criterion bench of strip_ansi on a real 50-line coloured Claude capture (capture-pane -p -e), old versus single-pass, plus a count of daemon captures per second.

#240 Session scan and pane scan are two forks per tick that one chained tmux call can serve

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area tmux, category subprocess
  • Where: src/tmux/mod.rs:613-621, src/tmux/mod.rs:695-740, src/tmux/mod.rs:1430-1440, src/tmux/mod.rs:2610-2615, src/server/status_poll.rs:512-513
  • Frequency: Daemon status tick (500ms with subscribers, 2s otherwise) and TUI snapshot poller every 1s; continuous for process lifetime.
  • Problem: refresh_session_cache (show-options x3 + list-sessions) and batch_pane_metadata (list-panes -a) are always called back to back, each a separate tmux fork and server round trip. Both pollers pay 2 forks per cycle forever, i.e. 4 forks/s in the daemon with a subscriber plus 2/s in the TUI.
  • Fix: Add scan_sessions_and_panes() building one tmux_query_command: the INHERITABLE_KIND_SCOPES show-options, list-sessions -F SESSION_SCAN_FORMAT, display-message -p a sentinel line, list-panes -a -F . Split stdout at the sentinel, feed parse_session_scan and parse_pane_metadata, publish both SESSION_CACHE and PANE_META_CACHE. Use it in status_poll and refresh_display_snapshots.
  • Verifier: Real: status_poll.rs:512-513 calls refresh_session_cache then batch_pane_metadata, two forks per tick, and the TUI path gates both on _if_due. Merging them saves only one fork per tick (about 2-5ms). It also couples the separate error classification each path does (no server, no current target, inventory fallback). The same tick also forks for pending_retirement_targets.
  • Measure: Time one fork of each with hyperfine 'tmux list-sessions -F ...' and 'tmux list-panes -a -F ...' against a chained command on a 30-session server.

#241 batch_pane_metadata re-lists all panes plus a server-identity fork whenever any tool pane is dead or unmarked

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area tmux, category subprocess
  • Where: src/tmux/mod.rs:1441-1478, src/tmux/tool_session.rs:364-376, src/tmux/mod.rs:2753-2778
  • Frequency: Every batch_pane_metadata call (each daemon tick, plus API handlers) for as long as one dead (remain-on-exit) or legacy unmarked tool pane exists, which can be hours.
  • Problem: The condition is persistent, so each call adds ToolSession::server_identity (list-sessions fork plus process birth lookups) and a second full display-message;list-panes -a fork, then re-parses all rows. Pane polling cost triples for the fleet because one stale tool pane exists.
  • Fix: Always run the first scan as display-message -p '#{socket_path}|#{pid}' ; list-panes -a -F ... so pid and socket come with the rows. Cache TmuxServerIdentity (with birth) in a Mutex<Option<..>> keyed by pid and reuse it, then stamp pane.server on tool rows without a second list-panes.
  • Verifier: Code matches the claim (mod.rs:1441-1478): a dead or Unmarked tool pane adds a list-sessions fork (configured_tmux_server_identity), a birth lookup and a second list-panes -a every call. But only legacy unmarked or remain-on-exit tool panes trigger it, which are rare and usually transient. Caching the identity is safe if the pid check and process_birth_is_live check stay.
  • Measure: Log at debug when the tool-pane rescan branch runs. Count hits per hour on real user daemons before deciding whether to optimize.

#242 VT row serialization allocates an SGR String per cell under the parser lock

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area tmux, category cpu
  • Where: src/tmux/vt.rs:1735-1769, src/tmux/vt.rs:1806-1846, src/tmux/vt.rs:1881-1929, src/tmux/vt.rs:2998-3058, src/tmux/vt.rs:3070-3116
  • Frequency: Every VtChannel sample on a grid-generation change (live TUI preview and web live view, driven by chunk wakeups while an agent streams); rows x cols cells, up to window_lines (50 by default, up to 2000 when scrolled).
  • Problem: row_to_ansi_upto calls cell_sgr for every cell, which builds a Vec, per-param Strings, join and format!, only to compare with the previous cell's SGR. A 50x200 styled grid is tens of thousands of allocations per sample, done while holding the parser mutex, which also stalls the reader thread's process() of new chunks.
  • Fix: Compare a Copy attribute tuple (fgcolor, bgcolor, bold, dim, italic, underline, inverse) with the previous cell and only on change write the SGR straight into out with std::fmt::Write; drop the Vec in cell_sgr/push_color_params. Reserve out to cols*2.
  • Verifier: cell_sgr (vt.rs:1735) builds Vec, join and format! per styled cell; unstyled cells return an empty String without allocating. SampleCache keyed by grid_gen limits sampling to one per change, but live_ws allows up to 60 Hz (FRAME_MIN_INTERVAL_MS=16) while streaming, all under the parser lock. Fix is safe. The win is CPU and lock hold time of about 1 ms per sample.
  • Measure: Criterion bench of grid_content on a 50x200 parser fed a recorded Claude Code stream, before and after; also time the parser lock hold in sample_with_clock.

#243 Per-name pane probes cost two forks each, four for is_pane_running_shell

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tmux, category subprocess
  • Where: src/tmux/utils.rs:242-266, src/tmux/utils.rs:405-407, src/tmux/utils.rs:436-450, src/tmux/utils.rs:480-497, src/tmux/utils.rs:512-525
  • Frequency: Fallback paths when batched metadata is absent (status_update.rs:261/487/510), per TUI action (app.rs:3110), restart, MCP control; per session per call.
  • Problem: probe_pane, pane_current_command and pane_start_command_is_protected each fork list-panes to find the first pane, then fork display-message for one field. is_pane_running_shell chains two of them, so 4 forks for facts one list-panes call already returns.
  • Fix: Add first_pane_facts(session) running one list-panes -s -t =name: -F '#{window_index} #{pane_index} #{pane_id} #{pane_dead} #{pane_current_command}\x1f#{pane_start_command}', sort as today and return a struct. Implement probe_pane, pane_current_command, pane_start_command_is_protected and is_pane_running_shell on top of it.
  • Verifier: Fork counts are right (is_pane_running_shell = 4). Not hot in the status poll (batched metadata). Only real loops are wait_for_pane_ready (50ms, up to 3s) and resume probe, ~7 forks per iteration. Fix is safe but wins tens of ms at session start.
  • Measure: Count tmux spawns during wait_for_pane_ready via a tmux wrapper script logging argv, starting one session.

#244 TUI display snapshot poller forks every second even when nothing reads it

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area tmux, category cpu
  • Where: src/tmux/mod.rs:2610-2650, src/tmux/mod.rs:2319-2338
  • Frequency: Every 1s (CACHE_TTL/2) for the TUI process lifetime, idle or not.
  • Problem: refresh_display_snapshots runs list-sessions and list-panes -a each cycle unconditionally, so an idle TUI left open for hours keeps forking tmux 2 times per second and waking the tmux server, independent of whether any frame consumed the snapshot.
  • Fix: Set a static AtomicBool SNAPSHOT_READ in session_exists_for_display, pane_dead_for_display and session_name_for_display; in the poller loop skip the refresh (just park) when it was not set since the last cycle, and swap it to false after refreshing.
  • Verifier: Poller wakes every 1s but forks only when snapshot is due (>=1s old); real cost is 2 cheap list calls per second in the TUI process only. Skipping when unread risks a stale first frame after idle unless refresh-on-read is added.
  • Measure: Idle TUI for 60s with a tmux wrapper logging argv; count list-sessions/list-panes -a calls and CPU of tmux server.

#245 aoe tmux-status makes four tmux forks per status refresh

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tmux, category subprocess
  • Where: src/tmux/status_bar.rs:225-240, src/tmux/status_bar.rs:268-283, src/tmux/mod.rs:2652-2665
  • Frequency: Per tmux status-interval per attached client for users who put #(aoe tmux-status) in their bar.
  • Problem: get_session_info_for_current runs display-message for the session name, then a separate show-options fork for each of @aoe_title, @aoe_branch and @aoe_sandbox, on top of starting the aoe binary itself.
  • Fix: Replace with one display-message -p '#{session_name}\x1f#{@aoe_title}\x1f#{@aoe_branch}\x1f#{@aoe_sandbox}' and split on \x1f; treat empty fields as None.
  • Verifier: Four forks confirmed in get_session_info_for_current, but it runs only for users who wire #(aoe tmux-status) at status-interval (default 15s). Binary startup dominates the saved ~15ms. Merge is easy; keep the empty-title fallback and per-field emptiness handling.
  • Measure: hyperfine 'aoe tmux-status' inside an aoe tmux session before and after; compare wall time.

#246 apply_all_tmux_options issues about ten sequential set-option forks per session

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area tmux, category subprocess
  • Where: src/tmux/status_bar.rs:25-79, src/tmux/status_bar.rs:115-134, src/tmux/status_bar.rs:168-221
  • Frequency: Per session start, restart and terminal creation; scales with sessions on bulk restore/startup recovery.
  • Problem: apply_status_bar calls set_session_option nine times (status, @aoe_title/branch/sandbox, status-right, -length, status-style, status-left, -length) and mouse adds one more, each a separate tmux fork with a 10s-timeout wrapper.
  • Fix: Collect the (option, value) pairs and run them as one set-option -t =name: k v ; set-option ... invocation, falling back to per-option calls on failure, as env::run_write_batch already does.
  • Verifier: apply_status_bar does 9 sequential forks plus mouse, each run via a timeout wrapper. About 50-100ms per session start, scaling on bulk restore. Fix caveat: a title or branch ending in ';' would be read as a tmux command separator, so escape it. Fallback pattern exists in env.rs.
  • Measure: Time apply_all_tmux_options with a tmux wrapper logging spawn count; restore 20 sessions before and after.

#247 Tool retirement journal is locked, read, parsed and validated every status tick

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area tmux, category disk-io
  • Where: src/tmux/tool_session.rs:122-124, src/tmux/tool_retirement.rs:34-68, src/tmux/tool_retirement.rs:79-84
  • Frequency: Every daemon status tick (500ms/2s) via status_poll.rs ToolSession::pending_retirement_targets.
  • Problem: Each tick opens the app dir, takes a LockedDataFile lock, reads the JSON, deserializes and runs validate (including serde_json::to_string per owner and receipt tree validation) only to list (instance_id, tool_name) pairs that almost never change.
  • Fix: Cache the decoded targets in a Mutex keyed by the journal file's (mtime, len); on unchanged metadata return the cached Vec without locking or parsing. Writers already go through LockedJournal::save, which changes mtime.
  • Verifier: Real: every status tick (2s idle, 500ms active) does open, flock, read, parse, validate in spawn_blocking (status_poll.rs:514). Journal is tiny, usually near-empty, so cost is sub-millisecond. mtime cache would skip the lock and risks coarse-mtime staleness against writers.
  • Measure: Wrap LockedJournal::open in tracing Instant timing under AGENT_OF_EMPIRES_DEBUG=1 with 50 sessions; compare to total tick duration.

#248 VT authoritative self-heal recaptures 2000 lines of scrollback every 10s

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area tmux, category cpu
  • Where: src/tmux/vt.rs:1397-1460, src/tmux/vt.rs:2924-2980, src/tmux/vt.rs:1519-1570
  • Frequency: Every 10s (AUTHORITATIVE_CAPTURE_INTERVAL) per live TUI preview with a VT channel, plus resize/drift reseeds.
  • Problem: refresh_authoritatively runs pane_seed_state plus capture-pane -e -S -2000 (2 forks per attempt), copies the body, lf_to_crlf-copies it again, replays it into a new vt100 parser with 2000 scrollback and scans it for OSC 8, even when the grid already matches the pane.
  • Fix: In refresh_authoritatively, first capture only the visible screen (no -S) and compare capture_rows_padded output with the grid's visible rows from row_to_ansi_upto; call reseed only on mismatch. Keep full-history reseed for resize.
  • Verifier: Runs in TUI live_send.rs only for the one selected preview, every 10s, and only when the pane is quiet (Busy is deferred). Two tmux forks per 10s is trivial. Visible-rows-only compare would miss scrollback drift, which is the self-heal purpose.
  • Measure: Time refresh_authoritatively on a pane with 2000 lines of scrollback; log elapsed in live_send.rs:1543.

#249 VT reader runs three extra per-byte scanners and an Osc8 buffer copy on every chunk

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area tmux, category cpu
  • Where: src/tmux/vt.rs:96-160, src/tmux/vt.rs:234-271, src/tmux/vt.rs:2141-2205, src/tmux/osc8.rs:45-88, src/tmux/vt.rs:1984-2003, src/tmux/vt.rs:2121-2123
  • Frequency: Per pipe-pane chunk (up to 8KB) for every armed VT channel while the agent streams; reader also wakes every 200ms idle.
  • Problem: SyncOutputScanner, Osc52Scanner and Osc8Scanner each walk every byte; Osc8Scanner first appends the whole chunk to its buffer then drains it. record_links clones the whole table on each chunk with links. The 200ms poll timeout wakes each reader 5 times/s only to check stop.
  • Fix: memchr the chunk for 0x1b; if absent and all scanner states are Idle, skip all three. In Osc8Scanner::feed scan the chunk in place when buf is empty and only buffer the tail. Compare generation instead of cloning in record_links. Stop the reader via conn.shutdown() and poll with -1.
  • Verifier: record_links already returns early when found is empty, so the clone happens only on chunks containing links. Armed channels exist only for live previews, not every session. Scanners are cheap next to vt100 parsing. The 200ms poll wake is negligible.
  • Measure: perf or flamegraph a streaming agent with a live preview; check scanner share of run_reader versus vt100 process().

#250 Composite preview clones every non-input pane's rows each frame

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tmux, category memory
  • Where: src/tmux/composite.rs:107-125, src/tmux/composite.rs:183-251
  • Frequency: Per live-preview frame of a split tmux window (cached layout re-rendered with fresh pane-0 rows).
  • Problem: composite_with_first_pane_rows builds a new Vec, cloning each pane's id and full rows Vec, only to pass a slice to composite_window.
  • Fix: Change composite_window to take an iterator or slice of (&PaneGeom, &[String]) and have composite_with_first_pane_rows pass the cached panes' borrowed rows plus the new pane-0 rows without cloning.
  • Verifier: Clones are real (composite.rs:115-123, plus rows.to_vec() for pane 0), but composite_window then allocates and copies every row again into the output String. Win is a few dozen small allocs per frame, microseconds. Needs a CapturedPane signature change for little gain.
  • Measure: Criterion bench of composite_with_first_pane_rows on a 3-pane 200x50 layout, before and after the borrow refactor.

#251 tmux -V is forked twice on first VT arm

  • Impact low, effort S, verdict partly, evidence proven-by-code, area tmux, category subprocess
  • Where: src/tmux/vt.rs:1607-1648
  • Frequency: Once per process (first VT channel arm), plus again after any failed probe since failures are not cached.
  • Problem: tmux_supports_pipe_pane_io and tmux_supports_pipe_pane_input each hold their own OnceLock and each call tmux_version, so the first arm pays two tmux -V forks on the latency-sensitive preview open path.
  • Fix: Cache the parsed (major, minor) in one static OnceLock<Option<(u32,u32)>> read by both functions.
  • Verifier: Two separate OnceLocks each call tmux_version (vt.rs:1607-1628), so first arm forks tmux -V twice; failures are uncached (cached_tmux_support). But it is once per process, a few ms. A single cached (major, minor) is correct and trivial, yet the win is tiny.
  • Measure: Run dtruss/strace -f -e execve on a fresh aoe launch and count tmux -V execs on first live preview arm.

4.process-daemon

#252 Every tmux/git subprocess run creates two named temp files and polls exit with sleep backoff

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area process-daemon, category latency
  • Where: src/process/mod.rs:771-797 (run_with_timeout_inner), src/process/mod.rs:674-724 (wait_with_timeout_inner_with_clock), src/tmux/mod.rs:486-499 (run_tmux_command_with_timeout_inner)
  • Frequency: Every tmux command run through TmuxCommandDeadline (about 170 call sites, including capture_pane on each 2s status poll per session), plus git remote/worktree and systemctl calls
  • Problem: Each call does two NamedTempFile::new() (create in $TMPDIR), two reopen() by path, and two unlinks on drop: about 8 extra fs syscalls plus directory churn (fseventsd noise on macOS). Exit is found by sleeping 1,2,4,8,16,25ms, so a 30ms tmux call returns at about 56ms. Cost scales with session count times poll rate.
  • Fix: Keep regular files (the comment explains why) but use tempfile::tempfile() plus try_clone() for the child's Stdio: anonymous, no reopen or unlink. Replace the sleep loop with a blocking wait: pidfd + poll on Linux, kqueue EVFILT_PROC on macOS, each with the timeout. Or block in waitid on a helper thread with recv_timeout.
  • Verifier: Claim on code holds (mod.rs:809-812, backoff 1..25ms), but the latency math is wrong: polls land at 1,3,7,15,31ms, so a 30ms call returns at about 31ms and a 4ms tmux call at about 7ms. capture-pane itself uses plain .output() (session.rs:839-849). Only live_pane_target goes through the deadline path. tempfile() still creates and unlinks on macOS.
  • Measure: Wrap run_with_timeout_inner in a tracing span and compare its p50 with child wall time over a 20-session status poll on macOS.

#253 Prime-agent status fallback forks ps three times per session per poll on macOS

  • Impact low, effort S, verdict partly, evidence proven-by-code, area process-daemon, category subprocess
  • Where: src/process/macos.rs:1356-1416 (foreground_arguments), src/process/macos.rs:1431-1471 (get_foreground_pid, find_process_in_group), src/process/macos.rs:192-219 (collect_pid_tree, build_children_map), src/session/instance/prime_capture.rs:512-520, src/session/instance/status_update.rs:375-379
  • Frequency: Every status poll (2s, sometimes 500ms) for each prime-agent session whose pane text matches no status rule and whose Prime observation is unavailable
  • Problem: foreground_arguments runs ps -o tpgid, then ps -A -o pid,pgid, then ps -A -o pid,ppid. That is three fork/execs, and two of them dump the whole process table. On Linux the same path walks /proc twice. Cost is sessions times poll rate times process count.
  • Fix: On macOS, read e_tpgid from proc_pidinfo(PROC_PIDTBSDINFO) (process_membership already wraps it). Short-circuit find_process_in_group: return tpgid when getpgid(tpgid)==tpgid. Get descendants with proc_listchildpids instead of building a full ps map. On Linux, check /proc//stat before walking /proc.
  • Verifier: Three ps forks confirmed (macos.rs get_foreground_pid, find_process_in_group, build_children_map). The path runs only for prime-agent panes when no status rule matches and prime_runtime().observe() returns None, which is a narrow fallback. A getpgid(tpgid)==tpgid short-circuit is an S-sized fix that removes one full-table ps.
  • Measure: Count prime_live_status fallback hits with a debug counter during an hour of mixed prime-agent sessions.

#254 Runner liveness checks fork ps on the async runtime while holding a global std Mutex

  • Impact low, effort M, verdict partly, evidence proven-by-code, area process-daemon, category concurrency
  • Where: src/acp/runner_lifecycle.rs:721-751 (SystemProcessControl::with_guard, is_alive), src/process/mod.rs:1444-1470 (RunnerProcessGuard::executing), src/process/mod.rs:1360-1442 (RunnerProcessGuard::refresh), src/process/macos.rs:291-318 (runner_group_executing), src/process/macos.rs:702-735 (runner_group_identities), src/acp/supervisor/teardown.rs:694-700
  • Frequency: Every 50ms (TEARDOWN_POLL) per session during ACP teardown and kill_wedged_runner, up to the grace window
  • Problem: is_alive is synchronous but runs from async teardown loops. On macOS, executing() calls refresh() and then ps -A twice (runner_group_identities and runner_group_executing), each with up to a 2s timeout. All of this runs inside the single guards std::sync::Mutex. Concurrent teardowns serialize on that lock and block tokio workers.
  • Fix: Call control.is_alive through tokio::task::spawn_blocking in teardown.rs and drain.rs. In SystemProcessControl, hold one Mutex per identity (for example HashMap<RunnerIdentity, Arc<Mutex>>) so the map lock is never held across the census. In runner_group_executing, short-circuit to false when killpg(group, None) returns ESRCH before walking the census.
  • Verifier: The facts hold. is_alive runs synchronously in async teardown loops (teardown.rs:694, 1400; drain.rs:1316) while it holds the global std Mutex (runner_lifecycle.rs:731), and on macOS it forks ps -A 1 to 2 times. This happens only during teardown at a 50ms cadence, not in steady state. The cost matters only when many sessions tear down at once, for example on daemon shutdown.
  • Measure: Tear down 20 ACP sessions at once on macOS and log max with_guard lock hold time plus the tokio worker blocked duration via tokio-console.

#255 Group-settlement loops run a full process census every 25ms

  • Impact low, effort S, verdict partly, evidence proven-by-code, area process-daemon, category cpu
  • Where: src/process/mod.rs:386-440 (OwnedProcessGroup::settle_with_signal), src/process/mod.rs:540-575 (terminate_and_reap_process_group, unreaped_group_settled), src/process/mod.rs:1493-1511 (RunnerProcessGuard::settle), src/process/linux.rs:1338-1370 (runner_group_executing), src/process/macos.rs:291-318
  • Frequency: During each process-group termination (opencode capture teardown, plugin commands, runner settle): every 25ms for up to grace + 5s
  • Problem: Each poll calls runner_group_executing. On Linux that is a full /proc walk reading every stat file. On macOS it is a ps -A fork. A slow-exiting group costs up to about 200 censuses. A group that is already empty still pays one full census per check.
  • Fix: At the top of linux::runner_group_executing and macos::runner_group_executing, add a killpg(group, None) probe and return Ok(false) on ESRCH. An empty group then costs one syscall. Keep the census only to tell zombie-only groups apart. Back off the 25ms sleep exponentially to 100ms after the first SIGTERM.
  • Verifier: Census per 25ms poll is real (/proc walk on Linux, ps fork on macOS). Callers are teardown paths only (plugin exec grace 250ms, pane/tool_session trees, ZERO grace). The killpg ESRCH probe is useless for OwnedProcessGroup and terminate_and_reap: the unreaped zombie leader keeps the group alive, so killpg succeeds. Backoff is the only useful part. Linux RunnerProcessGuard already checks its pidfd anchor first.
  • Measure: Count runner_group_executing calls per teardown with a tracing counter, then time plugin command teardown on macOS with hyperfine.

#256 File-watch subscribe blocks a tokio worker on watcher install while holding the global lock

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area process-daemon, category concurrency
  • Where: src/file_watch.rs:367-457 (FileWatchService::subscribe), src/file_watch.rs:156-195 (watch_loop), src/acp/task_transcript.rs:376, src/acp/workflow_journal.rs:72, src/logging.rs:955
  • Frequency: Per ACP task transcript follow and per workflow journal follow (per subagent task), plus startup subscribers
  • Problem: subscribe_channel runs std::fs::canonicalize and metadata, then blocks in rx.recv() until the backend thread commits the notify paths. All of this happens while holding inner: Mutex, and it is called from async fns. On macOS, the FSEvents commit restarts the stream. Meanwhile dispatch_path, fire_due and other subscribers block on the same std Mutex on tokio threads.
  • Fix: In subscribe, release inner before waiting on the reply channel: record pending state, drop the guard, wait, then re-lock to finalize. Or switch the async callers in task_transcript.rs and workflow_journal.rs to subscribe_channel_deferred, which already covers the race with a refresh. Move canonicalize ahead of the lock.
  • Verifier: Confirmed: subscribe holds the std Mutex inner and blocks in rx.recv() until watch_loop commits paths, and task_transcript.rs:376 and workflow_journal.rs:72 call it from async fns. The blocking install runs only when a dir is new (refcount 0) or its identity drifted. Switching the two callers to subscribe_channel_deferred is the safe fix. Dropping the lock mid-install needs pending-state rework.
  • Measure: Add a tracing span around rx.recv() in FileWatchService::subscribe on macOS and record its p99 during a run that starts many subagent tasks.

#257 Web system-health endpoint samples once per client request with no shared cache

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area process-daemon, category cpu
  • Where: src/server/api/system.rs:2114-2140 (system_health), src/process/metrics.rs:203-252, web/src/hooks/useSystemHealth.ts:6-9
  • Frequency: Every 500ms per web tab with the detail open, every 15s per collapsed tab, multiplied by open tabs and devices
  • Problem: Each request clones every Instance (state.instances.read().clone()) and runs a full sample (process table, tmux list-panes, worker registry dir scan). N tabs mean N full samples. Two clients also interleave CPU deltas over very short windows, which gives noisy CPU figures.
  • Fix: Store the last MetricsSnapshot with its Instant in AppState next to metrics_sampler. In system_health, return the cached snapshot if it is younger than 500ms, and resample only otherwise. Pass Arc'd instances or ids instead of cloning Vec.
  • Verifier: Each request samples and clones instances. The sampler mutex is taken inside spawn_blocking, so samples serialize. Hidden tabs stop polling, collapsed tabs poll every 15s, and the 500ms rate applies only to an open detail view. Duplicate samples need several visible clients with the detail open. A short-lived cached snapshot is cheap and would also fix the noisy CPU deltas.
  • Measure: Log the duration and caller count of sampler.sample() in system_health while 2 browsers have the detail open. Compare daemon CPU with top -pid.

#258 Agent hook shell command spawns about 6 processes per hook event

  • Impact low, effort S, verdict partly, evidence proven-by-code, area process-daemon, category subprocess
  • Where: src/hooks/command.rs:139-176 (hook_command_with_write), src/hooks/command.rs:96-128 (status_command_with_base)
  • Frequency: Every agent hook fire (PreToolUse, PostToolUse, UserPromptSubmit, Stop, ...) per session, so several per tool call
  • Problem: Each status write runs sh plus external mkdir -p twice, ls -ldn twice, id -u, and often cat for stdin. That is about 6 fork/execs per event and about 12 per tool call. Cost scales with agent activity times sessions and adds latency to the agent's synchronous hooks.
  • Fix: In hook_command_with_write, skip mkdir when [ -d "$D" ] already holds. Use one ls -ldn "$B" "$D" call parsed with set --, and compute ME once. Use mkdir -p "$B" "$D" only on the slow path. Keep the mode and owner checks but halve the forks. The Rust dir_guard stays authoritative.
  • Verifier: The host script runs external mkdir twice, ls twice in $() subshells, id -u, and cat for bound or waiting-tool hooks. That is about 6 fork/execs inside sh, roughly 5-15ms per hook. Agent tool calls take seconds, so the user-visible win is small. Guarding mkdir -p with [ -d ] and computing ME once is safe. Merging the two ls calls saves little.
  • Measure: Run hyperfine on the generated hook command string with AOE_INSTANCE_ID set and stdin piped, before and after the change.

#259 kill_process_tree blocks for a fixed 100ms and forks ps per call, sometimes on async threads

  • Impact low, effort S, verdict partly, evidence proven-by-code, area process-daemon, category latency
  • Where: src/process/mod.rs:1820-1867 (kill_process_tree, kill_with_fallback), src/process/macos.rs:192-219, src/acp/acp_client/mod.rs:1186-1190, src/process/runner/mod.rs:458-461, src/tmux/mod.rs:1388-1410
  • Frequency: Per session stop or teardown. stop_all_sessions calls it N times in sequence.
  • Problem: Every call rebuilds the full children map (ps -A fork on macOS, /proc walk on Linux), then std::thread::sleep(100ms), even when every pid exited at once. acp_client calls it inside an async fn while holding a tokio Mutex, which blocks a worker for over 100ms. stop_all_sessions pays N maps and N times 100ms, as its own ponytail comment notes.
  • Fix: Replace the fixed sleep in kill_with_fallback with a poll of process_exists every 10ms up to 100ms, exiting early when all pids are gone. Add a kill_process_trees(&[u32]) that builds one children map, for stop_all_sessions. Call it via spawn_blocking in acp_client/mod.rs and runner/mod.rs.
  • Verifier: Fixed 100ms sleep and one ps/proc map per call are real (mod.rs:2060-2100). But only on stop/teardown, not a hot path. The async blocking claim holds: acp_client:1189 holds the tokio Mutex while calling it. Early-exit poll and spawn_blocking are cheap safe wins.
  • Measure: Time stop_all_sessions with 20 tmux sessions: wall clock before vs after; check tokio worker stall via tokio-console during ACP client shutdown.

#260 Log writer does a synchronous write syscall per event under a global Mutex and reallocates its line buffer

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area process-daemon, category latency
  • Where: src/logging.rs:577-605 (init_subscriber_with_options, Mutex<SizeRotatingWriter>), src/logging.rs:731-743 (emit_line), src/logging.rs:822-845 (Write::write), src/logging.rs:506-528 (NoSpanFormat::format_event)
  • Frequency: Per enabled log event on every thread (daemon, TUI, runner)
  • Problem: Events are written inline: the global Mutex is held across write_all to the file, so tokio workers serialize on log I/O when debug or trace targets are enabled. std::mem::take(&mut self.line_buf) discards capacity, so every line regrows the Vec from zero. format_event also allocates an RFC3339 String per event.
  • Fix: Wrap SizeRotatingWriter in tracing_appender::non_blocking (lossy=false, bounded) so formatting stays inline but I/O moves to one thread. In write(), call emit_line on the buffer and then line_buf.clear(), swapping through a local Vec to satisfy the borrow, so capacity is kept. Write the timestamp with chrono's format directly into the writer.
  • Verifier: Mutex across write_all and line_buf take (logging.rs:822-845) are real, though a regrow costs one small alloc per line. tracing-appender is not a dependency. Non-blocking lossy or async writes risk losing the final logs on crash and break rotation and test reads. Default levels are low volume.
  • Measure: Run with RUST_LOG=trace under an ACP load and perf or samply the daemon; check time in SizeRotatingWriter::write versus total CPU.

#261 CLI telemetry rewrites state on every command and can block startup on a network POST

  • Impact low, effort S, verdict partly, evidence proven-by-code, area process-daemon, category startup
  • Where: src/telemetry/mod.rs:438-455 (track_cli_command), src/telemetry/state.rs:190-240, src/telemetry/mod.rs:365-397 (post), src/main.rs:342-347
  • Frequency: Every opted-in CLI invocation. The POST happens at most daily, or hourly while offline.
  • Problem: Before the command runs, each invocation loads config, takes a flock, reads and rewrites the state file, and then reads it again in cli_usage_due. When due, it awaits a fresh reqwest Client (TLS init) and a POST of up to 2s, or 500ms connect while offline, ahead of the user's command.
  • Fix: Merge record_cli_command and cli_usage_due into one update_state_locked call that returns whether a flush is due. Move the POST after the command completes, or spawn it and await it with a short cap at exit. Reuse one reqwest::Client through a OnceLock.
  • Verifier: Real: track_cli_command awaits post inline, up to 2s once per day (hourly retry offline), plus a flock RMW and a second load_state per opted-in command. Reqwest Client OnceLock is pointless for one POST per process. Merging the read is trivial; moving the POST needs a flush-at-exit cap.
  • Measure: hyperfine 'aoe --version' opted in vs DO_NOT_TRACK=1; run with offline network and an expired flush stamp to time the blocking window.

#262 Runtime stream ships and parses the full session list on every revision

  • Impact low, effort L, verdict partly, evidence plausible-needs-measurement, area process-daemon, category network
  • Where: src/daemon/runtime.rs:236-252 (RuntimeContents, RuntimeSnapshot), src/daemon/runtime_connection.rs:158-205 (receive_event), src/daemon/runtime_connection.rs:232-252 (receive)
  • Frequency: Per canonical revision (any status or metadata change on any session), per connected TUI or CLI client
  • Problem: Every frame holds all SessionResponse rows, profiles and projects. The client fully deserializes it, then drops it if the revision is stale. With N sessions changing status independently, client parse work is O(N) per change, so O(N^2) per interval. The full-state design is deliberate, but cost grows with session count.
  • Fix: Keep full-state semantics but add a RuntimeFrame::SessionsPatch {cursor, upserts, removed} for revisions that only touch rows, and send the full snapshot only on hello or resync. On the client, apply the patch to Arc through Arc::make_mut. Check the revision before deserializing the body by splitting the cursor out.
  • Verifier: Code matches: receive() does serde_json::from_str of the full snapshot, stale revisions are parsed then dropped. Full-state is deliberate and fixes use a large patch protocol. Cost only matters at hundreds of sessions. Cheap alternative is a revision peek or sender-side coalescing.
  • Measure: Time serde_json::from_str of a RuntimeFrame::Snapshot with 200 sessions; multiply by status revisions per second on a busy daemon.

#263 Status hook commands each hold a blocking-pool thread and poll for exit

  • Impact low, effort M, verdict partly, evidence proven-by-code, area process-daemon, category concurrency
  • Where: src/status_hooks.rs:302-327, src/status_hooks.rs:350-373 (run_hook_command_blocking), src/process/mod.rs:719-738 (run_status_with_timeout_process_group)
  • Frequency: Per debounced status transition per session when status_hooks are enabled
  • Problem: Each transition spawns a spawn_blocking task that runs the hook with a 30s cap, polling try_wait with 1 to 25ms sleeps. Nothing bounds how many run at once, so a status storm across many sessions can take up to N blocking threads and spawn N shells together.
  • Fix: Run hooks with tokio::process::Command and process_group(0) and await child.wait() under tokio::time::timeout, with killpg on timeout or cancel. Bound concurrency with a tokio::sync::Semaphore (for example 4) inside StatusHooks.
  • Verifier: Each debounced transition does spawn_blocking, polling try_wait, with no concurrency cap. But it only runs when the user configured hooks and commands are nonempty, debounce coalesces flaps, and the blocking pool is 512. A Semaphore is a cheap fix; the tokio rewrite is not needed.
  • Measure: Enable a sleep-30 hook, flip 50 sessions' status, and watch blocking-thread and shell-process counts via ps and tokio-console.

4.cli-startup

#264 Steady-state startup reconcile re-parses every profile's sessions.json twice and re-reads it per sandboxed row

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area cli-startup, category startup
  • Where: src/migrations/mod.rs:424-475, src/migrations/v027_isolate_sandbox_stores.rs:558-582, src/migrations/v027_isolate_sandbox_stores.rs:629-700, src/migrations/v033_isolate_sandbox_content.rs:2311-2395, src/migrations/v033_isolate_sandbox_content.rs:973-981
  • Frequency: Every CLI command except the exempt ones in main.rs (also TUI launch and daemon start), even when schema == CURRENT_VERSION. Scales with number of profiles, sessions per registry, and sandboxed rows.
  • Problem: With current == CURRENT_VERSION, run_migrations_inner still calls v027 reconcile_pending (Config::load via get_container_runtime plus load_registries) and v033 reconcile_in (read_registries again). For each sandboxed (row, tool) the bare-start branch calls resolve_config(profile) and read_row(), which re-reads and re-parses the whole registry: O(sandbox_rows x registry size).
  • Fix: Do both scans from one shared load_registries pass. Cache a pending marker (e.g. a .sandbox_reconciled stamp file keyed on registry mtime/len) so a bare start skips the scan when nothing changed. In v033 hoist resolve_config per profile out of the per-target loop and look up rows in the already-parsed registries instead of read_row().
  • Verifier: Confirmed in steady state: v027 calls get_container_runtime (Config::load) and load_registries. v033 calls read_registries again, then per sandboxed (row, tool) calls resolve_config plus read_row, which re-parses the whole registry. The container probe is lazy and never runs when nothing is pending. Cost is JSON and TOML parsing only, likely a few ms at realistic registry sizes.
  • Measure: Wrap run_migrations_inner's current==CURRENT_VERSION branch in Instant timing and log it with 50 sandboxed sessions across 3 profiles.

#265 Every one-shot CLI process builds a multi-thread Tokio runtime

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area cli-startup, category startup
  • Where: src/main.rs:86, src/main.rs:111, src/main.rs:124, src/cli/extract_session_id.rs:21-60, src/cli/tmux.rs:24-45
  • Frequency: Once per aoe process. Hot callers: hidden aoe __extract-session-id run by agent hooks (per hook event, per session), aoe tmux status in tmux status-right (every status-interval, per client), completion, init, hooks.
  • Problem: tokio::runtime::Runtime::new() creates a work-stealing runtime with one worker thread per core, plus I/O and timer drivers. Extract-session-id, tmux status, completion and init do only blocking sync work but still pay thread spawn and teardown on each invocation.
  • Fix: In main(), match on cli.command: for ExtractSessionId, Tmux, Completion, Init, Agents, Theme and Url use runtime::Builder::new_current_thread().enable_all(), or call the sync handler without a runtime. Keep multi_thread for serve, add and the TUI.
  • Verifier: Claim holds: main.rs:124 builds Runtime::new() for every command, including __extract-session-id (Claude UserPromptSubmit, Hermes pre_llm_call) and tmux status. Spawning worker threads costs well under 1 ms on macOS. That is small next to process exec, config load and the per-hop ps spawns in finding 3. A current_thread switch is safe but saves little.
  • Measure: hyperfine 'aoe __extract-session-id </dev/null' with AOE_INSTANCE_ID set, comparing multi_thread against new_current_thread builds.

#266 aoe __extract-session-id spawns one ps per ancestor hop on macOS

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area cli-startup, category subprocess
  • Where: src/cli/extract_session_id.rs:75-130, src/process/macos.rs:1417-1429
  • Frequency: Per agent hook invocation that carries an identity field (session-start and similar), per session, when AOE_AGENT_PID and AOE_AGENT_BIN are set. Cost scales with the ancestor depth between hook and agent, typically 2-6.
  • Problem: walk_reaches_single_agent calls parent_and_argv0 for each hop. On macOS it runs ps -o ppid=,args= -p PID per hop (fork+exec, tens of ms each), inside the agent's hook critical path. Linux reads /proc and is fine.
  • Fix: Implement macos::parent_and_argv0 with libc proc_pidinfo(PROC_PIDTBSDINFO) for ppid plus proc_pidpath or sysctl KERN_PROCARGS2 for argv0, with no subprocess. Alternatively fetch one ps -A -o pid=,ppid=,comm= and walk the map in memory.
  • Verifier: macos.rs:1417 forks ps for each hop. The walk runs synchronously inside identity hooks, which include Claude's UserPromptSubmit and Hermes pre_llm_call, so it delays every prompt, not only session start. macos.rs already uses proc_pidinfo and KERN_PROCARGS2 sysctl (lines 434, 1029, 1362), so a libc version is cheap to write. Expect about 5-15 ms saved per hop, 2-4 hops.
  • Measure: In a Claude pane on macOS, set AOE_AGENT_PID/BIN and run hyperfine on aoe __extract-session-id --field session-id </dev/null before and after.

#267 Agent availability probe spawns a serial which subprocess per agent, then a login shell

  • Impact low, effort S, verdict partly, evidence proven-by-code, area cli-startup, category subprocess
  • Where: src/tmux/mod.rs:3153-3185, src/tmux/mod.rs:3364-3377, src/tmux/mod.rs:3227-3242, src/cli/agents.rs:8
  • Frequency: Once per aoe agents run and per cold probe path (probe_agents_available: add override checks, settings and API recheck, then 60s TTL). Scales with the number of built-in agents (~15) and with how many are not on PATH.
  • Problem: agent_available_direct runs Command::new("which") through run_with_timeout_process_group, which creates two tempfiles and forks per agent, serially. Any agent that is missing then forces a $SHELL -lc login shell (rc files, nvm) of up to 15s. The TUI startup path already uses in-process which::which, so the two are inconsistent.
  • Fix: In agent_available_direct, replace the which subprocess with which::which(binary).is_ok() (same PATH inheritance). Keep the single batched login-shell probe only for misses, and skip it for aoe agents unless a flag asks for a deep scan.
  • Verifier: Confirmed: agent_available_direct forks which via run_with_timeout_process_group (two NamedTempFiles each), serially, about 14 Which agents. agent_availability_snapshot already uses which::which. But the login shell for misses is the deliberate one-batch design (#3909, nvm installs). Skipping it would misreport agents. Real win: about 14 forks, tens of ms.
  • Measure: hyperfine 'aoe agents' before and after swapping in which::which, on a machine where every agent is on PATH so the login shell is skipped.

#268 aoe tmux status spawns 4 tmux processes per refresh and runs the telemetry hook first

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area cli-startup, category subprocess
  • Where: src/cli/tmux.rs:24-45, src/tmux/status_bar.rs:227-281, src/tmux/mod.rs:2652-2665, src/main.rs:163-167, src/telemetry/mod.rs:438-455
  • Frequency: Per tmux status-interval (default 15s) per attached client, for users with #(aoe tmux status) in status-right.
  • Problem: get_session_info_for_current runs display-message for the session name, then three separate show-options -v calls for @aoe_title, @aoe_branch and @aoe_sandbox. Before that, run() calls track_cli_command, which loads config and, if telemetry is opted in, takes the state.toml flock and rewrites it for every status refresh.
  • Fix: Fetch everything with one display-message -p -F '#{session_name}\x1f#{@aoe_title}\x1f#{@aoe_branch}\x1f#{@aoe_sandbox}' and split it. Add Commands::Tmux to the telemetry exclusion (command_name returns None for it).
  • Verifier: get_session_info_for_current runs display-message plus three show-options forks. command_name maps Tmux to "tmux", so track_cli_command takes the state.toml lock and rewrites it each refresh. It can also POST, with a 2s timeout, once the daily slot is due. Do not split on \x1f: tmux 3.4 octal-escapes it. Use tabs or newlines.
  • Measure: Run hyperfine 'aoe tmux status' inside an aoe tmux session with telemetry opted in, before and after the change. Watch the state.toml mtime across status refreshes.

#269 Config.toml and state.toml parsed 5-6 times during one startup

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area cli-startup, category startup
  • Where: src/main.rs:51-52, src/main.rs:177-182, src/main.rs:341-353, src/session/mod.rs:1116-1160, src/session/poller.rs:97-101, src/containers/mod.rs:49-53, src/telemetry/mod.rs:70-72
  • Frequency: Once per CLI or TUI launch. Each extra load is a read plus TOML parse of a large Config, plus state.toml and a second parse for ignored-key detection.
  • Problem: One launch calls load_config (log sink), probe_global_config (parse plus serde_ignored parse), resolve_config for the poller ceiling, Config::load in get_container_runtime during reconcile, is_opted_in for telemetry, then the command's own load. Each is an independent file read and deserialize with no memo.
  • Fix: Add a per-process memo of the loaded global Config keyed on (mtime, len) of config.toml and state.toml, invalidated by update_config and update_app_state. Route load_or_warn, get_container_runtime, get_telemetry_settings and get_update_settings through it.
  • Verifier: Repeated loads are real (main.rs log sink, probe, poller ceiling at main.rs:420, container runtime, telemetry), but each is a small file read and parse, once per launch. Memo keyed on mtime adds invalidation risk, since 33 get_container_runtime callers expect fresh reads. Likely sub-10ms total.
  • Measure: Time Config::load with a typical config.toml via a tracing span, or run hyperfine 'aoe --version' vs aoe list and compare.

#270 aoe session wait polls at 1s with a full reload, adding up to 1s+ latency

  • Impact low, effort S, verdict partly, evidence proven-by-code, area cli-startup, category latency
  • Where: src/cli/session.rs:1527, src/cli/session.rs:1600-1650
  • Frequency: Per poll (1s) for the duration of a wait. Scripts and agents that orchestrate with aoe session wait --until idle.
  • Problem: Each iteration runs refresh_session_cache twice (tmux list-sessions), reloads and parses the whole sessions.json via storage.load(), and runs status detection (capture-pane). The wait only sees a state change on the next tick, and Running to Idle needs a second observation, so effective latency is at least 1-2s.
  • Fix: Lower WAIT_POLL_INTERVAL to ~200ms and make the poll cheap by dropping the sessions.json reload. Alternatively wait on the daemon status event stream (a runtime read websocket) instead of polling when a daemon is running.
  • Verifier: Polling at 1s with sessions.json reload per tick is true (session.rs:1527, 1620). Latency is up to 1s plus a second observation for Running to Idle. But the reload is needed to adopt stored state, and 200ms would multiply tmux and capture-pane spawns. Only the interval tradeoff is real.
  • Measure: Run aoe session wait --until idle on a session that just finished and time it with time; repeat with the interval at 250ms.

#271 Update cache read and config load run synchronously on async tasks; cache write is non-atomic

  • Impact low, effort S, verdict partly, evidence proven-by-code, area cli-startup, category latency
  • Where: src/update/mod.rs:92-117, src/update/mod.rs:119-131, src/server/api/system.rs:2381-2411
  • Frequency: Per GET update-status request (web polls hourly per open tab), per TUI 60s tick check, and per list/ps. Cost scales with cached release body size (up to 20 changelogs).
  • Problem: check_for_update is async but does get_update_settings (Config::load_or_warn) plus fs::read_to_string and serde_json parse of update_cache.json (20 releases with full markdown bodies) directly on the runtime worker. save_cache uses plain fs::write, so a concurrent reader can see a truncated file and refetch.
  • Fix: Wrap the settings and cache read in tokio::task::spawn_blocking, or store latest_version in a tiny separate field or file so the hot path does not parse bodies. Use crate::session::atomic_write in save_cache.
  • Verifier: save_cache uses plain fs::write (update/mod.rs:119-123) while atomic_write exists in session/storage.rs. A torn read only causes a refetch. Blocking read is a small local file once per hour per tab, so spawn_blocking is not worth it. Atomic write is the cheap valid fix.
  • Measure: Time load_cache with a 20-release update_cache.json under a tracing span; expect well under 1ms.

4.plugin-git-containers

#272 Plugin RPCs re-read and double-parse sessions.json on every call

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area plugin-git-containers, category disk-io
  • Where: src/plugin/host_api.rs:323, src/plugin/host_api.rs:349, src/plugin/host_api.rs:521, src/plugin/host_api.rs:80, src/session/storage.rs:2171
  • Frequency: Per worker RPC (session.meta.get/set/cas, session.capture.set, sessions.list); a plugin reacting to status events can issue several per second. Cost scales with session count.
  • Problem: Each call builds Storage::new_unwatched, then storage.load() reads the whole sessions.json and parses it twice (to serde_json::Value, then per row). session.meta.set/cas rewrite the whole file. The daemon already holds the same rows in session_service.instances, which session_api.rs uses.
  • Fix: Serve session.meta.get and sessions.list from SessionRpcDeps.session_service.instances (read lock). Route meta set/cas and capture through the session service so the in-memory row changes and one coalesced save runs. Fallback: use load_instances_readonly_cached with a shared SessionsFileCache.
  • Verifier: Confirmed: session_meta_get, sessions_list and session_capture_set each run Storage::new_unwatched + load(), and the Recover path parses to Value then deserializes per row. It runs on spawn_blocking, so it never blocks the runtime. Per-call cost is about 1 ms at typical sessions.json sizes, and no in-repo plugin polls these. Serve reads from session_service.instances. Rerouting set/cas is riskier.
  • Measure: Add a tracing span with elapsed time around storage.load() in host_api read RPCs, then run a plugin that calls sessions.list in a loop with 100 sessions.

#273 events.publish prunes with LIMIT 1 OFFSET retention, scanning up to 10k index rows per publish

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area plugin-git-containers, category latency
  • Where: src/plugin/host_api.rs:272, src/events/mod.rs:255, src/plugin/automation_policy.rs:137, src/plugin/host.rs:23
  • Frequency: Per events.publish RPC (and per admit_turn/admit_message/audit with 2000 retention); runs under the single global std::sync::Mutex.
  • Problem: prune_retention runs SELECT seq ... ORDER BY seq DESC LIMIT 1 OFFSET retention on every publish. SQLite walks up to EVENT_RETENTION_PER_TOPIC=10_000 index entries to find the cutoff, even when nothing needs deleting. All plugins share the one connection mutex, so a chatty plugin delays the others.
  • Fix: Seq is gapless and monotonic (highest_seq()+1), so compute cutoff = new_seq - retention in events_publish and run DELETE ... WHERE session_id=? AND seq <= cutoff directly. Add a prune_below(seq) helper in src/events and use it from AutomationPolicy::admit_windowed and audit.
  • Verifier: Confirmed: prune_retention uses LIMIT 1 OFFSET retention on the (session_id, seq) primary key and runs on every publish. That is an index walk of at most 10k entries, roughly sub-millisecond. Plugin topics are gapless because events_publish passes no pinned prefixes, so seq - retention works there. Audit and admit callers need a separate gaplessness check.
  • Measure: Seed one topic with 10k events, then time events_publish with and without the OFFSET query using EXPLAIN QUERY PLAN and a criterion microbench.

#274 events.subscribe returns the whole topic unpaginated and workers must poll

  • Impact low, effort M, verdict partly, evidence proven-by-code, area plugin-git-containers, category latency
  • Where: src/plugin/host_api.rs:288, src/plugin/host_api.rs:312
  • Frequency: Per worker subscribe call (plugin-chosen poll cadence). Result size scales with retained events (up to 10_000).
  • Problem: scan(..., None) has no limit, so after_seq=0 loads up to 10k rows, parses each payload into serde_json::Value, and builds one JSON-RPC line, all under the global events mutex. There is no push for plugin events, unlike session.status.changed, so consumers poll.
  • Fix: Add a limit param to events_subscribe (default 500, max 1000) passed to events::scan, plus has_more in the response. Optionally emit an events.published notification through PluginHost.notify_worker so idle workers stop polling.
  • Verifier: Confirmed: events_subscribe calls scan(..., None) with no limit, so after_seq=0 can return up to 10k rows built under the events mutex. This only costs anything on a cold subscribe, because later polls with a cursor are small. Adding a limit changes the RPC contract: callers must loop on has_more. The push notification is a feature, not a performance fix.
  • Measure: Seed 10k events on one topic, then time events.subscribe with after_seq=0 and measure the hold time of the state.events mutex.

#275 serve_connection awaits each RPC serially, so one slow call blocks the worker's other RPCs

  • Impact low, effort M, verdict partly, evidence proven-by-code, area plugin-git-containers, category latency
  • Where: src/plugin/host.rs:947, src/plugin/host.rs:977, src/plugin/session_api.rs:277
  • Frequency: Per worker RPC. sessions.create (worktree add, git fetch up to 10s, hooks) and sessions.turn.send hold the loop for seconds.
  • Problem: The read loop does work.run(...).await before reading the next line. While sessions.create runs, the same worker's ui.state.set, ui.notify and storage calls queue behind it, so its UI state goes stale for seconds. Every non-session RPC also pays a spawn_blocking hop, even the in-memory ui.state.set.
  • Fix: In serve_connection, spawn each dispatch as a task bounded by a per-worker Semaphore (about 8). Responses carry ids and the writer is a single channel, so ordering is safe. Call UiStore ops inline instead of spawn_blocking; keep spawn_blocking only for SQLite and storage methods.
  • Verifier: Confirmed: serve_connection awaits work.run for each request before it reads the next line. sessions.create is capped at 20 per hour per plugin, so stalls are rare. Concurrent dispatch would reorder pipelined calls, for example storage.set then get, and plugins may rely on that order. Keep the order per method class instead. The spawn_blocking hop for ui.state.set costs microseconds.
  • Measure: Log per-RPC queue wait (line read to dispatch start) in serve_connection while a worker issues sessions.create, then ui.state.set.

#276 GET /api/plugins/ui-state rebuilds, serializes and hashes the full snapshot on every 3s poll even when unchanged

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area plugin-git-containers, category cpu
  • Where: src/server/api/plugins.rs:361, src/plugin/ui_state.rs:571, web/src/hooks/usePluginUiState.ts:4, web/src/hooks/usePluginUiState.ts:71
  • Frequency: Every 3s per open dashboard tab (500ms for 15s after a poke), forever while idle. Cost scales with total UI entries (up to 1024 per plugin, 64KB pane payloads) and tab count.
  • Problem: UiStore::snapshot clones every entry payload and sorts. The handler then does to_value, to_vec, hashes the bytes for the ETag and only afterwards answers 304. Per-plugin revision counters already exist but are not used to short-circuit. The client also calls setEntries with a new array each tick, re-rendering consumers when nothing changed.
  • Fix: Add a global AtomicU64 revision to UiStore bumped in set/remove/notify/clear_plugin/begin_generation. Use it as the ETag (combined with a registry generation for pages) and return 304 before calling snapshot(). Client: skip setEntries/setRevisions on 304. Longer term, push via the existing WS channel.
  • Verifier: Handler at plugins.rs:354 does snapshot clone+sort, to_value, to_vec, hash before the 304 check, as claimed. But typical entry counts are small, so server cost is microseconds. The ETag also covers registry pages, so a store revision alone is insufficient. Bigger waste: fetch returns a fresh parsed array on 304, so setEntries re-renders consumers every 3s.
  • Measure: React Profiler commit count for usePluginUiState consumers over 60s idle; tracing span around plugin_ui_state with 50 entries.

#277 Diff files scan reruns per file click and every 10s poll, with per-line PathBuf allocation

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area plugin-git-containers, category cpu
  • Where: src/git/diff.rs:90, src/git/diff.rs:110, src/git/diff.rs:112, src/server/state.rs:89, src/server/api/sessions/diff.rs:412, web/src/hooks/useDiffFiles.ts:6
  • Frequency: Web: every 10s per open diff panel and once per file selection beyond the 1.5s cache TTL. TUI: each refresh. Scales with repo size, untracked files and patch size.
  • Problem: compute_changed_files runs a tree-to-workdir diff with untracked recursion and copy detection, then diff.print(Patch) to count +/- lines, calling path.to_path_buf() for every diff line (headers and context too) and rendering whole patch text. The per-file endpoint only needs the file list to validate the path and fetch counts, yet triggers a full rescan once the 1.5s TTL lapses.
  • Fix: Count with git2::Patch::from_diff(&diff, idx)?.line_stats() per delta (no text rendering, no per-line alloc). In session_diff_file validate the path with a targeted pathspec diff, not changed_files_cached. Gate the 10s poll on the file watch service or backoff while the fingerprint is unchanged.
  • Verifier: Per-line to_path_buf in diff.print callback is real (diff.rs:110). The dominant cost is the workdir/untracked walk plus xdiff, which Patch::line_stats still pays. The 10s poll only runs when the panel is enabled. A 1.5s TTL cache (state.rs:96) already dedupes click bursts.
  • Measure: Time compute_changed_files on a large repo with criterion: current print vs Patch::from_diff line_stats; log duration per /diff/files request.

#278 Plugin update check runs serially: one HTTP client, one release API call and one git ls-remote per plugin

  • Impact low, effort S, verdict partly, evidence proven-by-code, area plugin-git-containers, category network
  • Where: src/plugin/update_check.rs:23, src/plugin/update_check.rs:38, src/plugin/update_check.rs:75, src/plugin/fetch.rs:279, src/plugin/auto_update.rs:96
  • Frequency: Per dashboard Check for updates click and per daemon/TUI startup when updates.auto_update_plugins is on. Scales with installed external plugins.
  • Problem: outdated() awaits check_one for each plugin in a for loop. Each unpinned github plugin builds a fresh reqwest client (GitHubClient::unauthenticated, no connection reuse), calls releases/latest (60 req/hour unauthenticated), then spawns git ls-remote. N plugins cost N times the sum of latencies.
  • Fix: In outdated(), build one GitHubClient and drive check_one with futures_util::stream::iter(...).buffer_unordered(4). Pass the shared client into latest_release_tag. Keep results sorted by id as now.
  • Verifier: Serial loop and per-call client in latest_release_tag are real. But it runs only on explicit click or startup auto-update, with few plugins. Parallelism cuts wall time only; request count and the 60/hour limit are unchanged. Client reuse is trivial.
  • Measure: Time aoe plugin outdated with 5+ github plugins installed, before and after buffer_unordered(4).

#279 Session list takes the remote_owner_cache write lock on every request for repos with no origin

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area plugin-git-containers, category concurrency
  • Where: src/server/api/sessions/list.rs:405, src/server/api/sessions/list.rs:423, src/server/api/sessions/list.rs:437, src/git/remote.rs:312
  • Frequency: Every GET /api/sessions (dashboard refetches) for each session whose repo has no origin remote. First lookup per repo opens it with git2 on the runtime thread.
  • Problem: A cached None leaves session.remote_owner None, so the repo lands in uncached again. The code takes remote_owner_cache.write().await each time just to find contains_key true. The first miss runs blocking git2 open_repo_at and find_remote while holding the async write lock. The cache never invalidates.
  • Fix: Build uncached from keys absent in the read-locked cache (cache.contains_key), not from remote_owner.is_none(). Resolve misses in spawn_blocking before taking the write lock to insert.
  • Verifier: Cached None leaves remote_owner None, so the repo goes into uncached and takes write().await on every list call. Only contains_key runs, so the hold is short but blocks readers. First miss does sync git2 under the lock. Real but minor.
  • Measure: Add a counter around remote_owner_cache.write() in list.rs; hit GET /api/sessions repeatedly with an origin-less repo session.

#280 Worker stderr log is unbounded in size for a long-lived worker

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area plugin-git-containers, category disk-io
  • Where: src/plugin/host.rs:685, src/plugin/host.rs:697, src/plugin/worker_logs.rs:68
  • Frequency: Continuous for the life of each plugin worker (hours to days). Rotation only trims the count to 5 per plugin at spawn.
  • Problem: stderr is redirected straight to an append-mode file, and prune_plugin only removes older files. A chatty or crash-looping-within-budget worker can grow one file without limit and nothing truncates it while it runs.
  • Fix: Pipe stderr through a task that copies lines into the log with a cap (for example 5 MiB, then rotate to .1 or truncate), or at minimum prune by total bytes in prune_plugin. Alternatively tail-limit on write via a bounded ring file.
  • Verifier: stderr goes straight to an append file; prune_plugin runs only at spawn and counts files, not bytes. No in-run cap exists, so growth is unbounded for a chatty worker. Needs a noisy plugin to matter; disk-only, not CPU.
  • Measure: Run a plugin worker that logs heavily for an hour; check size with ls -lh in the workers log dir.

#281 Worktree create walks the whole checkout (depth 6) just to log file counts

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area plugin-git-containers, category disk-io
  • Where: src/git/worktree/create.rs:341, src/git/worktree/create.rs:394
  • Frequency: Once per aoe-created worktree session. Scales with checkout file count (monorepos: hundreds of thousands of stat calls).
  • Problem: The walk is guarded by tracing::enabled!(INFO), described as only paid when logged. The default level is info, so it always runs: read_dir plus entry.metadata() per file, synchronously after git worktree add, delaying session start.
  • Fix: Gate it on tracing::enabled!(Level::DEBUG) (target git.worktree) or delete walk_worktree_stats and log only add_elapsed. If counts are wanted, read the index entry count via git2 Index::len() on the new worktree instead.
  • Verifier: Default log level is info, so enabled!(INFO) is always true and walk_worktree_stats runs after every worktree add: read_dir plus metadata per entry, depth-capped at 6. Result is only logged. Cost scales with checkout size, so large repos pay hundreds of ms.
  • Measure: Time walk_worktree_stats on a large checkout (e.g. linux kernel) via a temporary Instant log, or compare session create with the call removed.

#282 GitWorktree::list_worktrees opens every linked worktree repo to read its HEAD (O(M) opens per listing)

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area plugin-git-containers, category disk-io
  • Where: src/git/worktree/mod.rs:377, src/git/worktree/mod.rs:393, src/git/worktree/mod.rs:337, src/session/trash.rs:291, src/session/trash.rs:316
  • Frequency: Per call: session create, trash sweeps (hourly per trashed session), deletion, attach, worktree_edit. Scales with worktrees per repo and sessions sharing it.
  • Problem: worktree_entries calls get_current_branch(&path), which does open_repo_at for each linked worktree (parsing shared config, which the code itself calls costly) plus canonicalize. ReconcileCache amortizes this for reconcile only. trash.rs calls list_worktrees fresh per session, so cost is N*(M+1) opens.
  • Fix: Read the branch from the admin dir HEAD file (.git/worktrees//HEAD, via wt.path() or repo.path().join("worktrees").join(name).join("HEAD")) and parse ref: refs/heads/X, skipping the per-worktree open. Reuse ReconcileCache in trash.rs checks.
  • Verifier: worktree_entries does open_repo_at per linked worktree via get_current_branch: real O(M) opens. But M is typically small, calls are on user actions or an hourly sweep, and git2 open is ~ms. Hand-parsing HEAD files adds fragility (reftable, bare repos).
  • Measure: Benchmark list_worktrees on a repo with 20 linked worktrees using a criterion bench or Instant logging; compare against reading HEAD files.

#283 aoe-agent emits one ACP notification per text delta with no coalescing

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area plugin-git-containers, category latency
  • Where: acp-worker/aoe-agent/src/index.ts:85, acp-worker/aoe-agent/src/index.ts:92
  • Frequency: Per streamed model token chunk (tens per second per active aoe-agent turn). Each goes through JSON-RPC encode, pipe write, Rust parse and event-log append, then fans out to WS clients.
  • Problem: Each text-delta does await update({sessionUpdate: agent_message_chunk, ...}), so there is a full ndjson frame and a downstream event per chunk. The await also serializes the model stream behind the stdout write, adding backpressure latency.
  • Fix: In handlePrompt buffer deltas and flush on a timer (about 30 to 50ms) or at 512 bytes, and flush immediately before any tool_call or end_turn. Keep assistantBuffer unchanged for persistence.
  • Verifier: Per-delta await update() is real (index.ts:85-92), but aoe-agent is the minimal built-in agent and LLM streams are tens of chunks/s. Downstream cost per frame is small. Coalescing is feasible but changes chunk granularity seen by clients; win is minor.
  • Measure: Run an aoe-agent turn, count session/update frames per turn and event-log appends; compare CPU of daemon with 30ms coalescing.

#284 Automation ledger SQLite and std Mutex used directly on the async runtime

  • Impact low, effort S, verdict partly, evidence proven-by-code, area plugin-git-containers, category concurrency
  • Where: src/plugin/automation_policy.rs:121, src/plugin/session_api.rs:588, src/plugin/session_api.rs:645, src/plugin/session_api.rs:861
  • Frequency: Per sessions.create, sessions.turn.send, sessions.message.send and each audit write. Each is 3 to 4 SQL statements plus prune.
  • Problem: admit_windowed and audit take std::sync::Mutex and run count_since, highest_seq, insert and prune on the tokio worker thread from async fns, with no spawn_blocking. A stalled disk or a held lock blocks a runtime thread, delaying unrelated requests and terminal streams.
  • Fix: Wrap admit_create/admit_turn/admit_message/audit in tokio::task::spawn_blocking inside session_api, or move the ledger onto a dedicated writer thread fed by an mpsc channel and make audit fire-and-forget.
  • Verifier: Claim true: sync SQLite (WAL, synchronous=NORMAL) under std Mutex in async fns. But it runs only per plugin-initiated create/turn/message, about 4 small statements on a local file. Blocking is sub-millisecond; spawn_blocking is hygiene, not a measurable win.
  • Measure: Time admit_windowed with tracing::Instant around the lock and SQL in a burst of 100 sessions.turn.send calls.

#285 tree_hash reads every file of a plugin into memory before hashing

  • Impact low, effort S, verdict partly, evidence proven-by-code, area plugin-git-containers, category memory
  • Where: src/plugin/integrity.rs:12, src/plugin/integrity.rs:29, src/plugin/registry.rs:157, src/plugin/update_check.rs:101
  • Frequency: Per registry load for each featured plugin (startup and every reload_registry on toggle/install), per local-plugin update check, and per fetch. Scales with plugin tree size.
  • Problem: collect() pushes (path, Vec contents) for all files, then hashes. Peak memory equals the whole plugin tree (assets, vendored code), allocated on every registry reload that verifies a featured plugin.
  • Fix: Collect only (rel path, PathBuf), sort, then feed each file to the Sha256 hasher through a fixed 64 KiB buffered reader using the length from metadata. Output is identical since the hash input order and bytes are unchanged.
  • Verifier: collect() does fs::read of every file into a Vec (integrity.rs:29-50), so peak memory is the whole tree. Real, but only for featured plugins at registry load and plugin trees are small source. Streaming hash with identical output is safe. Transient.
  • Measure: Run /usr/bin/time -l on registry load with a featured plugin installed; compare peak RSS before and after streaming.

#286 Container health sampling re-parses config.toml and spawns docker ps -a every 5s

  • Impact low, effort S, verdict partly, evidence proven-by-code, area plugin-git-containers, category subprocess
  • Where: src/containers/mod.rs:49, src/containers/mod.rs:62, src/containers/runtime.rs:822, src/server/status_poll.rs:388
  • Frequency: Every 5s while any sandboxed non-trashed session exists, idle or not.
  • Problem: batch_container_health calls get_container_runtime(), which does Config::load (read and TOML parse config.toml and state.toml), then spawns docker ps -a --filter name=aoe-sandbox- via run_with_timeout, which creates two temp files per call. Runtime kind rarely changes.
  • Fix: Cache ContainerRuntime in the maintenance loop (reload on config change signal or every 60s) and pass it to a batch_container_health_with(runtime). Longer term replace the poll with docker events --filter type=container as a long-lived child.
  • Verifier: 5s gate and docker ps spawn are real (status_poll.rs:388), and get_container_runtime() does Config::load per call. But sampling is skipped when no sandboxed candidates and the sample runs in spawn_blocking. Cost is one config read plus one subprocess per 5s; caching the runtime is a small win.
  • Measure: Count execs via dtruss/strace -f -e execve on the daemon with sandboxed sessions idle for 60s; time Config::load.

#287 Agent integration config freshness stats 3 to 6 files per session per status tick

  • Impact low, effort S, verdict partly, evidence proven-by-code, area plugin-git-containers, category disk-io
  • Where: src/plugin/agent_integration.rs:597, src/plugin/agent_integration.rs:635, src/plugin/agent_integration.rs:687, src/plugin/agent_integration.rs:758
  • Frequency: Per integration-claimed session per status poll tick (0.5s to 2s), via owned_status and configured_for. Scales with sessions using a plugin-provided agent integration.
  • Problem: effective_config caches parsed Config correctly, but each call recomputes config_stamps: symlink_metadata plus metadata on global config, state.toml and profile config.toml, and resolves get_profile_dir_path, for every session every tick, even when nothing changed. owned_status also reads the report file with a pid liveness check per session.
  • Fix: Hoist the stamp check out of the per-session path: compute config_stamps once per poll tick (or at most once per second) keyed by profile, via a small TTL memo in effective_config.
  • Verifier: effective_config already caches parsed Config (agent_integration.rs:635-690); remaining cost is 3 stamps (about 6 stat syscalls) per call, gated by eligible() and active plugin claim first. Only integration-claimed sessions pay. Microseconds per session; TTL memo risks stale config invalidation the stamp design avoids.
  • Measure: Run perf/dtruss counting stat calls per status tick with 50 integration-claimed sessions; time effective_config in a criterion microbench.

#288 Sound playback spawns an OS thread plus player process per transition, unbounded, with fs scans on the TUI thread

  • Impact low, effort S, verdict partly, evidence proven-by-code, area plugin-git-containers, category subprocess
  • Where: src/sound/playback.rs:93, src/sound/playback.rs:101, src/sound/mod.rs:13, src/sound/discovery.rs:11, src/tui/home/status.rs:658
  • Frequency: Per status transition with sounds enabled; bursts when many sessions flip together (startup, mass resume).
  • Problem: play_for_transition runs on the TUI thread: it does read_dir and sort of the sounds dir for random selection, a stat in find_sound_file, then std::thread::spawn plus afplay/aplay, and on Linux which::which PATH scans each play. There is no cap or coalescing, so 20 simultaneous transitions start 20 players.
  • Fix: Cache list_available_sounds and the resolved player in a OnceLock/short TTL. Coalesce transitions within about 250ms into one sound and cap concurrent players at 1 or 2 through a single long-lived player thread fed by a bounded channel.
  • Verifier: Claims hold: read_dir+sort, stat, thread spawn and which::which per play, no cap. But cost is microseconds on a small sounds dir, gated by sounds being enabled, and runs on status change only. Real issue is overlapping audio, not CPU. Coalescing is a UX fix.
  • Measure: Time play_for_transition with 20 transitions and a 10-file sounds dir via a criterion bench or Instant logging; expect under 1ms each.

4.sweep-async-blocking

#289 Every streamed ACP event goes through tokio block_in_place to take an uncontended seq mutex

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-async-blocking, category cpu
  • Where: src/acp/supervisor/drain.rs:197-330, src/acp/supervisor/mod.rs:889-901, src/acp/supervisor/sink.rs:189-207, src/acp/supervisor/sink.rs:360-366, src/acp/supervisor/sink.rs:266-276
  • Frequency: Once per worker event in pump(), meaning every AgentMessageChunk, tool update and so on. This is tens to hundreds per second for each actively streaming session.
  • Problem: publish_with_next_seq wraps the seq-counter lock and publish_from_worker in blocking_io, which calls block_in_place. Each call hands the worker core to another thread and later reclaims it. The guarded work is a std Mutex lock plus a non-blocking try_send on a 4096-slot channel. It only blocks when the queue is full, and submit() already wraps that path in its own blocking_io.
  • Fix: In publish_with_next_seq, try counter.try_lock() first and call publish inline when the lock is free. Fall back to blocking_io only when try_lock fails. submit() already calls block_in_place for the TrySendError::Full case, so the holder still leaves the async worker before it can block.
  • Verifier: Confirmed that pump calls publish_with_next_seq, and so block_in_place, once per event (drain.rs:323). The guarded publish_from_worker only does try_send. block_in_place costs microseconds, so at hundreds of events/s the CPU win is small. The try_lock fast path is safe because submit and record_attachment already use blocking_io.
  • Measure: Run perf or Instruments on the daemon while 5 sessions stream; measure the share of samples in block_in_place and worker handoff.

#290 ACP config-option handler rewrites sessions.json synchronously on the runtime, twice for a model pick

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area sweep-async-blocking, category latency
  • Where: src/server/api/acp/config.rs:98-133, src/server/api/acp/config.rs:243-276, src/session/storage.rs:2462-2560
  • Frequency: Per model, mode or effort change from the web UI or MCP. A model pick sends both a persist_selector and an acp_model_config persist.
  • Problem: persist_with calls Storage::new(..).update(..) directly in the async fn. update takes the process-wide std Mutex save_lock and a blocking flock that the TUI and CLI processes share, then reads, rewrites and saves the whole sessions.json. Under flock contention it stalls a tokio worker for the full wait. It also holds disk_mutation_guard, which blocks disk reloads. A model pick does this twice.
  • Fix: Wrap the update in tokio::task::spawn_blocking, as acp_reconciler/idle.rs:137-151 persist_dormant does. Merge the selector and acp_model_config mutations into one persist_with closure so a model pick does one storage transaction.
  • Verifier: persist_with (config.rs:107-133) runs Storage::update (save_lock plus cross-process flock plus full sessions.json rewrite) inline on the async worker. A model pick runs it twice (lines 244 and 263). It only triggers on a user click, so the stall is user-paced. It matters only under flock contention with the TUI or CLI.
  • Measure: Time each persist_with call with tracing elapsed during a model pick while the TUI saves concurrently, for example a loop of aoe CLI session edits.

#291 Synchronous EventStore reads in HTTP handlers and the serial ACP event listener

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-async-blocking, category latency
  • Where: src/server/api/acp/history.rs:337-346, src/server/api/acp/history.rs:420-480, src/server/api/acp/prompt.rs:630-638, src/server/api/queue.rs:181-190, src/acp/event_store/attachments.rs:41-46, src/acp/event_store/attachments.rs:96-98, src/server/acp_events.rs:365-370, src/acp/event_store/turns.rs:195-215
  • Frequency: Per transcript open or page (up to 2000 events), per context-primer request (whole history), per attachment GET, per queued prompt with attachments, and once per session first turn in the single acp_event_listener task.
  • Problem: These async fns call rusqlite directly on tokio workers. acp_replay decodes and folds up to MAX_REPLAY_PAGE=2000 events inline. replay_before loads the whole pre-seq history. load_attachment, pending_attachment_bytes and first_turn_context use self.conn(), the writer mutex, so a blob read or a full-history scan stalls event persistence. first_turn_context also blocks the serial broadcast listener.
  • Fix: Wrap each handler's store call and decode or fold in spawn_blocking, following query_store in acp_reconciler/mod.rs:161. Switch load_attachment, pending_attachment_bytes, load_pending_attachments_for_ref and first_turn_context from self.conn() to self.reader(). In acp_events.rs, move the first_turn_context call into the spawned smart-rename task.
  • Verifier: Real but overstated. replay_page, replay_page_before, replay_before and retained_page already use the pooled read connections, not the writer, so transcript paging cannot stall persistence. They do run inline on tokio workers (2000-event decode and fold). Writer-mutex use holds for load_attachment, pending attachment reads and first_turn_context. first_turn_context runs once per session, streams, and stops at the first Stopped.
  • Measure: Add tracing spans with elapsed time around acp_replay(view=rows, limit=2000) and load_attachment on a large session. Count tokio worker busy time with tokio-console.

#292 Global instances write lock held across spawn_blocking sessions.json writes during reload

  • Impact low, effort M, verdict partly, evidence proven-by-code, area sweep-async-blocking, category concurrency
  • Where: src/server/reload.rs:1324-1414, src/server/status_poll.rs:85-140, src/server/structured_repair.rs:120-130
  • Frequency: Each status-poll tick (500ms with subscribers, 2s otherwise) and disk-watch reload that carries passive transitions (terminal Running/Idle changes) or structured repairs. Scales with active terminal sessions and profile count.
  • Problem: reload_state_instances_from_disk takes publication.write() and instances.write(). While holding both, it awaits persist_structured_row_repairs and flush_passive_transition_writes, which run a flocked sessions.json read-modify-write per profile in sequence. Every API read of instances and every publish waits for that disk I/O. That includes contention with the TUI's flock.
  • Fix: Run the flush and repair writes while holding only publication.write() and the reload guard. Then take instances.write() just for the mutation_epoch check and merge_loaded_rows. The patches are already generation-guarded in merge_passive_status_patch, so a stale epoch only drops the in-memory merge.
  • Verifier: Both write guards are held across flush/repair spawn_blocking (reload.rs:1324-1414), but only when a transition exists (passive changes or repairs), not every tick. Narrowing instances.write() risks dropping in-memory merges after durable writes. Writes are small per-profile flocked RMW.
  • Measure: Log hold time of instances.write() in reload_state_instances_from_disk when transition is Some; compare with API read latency during status flips.

#293 Live terminal WebSocket setup runs tmux subprocesses and config reads on the runtime

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-async-blocking, category latency
  • Where: src/server/live_ws.rs:766-773, src/server/live_ws.rs:1024-1027, src/server/live_ws.rs:1056-1062, src/tmux/vt.rs:3419-3455, src/tmux/mod.rs:1302-1308, src/server/pane.rs:664-665, src/server/pane.rs:723-724
  • Frequency: Per live terminal or pane WebSocket connect and reconnect, and per paired or container pane open.
  • Problem: live_terminal_ws calls Session::resolve_name under instances.read(). On a stale snapshot it runs refresh_session_cache, which spawns tmux list-sessions synchronously. handle_live_ws_inner calls Config::load_or_warn and Osc52Channel::acquire inline. acquire takes std mutexes and runs tmux pipe-pane and capability probes plus fs ops. The VtChannel acquire next to it already uses spawn_blocking.
  • Fix: Use resolve_name_for_display (snapshot-only) in live_terminal_ws, or resolve after dropping the lock inside spawn_blocking. Move Config::load_or_warn and Osc52Channel::acquire into the same spawn_blocking that runs VtChannel::acquire_with_deadline (live_ws.rs:1031-1037). Do the same for resolve_name_indexed in pane.rs.
  • Verifier: Real inline blocking: resolve_name refreshes list-sessions only on a cache miss, with a timeout. Osc52Channel::acquire and Config::load_or_warn run inline, once per connect. resolve_name_for_display would return derived names for renamed sessions, so it is unsafe. Rare per-connect cost.
  • Measure: Time live_terminal_ws and handle_live_ws_inner setup with tracing spans during reconnect storms; count refresh_session_cache calls from them.

#294 Maintenance tick reads the worker registry and restart markers synchronously on the runtime

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-async-blocking, category disk-io
  • Where: src/server/acp_reconciler/mod.rs:642-685, src/server/acp_reconciler/mod.rs:606-622, src/server/acp_reconciler/mod.rs:311-322, src/process/worker_registry.rs:458-486, src/process/worker_registry.rs:598-608, src/acp/supervisor/teardown.rs:1043-1053
  • Frequency: Every maintenance_loop tick (2s). Scales with worker-record count and with the size of the attempted set.
  • Problem: sweep_orphan_workers calls worker_registry::list(), which runs read_dir and reads and parses every worker JSON, inside the async fn. readopt_orphan_runners calls worker_registry::load and is_record_live (process birth probe, socket stat) for each attempted session. The resume pass calls take_late_restart_marker (fs claim plus load) for each attempted session. All of this is synchronous on a tokio worker every 2s.
  • Fix: Collect the ids first. Then run list(), the per-id load and is_record_live checks, and the restart-marker claims in one spawn_blocking per tick, returning plain Vecs. Keep the async is_owned checks outside it.
  • Verifier: Sync fs in async fn is real (list() read_dir plus JSON parse, load, is_record_live per attempted id) every 2s tick. But the worker record count is small and files are tiny on local disk. The sweep also holds an instances read lock only briefly. Hygiene fix, not a measurable win.
  • Measure: Wrap maintenance tick phases in Instant timers with 50 and 200 worker records; check tokio-console or runtime poll-time warnings.

#295 Log sinks write synchronously per line on the emitting thread; the session tee formats every event before filtering

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-async-blocking, category cpu
  • Where: src/logging.rs:580-606, src/logging.rs:731-743, src/logging.rs:822-853, src/acp/session_tee.rs:118-140, src/main.rs:198-211
  • Frequency: Per tracing event that passes the filter (info by default for serve, much more with acp_trace or debug), on whichever tokio worker emits it.
  • Problem: The file sink is a std Mutex around an unbuffered SizeRotatingWriter that calls write_all on the File for each line, a syscall under a process-wide lock on async threads. SessionTeeLayer::on_event records every field into an owned-String visitor before it knows whether a session applies. It then does a second write plus flush syscall for each session event.
  • Fix: Wrap the file writer in tracing_appender::non_blocking (or a BufWriter flushed on a timer) so workers only enqueue. In SessionTeeLayer::on_event, resolve the session first: try session_from_scope, or use a cheap visitor that captures only the session field. Run the full LineVisitor only when a session is found, and drop the per-line flush.
  • Verifier: Unbuffered write_all per line under a Mutex is true. But the tee's per-line flush is a no-op on std File, so there is no second syscall. The visitor is needed anyway to find the session field. non_blocking would risk losing the final lines on crash.
  • Measure: strace -c -f -e write on aoe serve under acp_trace load, or criterion bench of SessionTeeLayer::on_event with and without session fields.

4.sweep-timers-polling

#296 Every session-status WS connection re-runs a full runtime publish for each status change

  • Impact low, effort M, verdict partly, evidence proven-by-code, area sweep-timers-polling, category cpu
  • Where: src/server/session_status_ws.rs:207, src/server/runtime.rs:278, src/server/api/sessions/list.rs:40
  • Frequency: Each status change, once per connected status WS. Every open dashboard tab holds one.
  • Problem: In serve(), Next::Change calls state.runtime.publish() for each connection. publish() runs project_sessions: up to 4 SQLite lookups per structured session (latest_plan, latest_pending_wakeup, latest_active_monitor, pending_approval_requests), a read and parse of ~/.claude/settings.json, and profile config resolves, all serialized on publish_lane. With K tabs and a burst of M changes, that is K*M full projections, and the status poll publishes the same state again.
  • Fix: Do not publish from session_status_ws. Make the status_tx producer (reload_state_instances_from_disk / status_poll_loop) publish once before it broadcasts. Or have serve() wait on runtime.snapshots until mutation_epoch or revision covers the change, then call frame_for with that borrowed snapshot.
  • Verifier: Confirmed: serve() calls runtime.publish per connection per change (session_status_ws.rs:213). This exists to keep a documented invariant (module doc lines 5-6): a frame must follow a publication that began after the move. reload.rs:1424 broadcasts before status_poll publishes (status_poll.rs:624). The fix must keep that order. K tabs and M changes are small, and the epoch dedup does not skip the projection.
  • Measure: Add a tracing span with a counter around publish() keyed by caller. Open 3 dashboard tabs, flip 10 sessions, and compare project_sessions call counts.

#297 Status poll spawns two tmux processes per tick where one list-panes would do

  • Impact low, effort M, verdict partly, evidence proven-by-code, area sweep-timers-polling, category subprocess
  • Where: src/server/status_poll.rs:474, src/tmux/mod.rs:744, src/tmux/mod.rs:1434, src/tmux/tool_session.rs:122
  • Frequency: Every 2s with no subscribers (500ms with subscribers), forever, even with zero tmux-backed sessions.
  • Problem: Each tick runs refresh_session_cache (tmux list-sessions), batch_pane_metadata (tmux list-panes -a), and pending_retirement_targets, which opens and locks the retirement journal file. list-panes -a already returns session_name and session_id, so the separate list-sessions call is redundant. When no instance is tmux-backed, the work produces nothing.
  • Fix: Derive the session cache from the batch_pane_metadata output and drop the list-sessions call from the tick. Skip the tmux and journal work entirely when no loaded instance or auxiliary needs pane observation.
  • Verifier: Two spawns per tick are real (status_poll.rs:512-513). The list-sessions scan also carries session_activity and show-options subtraction of the inherited @aoe_kind scopes (mod.rs:652-677), which list-panes does not provide. Better: chain both into one tmux invocation with ';'. That saves one fork per 2s/500ms. Skipping when nothing is tmux-backed is a minor win.
  • Measure: Time refresh_session_cache plus batch_pane_metadata with tracing duration_ms at trace level, then compare against a single chained command over 100 ticks.

#298 Background sub-agent tailer polls every 500ms with no backoff; sandboxed sessions spawn docker exec each poll

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-timers-polling, category subprocess
  • Where: src/acp/background_agent.rs:15, src/acp/background_agent.rs:48, src/acp/background_agent.rs:82, src/acp/background_agent.rs:281, src/acp/background_agent.rs:433
  • Frequency: Every 500ms per running background sub-agent, until it ends or 300s pass without growth.
  • Problem: run_tailer and run_progress_tailer wake every 500ms. For TranscriptSource::Container, each wake runs docker exec test -e and/or docker exec tail -c, so 2-4 container execs per second per sub-agent. A stalled agent keeps that rate for 5 minutes. Host sources reopen and seek the file each poll, while task_transcript.rs already uses FileWatchService.
  • Fix: For TranscriptSource::Host, subscribe with FileWatchService (WATCH_DEBOUNCE, SAFETY_REREAD) the same way task_transcript does. For Container, back off the poll from 500ms to 5s while the transcript is not growing, and reset on growth.
  • Verifier: run_tailer runs docker exec test -e every 500ms only until the file appears. After that it runs one docker exec tail -c per 500ms, so about 2 execs/s, not 2-4. run_progress_tailer is Host-only. A Host open+seek every 500ms is trivial, so FileWatchService is overkill. The only worthwhile fix is idle backoff for Container. Background sub-agents are few and short-lived.
  • Measure: In a sandboxed session with one background sub-agent, count docker exec processes per minute with execsnoop or ps sampling, before and after the backoff.

#299 TUI redraws every 120ms whenever any session is Running or Waiting, faster than the spinners change

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area sweep-timers-polling, category render
  • Where: src/tui/app.rs:692, src/tui/app.rs:1497, src/tui/home/rows.rs:136, src/tui/home/render.rs:408, src/tui/home/render.rs:415
  • Frequency: About 8 full draws per second while any session is Running, Waiting, Starting or Creating, which is most of the time. Draw cost scales with the visible row count.
  • Problem: SPINNER_REDRAW_INTERVAL is fixed at 120ms (sized for the 180ms Starting breathe). Running frames change every 220ms and Waiting every 400ms, so most redraws reproduce the same glyphs. Waiting can last for hours. The 33ms refresh_interval also wakes the loop 30 times a second unconditionally and runs about 30 poll helpers per wake.
  • Fix: In has_animated_sessions, return the minimum interval among the present statuses, or compute the next frame boundary from the session_offset of the visible animated rows, and sleep_until it. Raise the base refresh_interval when nothing is pending, such as no live_send and no structured_preview.
  • Verifier: The 120ms cadence and has_animated_sessions (rows.rs:136, which checks all instances, not visible ones) are as described. But spinners use per-session offsets, so several Running sessions change frames at staggered times, and Starting needs 180ms. Ratatui diffs cells, so the terminal sees few writes. The waste is only widget building, likely about 1ms per draw.
  • Measure: Add a tracing span around self.draw(terminal) and log frame time and draws/sec with 30 sessions, 5 of them Running, using AGENT_OF_EMPIRES_DEBUG=1.

#300 TUI 5s heartbeat re-applies an unchanged snapshot, re-reads config, and forces a full redraw

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area sweep-timers-polling, category cpu
  • Where: src/tui/app.rs:1419, src/tui/app.rs:1426, src/tui/home/lifecycle.rs:455, src/tui/home/lifecycle.rs:473
  • Frequency: Every 5s while the TUI is open, including when its terminal is in the background.
  • Problem: On DiskRefreshDecision::FullHeartbeat, home.reload() runs apply_canonical_projection on the already-applied session_feed snapshot even when its cursor is unchanged. resolve_config(profile) then reads the config from disk to recompute mouse capture, and needs_full_refresh forces a draw. Config changes already arrive through config_watch.dirty.
  • Fix: In reload_storage_only, skip apply_canonical_projection when snapshot.cursor equals the last applied cursor. Move the mouse-capture resolve_config into the config_watch dirty branch. Set needs_full_refresh only when the projection actually changed.
  • Verifier: Real cost is larger than claimed: the heartbeat passes refresh_metadata=true, so status.rs:489 reloads and parses each profile's sessions file and runs duplicate_reports every 5s. But that refresh is intentional, so skipping on equal cursor breaks it; gate on file mtime instead. resolve_config read is minor.
  • Measure: Wrap the FullHeartbeat arm in app.rs:1425 with Instant timing under tracing; run with 200 sessions and log p50 and p99.

#301 write_tui_activity does synchronous create_dir_all and fs::write on every key press

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area sweep-timers-polling, category disk-io
  • Where: src/tui/app.rs:772, src/session/mod.rs:1168
  • Frequency: Every key press in the TUI, including fast typing in live-send.
  • Problem: The activity file only needs to be fresh within the 30s threshold that is_tui_active checks. The TUI rewrites it on every keystroke, with a directory create, on the render thread.
  • Fix: Keep a last_activity_write Instant in App and call write_tui_activity at most once every 5s. Create the directory once at startup instead of in each call.
  • Verifier: app.rs:772 calls write_tui_activity on every key press; each does create_dir_all plus open/truncate/close of an empty file. Cost is tens of microseconds, bounded by typing rate. The 30s freshness threshold makes a 5s throttle safe. Tiny win.
  • Measure: strace -c -e trace=mkdir,openat,write on the TUI while pasting or typing 1000 keys; count syscalls and total time.

#302 Web dashboard polls /api/sessions every 3s even in hidden tabs, despite the status push stream

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-timers-polling, category network
  • Where: web/src/hooks/useSessions.ts:12, web/src/hooks/useSessions.ts:256, web/src/hooks/useSessionStatusStream.ts:20
  • Frequency: Every 3s per open dashboard tab, forever, plus syncTrash each tick once trash has been viewed.
  • Problem: The tick and scheduleNext chain ignores document.visibilityState. The ETag makes unchanged responses 304s, but each poll still costs a request, auth middleware, and a JSON parse and setState on 200s. Status moves already arrive through /api/sessions/status/ws, and its resync frame triggers refresh().
  • Fix: In the polling effect, stop scheduleNext while document.hidden and refetch on visibilitychange. While the status WS is connected, stretch POLL_INTERVAL to about 15-30s, because pushed moves plus resync cover freshness.
  • Verifier: The poll loop (useSessions.ts:257) ignores visibility, and useSystemHealth already shows the pattern for pausing. But useSessionStatusStream says the polled list stays authoritative for everything except status, so stretching to 15-30s while the WS is connected would delay titles and other fields. Browsers already throttle timers in hidden tabs. ETag returns 304s.
  • Measure: In Chrome DevTools Network, count /api/sessions requests over 10 minutes with the tab hidden, before and after adding a visibilitychange pause.

#303 Plugin UI state is polled every 3s by the web, the TUI home, and each structured view, instead of pushed

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-timers-polling, category network
  • Where: web/src/hooks/usePluginUiState.ts:5, web/src/hooks/usePluginUiState.ts:55, src/tui/plugin_ui_poller.rs:10, src/tui/structured_view/mod.rs:51, src/tui/structured_view/mod.rs:272, src/server/api/plugins.rs:355
  • Frequency: Every 3s per web tab (500ms during a 15s boost), per TUI home with sessions, and per open structured view (2 requests: ui-state plus commands).
  • Problem: Each poll makes the daemon serialize the full plugin UI snapshot to bytes and hash it for the ETag, even when nothing changed. The web poll has no visibility gating. The structured view also refetches plugin_commands every 3s.
  • Fix: Have plugin_host bump a revision and send it on the status WS (web) and the runtime/session feed (TUI). Fetch /api/plugins/ui-state only when the revision changes. Until then, pause the web loop while document.hidden and fetch plugin_commands once per view.
  • Verifier: Polling is real (web 3s, no visibility gating in usePluginUiState.ts; TUI poller and structured view every 3s with commands refetch). But the response is small and already ETag/304. A revision push is M effort for little; web document.hidden pause is the cheap, worthwhile part.
  • Measure: Count GET /api/plugins/ui-state per minute in daemon access log with a hidden browser tab, one TUI and 3 structured views open.

#304 StatusGlyph starts one setInterval per animated row

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-timers-polling, category render
  • Where: web/src/components/StatusGlyph.tsx:66, web/src/components/StatusGlyph.tsx:72
  • Frequency: Per Running, Waiting or fresh-Idle glyph rendered (sidebar, Dashboard, palette), at 180-400ms each.
  • Problem: N animated sessions create N independent timers, so 30 Running rows cause about 136 setState calls and React commits per second. Each timer keeps the main thread waking, and rows in collapsed groups or hidden surfaces still animate.
  • Fix: Replace the per-glyph interval with a shared module-level ticker per rattle interval (a useSyncExternalStore subscription to one setInterval, paused on document.hidden). Or render the frames with a CSS steps() animation driven by the epoch offset.
  • Verifier: Claim holds: StatusGlyph.tsx:66-72 sets one setInterval per animated glyph, and frames always change so every tick commits. But each commit renders a one-character component, animate=false covers reduced motion, and browsers throttle hidden-tab timers. Real cost is small; a shared ticker is safe.
  • Measure: Chrome Performance profile with 30 Running sessions for 10s; compare scripting time and commits per second with and without a shared ticker.

#305 Sandbox health sampling runs docker ps every 5s even when every sandboxed session is Stopped

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area sweep-timers-polling, category subprocess
  • Where: src/server/status_poll.rs:385, src/server/status_poll.rs:191
  • Frequency: Every 5s while any non-trashed sandboxed row exists.
  • Problem: sample_sandbox_health filters out only Starting, Creating and Deleting, so Stopped sandboxed sessions still trigger batch_container_health (one container-runtime subprocess). apply_tick_status_decision ignores health for Stopped rows, so that result is never used.
  • Fix: Add Status::Stopped to the exclusion in sample_sandbox_health's candidate filter, so candidates.is_empty() returns early.
  • Verifier: status_poll.rs:200 excludes only Starting, Creating and Deleting. reload.rs:~936 skips the health check for Stopped rows, so a Stopped-only fleet still pays batch_container_health every 5s for nothing. Fix is one line. It runs in spawn_blocking, so the real win is one docker ps per 5s.
  • Measure: Run the daemon with only Stopped sandboxed sessions and count container-runtime subprocess spawns per minute, for example with dtruss or ps sampling.

#306 Dashboard presence POSTs every 10s even when the tab is hidden

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-timers-polling, category network
  • Where: web/src/hooks/useDashboardPresence.ts:4, web/src/hooks/useDashboardPresence.ts:33
  • Frequency: Every 10s per open tab, including background tabs.
  • Problem: While the tab is hidden, update() keeps posting active=false every 10s. The server's web_watch_within(30s) expires on its own, and the visibilitychange and blur handlers already report the transition.
  • Fix: Run the interval only while isForeground() is true: start it on visibilitychange or focus to visible, and clear it on hidden or blur after the single report.
  • Verifier: Hidden tabs do re-POST active=false every 10s, which only calls set_web_presence's remove(). The cost is a tiny request, and browsers throttle background timers anyway. Visible-but-unfocused windows also POST, and the interval is a fallback if the blur report fails, so gating needs care.
  • Measure: Open a background tab for 5 minutes and count POST /api/presence in the network log or server access log.

4.sweep-alloc-serde

#307 strip_ansi is quadratic in escape count

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-alloc-serde, category cpu
  • Where: src/tmux/utils.rs:12-31, src/session/instance/status_update.rs:572, src/session/instance/pane_status.rs:15, src/session/instance/pane_status.rs:162-172
  • Frequency: Per status poll per session whenever the screen changed (poll interval 2s backing off to 60s), plus several times per poll in pane_status helpers; scales with sessions x escapes in a 50-line colored capture.
  • Problem: Each CSI/OSC found triggers result = format!(prefix, suffix), copying the whole string, and find restarts at offset 0. A capture-pane -e dump with hundreds of SGR sequences does hundreds of full-string copies and rescans. pane_status helpers call it again on the same capture.
  • Fix: Rewrite strip_ansi as one pass over bytes writing into a pre-sized String (skip ESC [ ... final-byte and ESC ] ... BEL), reusing strip_osc_st's slice approach. Strip once in the caller and pass the clean text to pane_status helpers.
  • Verifier: strip_ansi is quadratic as claimed: each escape triggers a format! copy and the search restarts at offset 0. capture_pane uses -e (session.rs:845). But the input is a capture of about 50 lines (about 10KB), and the poll is skipped when the screen is unchanged (status_update.rs:560). The tmux subprocess spawn per poll likely costs more. The pane_status helpers run on the error and dead-pane paths, not on every poll.
  • Measure: Run a criterion bench of strip_ansi on a real 50-line capture-pane -e dump of Claude Code, before and after a single-pass rewrite.

#308 Per-event SQLite transaction with duplicate index and unprepared SQL

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area sweep-alloc-serde, category disk-io
  • Where: src/acp/event_store/mod.rs:236-262, src/events/mod.rs:101-112, src/events/mod.rs:219-237, src/acp/supervisor/sink.rs:155-175
  • Frequency: Per ACP event (every chunk) on one global writer thread shared by all sessions; scales with total chunk rate across sessions.
  • Problem: record() opens a transaction and commits for each single-row insert; insert_event does format! of the SQL and conn.execute (re-prepare) each time. The table has PRIMARY KEY(session_id, seq) plus a redundant idx_*_session_seq on the same columns, doubling index writes, plus a created_at index.
  • Fix: In the writer loop in sink.rs, drain queued Publish jobs with try_recv and insert them in one transaction; use prepare_cached with a static SQL string in insert_event. Add a migration dropping idx_{events}_session_seq since the PK already covers it.
  • Verifier: The DB uses WAL with synchronous=NORMAL (events/mod.rs:92-95), so a commit per event does no fsync and costs tens of microseconds. idx_{events}_session_seq does duplicate the PK autoindex, so every insert writes one extra B-tree. Dropping it needs a migration. prepare_cached is a micro-win. prune_retention is a no-op by default because replay_events defaults to 0 (unlimited).
  • Measure: Time EventStore::record with a histogram on the acp-event-writer thread during a burst of chunks. Compare with the duplicate index dropped and prepare_cached in place.

#309 Metrics refresh clones every Instance each second even when the strip is hidden

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area sweep-alloc-serde, category memory
  • Where: src/tui/home/status.rs:8-10, src/tui/home/status.rs:18-27, src/tui/app.rs:1316-1319
  • Frequency: Once per second per TUI process; scales with session count times Instance size (many String/Vec fields).
  • Problem: request_metrics_refresh calls pollable_instances() (instances.values().cloned().collect()) before checking show_diagnostics/system_health_open/tip_candidate. The deep clone is discarded when none apply; tip_candidate needs only instances.len().
  • Fix: In request_metrics_refresh, compute the condition first using self.instances.len(), and call pollable_instances() only inside the branch that sends to metrics_poller.
  • Verifier: request_metrics_refresh runs every 1s and always calls pollable_instances() (deep clone of all Instances) before checking the gate; clone is dropped when strip hidden. Fix is trivial: use instances.len() and clone only in the send branch. Win is small CPU/alloc per second.
  • Measure: Count allocations per tick with dhat or a counter around pollable_instances with 100 sessions and diagnostics hidden.

#310 Linear scans over transcript rows per delta and per tool event

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-alloc-serde, category cpu
  • Where: src/acp/transcript.rs:937-942, src/acp/transcript.rs:1030-1054, src/acp/transcript.rs:561, src/acp/transcript.rs:610, src/tui/structured_view/reducer.rs:268-270
  • Frequency: Per transcript_delta in each TUI/web-model client and per ToolCallUpdated/Completed on the server fold; scales with row count (one row per chunk), giving O(n^2) over a long session.
  • Problem: upsert_transcript_row and patch_transcript_row do rows.iter().position(id) even for brand-new ids (full scan then push); find_tool_start scans all rows per tool event; Remove does retain over all rows. Server TranscriptModel already keeps row_ids, but the position lookup still scans.
  • Fix: Keep a HashMap<String, usize> id->index (and tool_call_id->start index) beside rows in TranscriptModel and AcpTranscript, updated in append/remove; check row_ids first to skip the scan on appends.
  • Verifier: Each chunk is its own row (msg-{seq}), so scans are real. Live per-delta scan is O(n) and dwarfed by render.rs:1530 transcript_lines rebuilding all rows per frame. The real quadratic is batch replay: http.rs:345 replay_rows_paged and reducer merge_server_rows upsert row-by-row. Fix: build a local id-index per batch like web mergeServerRows, not a persistent map.
  • Measure: Time replay_rows_paged plus merge_server_rows on a 20k-row session with tracing spans around reseed_server_rows in src/tui/structured_view/mod.rs:1919.

#311 Region text lowercased once per rule instead of once per region

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area sweep-alloc-serde, category cpu
  • Where: src/tmux/detect/manifest.rs:340-347, src/tmux/detect/manifest.rs:244-247, src/tmux/detect/manifest.rs:466-472, src/tmux/detect/region.rs:238-250
  • Frequency: Per status poll per session with a changed screen; scales with rule count (tens per manifest) times region size (up to a 50-line capture).
  • Problem: Screen::region_text memoizes region slices in OnceCell, but Rule::matches does text.to_lowercase() for every rule, and nested matchers with a region lowercase again. Overlapping rules over the same WholeRecent region each allocate and lowercase the same few KB; match_position also rebuilds window strings per line.
  • Fix: Add lowered OnceCell fields to Screen beside collapsed/unstacked and expose region_lower(region), so Rule::matches borrows both text and lower. Lowercase each rule-independent region once per poll.
  • Verifier: Real repeated to_lowercase per rule (manifest.rs:342, 245, 466-472), but regions are a few KB and polls are 2s+ per session; microseconds each. Per-line window join in match_position is the larger cost. Caching lowered region is feasible but wins little.
  • Measure: criterion bench of detect over a 50-line capture with a full manifest; compare with lowered-region cache prototype.

#312 sessions.json is parsed twice and rewritten pretty-printed on each mutation

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area sweep-alloc-serde, category disk-io
  • Where: src/session/storage.rs:2223-2232, src/session/storage.rs:2587-2597, src/session/storage.rs:2569-2576
  • Frequency: Per storage.update call and per non-Complete load (stamp change in the cached reader); scales with session count and sessions.json size.
  • Problem: Non-Complete loads deserialize the file to Vec<serde_json::Value> and then T::deserialize(&row) per row (two passes with a Value tree allocated). update_under_lock also clones groups for comparison and uses to_vec_pretty for the whole sessions file, growing bytes written with whitespace.
  • Fix: In load_rows, deserialize Vec<Box<serde_json::value::RawValue>> and parse each row once with from_str, falling back to Value only for the corrupt row. Use to_vec for sessions.json if human-readability is not a contract.
  • Verifier: Two-pass Value parse only occurs on non-Complete policy (storage.rs:2214 fast-paths Complete with direct Vec). Pretty-printing on update is real but sessions.json is small and writes are user-action driven. Pretty format may be a readability contract.
  • Measure: Time storage.update and load_rows with 200 instances using a criterion bench, pretty vs compact, Value vs RawValue.

#313 Hook status read opens the instance dir twice per poll

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-alloc-serde, category disk-io
  • Where: src/hooks/status_file.rs:46-67, src/session/instance/status_update.rs:480-484
  • Frequency: Per status poll per session (2s-60s backoff); scales with session count.
  • Problem: read_hook_status and read_hook_status_age each call open_instance_dir_read_only, then do read vs fstatat on the same file, so detect_pane_now pays two directory opens and two syscall sequences for one observation.
  • Fix: Add read_hook_status_with_age(instance_id) that opens the dir once and returns (Status, Option) from a single fstat plus read; use it where HookObservation is built.
  • Verifier: Confirmed: status_update.rs:480-484 calls read_hook_status then read_hook_status_age, each opening the instance dir (two extra openat plus read/fstatat). Per poll per session at 2s+ intervals, a few microsecond syscalls; a combined helper is easy but the win is tiny.
  • Measure: Run dtruss/strace -c on aoe daemon with 50 sessions and count openat on instance dirs per minute.

4.sweep-subprocess

#314 ACP adapter and Node version probes block tokio workers on every session spawn

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-subprocess, category subprocess
  • Where: src/acp/acp_client/runner.rs:195-262, src/acp/acp_client/resolve_command.rs:34-60, src/acp/acp_client/resolve_command.rs:164-200, src/acp/node.rs:96-150, src/acp/adapters.rs:166-170, src/acp/acp_client/spawn.rs:476-492, src/acp/acp_client/list.rs:55-58
  • Frequency: Per ACP session spawn or resume, so N times on a daemon restart. Scales with session count.
  • Problem: spawn_runner_detached is async but calls resolve_agent_command synchronously. With a PATH copy plus bundled adapter it spawns <adapter> --version (sleep-polled, up to 2s). The bundled path adds node --version (up to 5s) and runtime_too_old_for adds another. The doc comment says it is deliberately uncached. A mass resume stalls many runtime workers.
  • Fix: Run resolve_agent_command inside tokio::task::spawn_blocking in spawn_runner_detached and spawn_subprocess. Memoize path_copy_below_floor and node::resolve_for in a static map keyed by (path, mtime, len). This keeps the nvm-use freshness the comment wants, since the key changes with the binary.
  • Verifier: Blocking is real: spawn_runner_detached (runner.rs:266) and spawn_subprocess call resolve_agent_command inline, with sleep-polled probes and an uncached node::resolve_for that runs twice on the bundled path. Frequency is overstated: runners outlive the daemon, so a restart does not respawn them. The fix is spawn_blocking only. Skip the memo cache.
  • Measure: Wrap resolve_agent_command in a tracing span and log elapsed_ms per spawn while creating 10 ACP sessions concurrently with a bundled adapter installed.

#315 Agents without a detection manifest capture the pane every tick with no skip

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-subprocess, category subprocess
  • Where: src/session/instance/status_update.rs:356, src/session/instance/status_update.rs:476-560, src/tmux/detect/manifests
  • Frequency: Every status tick per session on a hand-written detector (kiro, prime-agent, custom or alias tools) that has no hook file.
  • Problem: Only update_status_from_manifest uses skip_capture (window_activity unchanged). The legacy branch calls session.capture_pane(50) unconditionally, so an idle session still costs two forks every 2s (500ms with subscribers).
  • Fix: Apply the existing skip_capture(activity, self.detection.activity, captured_at, ...) gate to the legacy branch. Store activity and captured_at in self.detection after the legacy capture, and skip when the hook is absent and the activity timestamp is unchanged.
  • Verifier: The legacy branch (status_update.rs:365) captures on every tick when no fresh hook exists. Only niche agents lack manifests (kiro, kimi, prime-agent, custom). For prime-agent the gate is unsafe: it uses prime_live_status, which is PID-based. The shell_stale check also reads metadata, not screen content. So gate only the non-prime path.
  • Measure: Run 5 idle kiro sessions and count tmux capture-pane execs per minute with dtrace or execsnoop.

#316 Every tmux spawn carries pre_exec, which forces fork+exec instead of posix_spawn

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-subprocess, category subprocess
  • Where: src/tmux/mod.rs:209-229, src/tmux/mod.rs:278-289, src/process/mod.rs:864-877, src/process/macos.rs:178-191
  • Frequency: Every tmux invocation: at least 2 per status tick, plus per-session captures, TUI snapshot poller (1s), web live fallbacks.
  • Problem: tmux_command() always installs reset_signals_on_exec via pre_exec. Rust std then cannot use posix_spawn and falls back to fork+exec of the whole multi-threaded daemon. The comment says the reset is only needed because the TUI ignores SIGINT/SIGQUIT during attach; aoe serve never does. throttle_child on macOS has the same effect for git.
  • Fix: Install reset_signals_on_exec only on attach/switch-client commands, or only when sigaction currently reports SIG_IGN for SIGINT or SIGQUIT in this process. Keep tmux_command() pre_exec-free by default so std can use posix_spawn.
  • Verifier: tmux_command always installs pre_exec (mod.rs:223), and std skips posix_spawn when closures exist. Only the TUI attach path sets SIG_IGN (tui/app.rs:189); the daemon never does. throttle_child is opt-in for throttled git deletes only, so that part is overstated. The win is about 1 to 3 ms per fork.
  • Measure: Microbench: 1000 spawns of tmux -V with and without pre_exec from a process holding 300MB RSS, comparing wall time.

#317 run_with_timeout creates two temp files per spawn and polls with up to 25ms sleeps

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-subprocess, category latency
  • Where: src/process/mod.rs:737-830, src/process/mod.rs:647-720, src/process/mod.rs:309, src/tmux/mod.rs:482-500
  • Frequency: Every tmux query routed through TmuxCommandDeadline or run_tmux_command_with_timeout, every docker/git timed probe, and every macOS ps census.
  • Problem: Each call makes two NamedTempFile (create, reopen, unlink on drop) and then polls try_wait with sleeps 1,2,4,8,16,25ms. A 10-30ms command is only noticed on the next poll boundary. The daemon tick serializes many of these, adding several ms per command, plus tmpdir filesystem churn.
  • Fix: For short bounded commands, use piped stdout/stderr read on a helper thread and wait on a channel with recv_timeout, or cap the poll at 2ms for the first 50ms. Keep the temp-file variant only for the grandchild-holds-pipe case, i.e. the process-group variants.
  • Verifier: Poll backoff is 1,2,4,8,16,25ms (mod.rs:705), so exits are seen at cumulative 1,3,7,15,31,56ms. A 20ms command waits about 11ms extra, a 35ms command about 21ms. Temp files cost microseconds. The doc comment says files exist on purpose for inherited writers, so keep them. Changing only the poll schedule is a one-line fix.
  • Measure: Add tracing around run_with_timeout_inner that logs spawn-to-detect minus the child exit time. Run 200 tmux display-message calls and compare the 1ms-poll and current schedules.

#318 apply_status_bar runs about 9 sequential tmux set-option forks per call

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-subprocess, category subprocess
  • Where: src/tmux/status_bar.rs:25-77, src/tmux/status_bar.rs:117-134, src/tmux/status_bar.rs:165-215, src/session/instance/start.rs:1167, src/session/instance/tmux_session.rs:142, src/session/instance/terminal.rs:255
  • Frequency: Per session start, restart, daemon recovery of each missing session, and per paired or container terminal open. Scales with the number of sessions started or recovered.
  • Problem: set_session_option forks tmux once per option: status, @aoe_title, @aoe_branch, @aoe_sandbox, status-right, status-right-length, status-style, status-left, status-left-length, then mouse. The unset path forks 6 more times. Recovering N sessions costs about 10N forks, while creation already chains options with ; in utils.rs.
  • Fix: Build one tmux set-option -t =name: k v ; set-option ... argument vector in apply_status_bar and apply_all_tmux_options, reusing chain_set_option from src/tmux/utils.rs, and run it once. Do the same for the 7 set_session_option_unset calls.
  • Verifier: Confirmed: status_bar.rs makes 9 or 10 separate run_tmux_command_with_timeout forks, and the unset path makes 7 forks with .output(). This happens only at start, recovery or terminal open. Chaining needs care: a title argument ending in ';' would split the list unless escaped. A failing option would also abort the rest of the list, where today each failure is ignored on its own.
  • Measure: Time apply_all_tmux_options with Instant around the call during daemon recovery of 20 sessions, then compare against one chained set-option command.

#319 macOS settlement loop forks ps -A every 25ms per stopping session

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area sweep-subprocess, category subprocess
  • Where: src/process/mod.rs:388-440, src/process/macos.rs:291-317, src/process/macos.rs:702-735, src/process/macos.rs:814-835, src/process/macos.rs:192-230, src/process/worker_registry.rs:262-275, src/process/mod.rs:1382-1470
  • Frequency: During each ACP or runner teardown on macOS, up to grace+5s at 25ms polls, so up to about 40 full process-table dumps per second per stopping session. recover_worker and RunnerProcessGuard::executing also call it.
  • Problem: settle_with_signal polls settled() each WAIT_POLL_INTERVAL. On macOS this calls runner_group_executing, which forks ps -A -o pid=,pgid=,stat= over the whole table (about 30-60ms, longer than the poll interval). Linux avoids this. Native libproc is already used (process_executing, audit_token). Stopping many sessions at once multiplies the dumps.
  • Fix: On macOS implement runner_group_executing, runner_group_identities and build_children_map with libc proc_listpids/proc_listpgrppids plus proc_pidinfo, which macos.rs already uses at lines 750-770. Alternatively first test killpg(group,0) ESRCH, as is_process_group_alive does, and only fall back to ps when the group still exists.
  • Verifier: Confirmed that macos.rs:291 forks ps -A on each settled()/executing() poll, and RunnerProcessGuard::executing can also fork ps through refresh. This only runs during teardown or recovery, not steady state. Each ps takes longer than the 25ms sleep, so the real rate is about 10 to 15 per second, not 40. A killpg ESRCH fast path may never trigger while the unreaped zombie leader holds the group.
  • Measure: On macOS, stop 10 ACP sessions at once while running sudo dtrace -n 'proc:::exec-success /execname=="ps"/{@=count()}' to count ps execs per teardown.

#320 macOS diagnostics sampler forks about 8 processes per second

  • Impact low, effort M, verdict partly, evidence proven-by-code, area sweep-subprocess, category subprocess
  • Where: src/process/macos.rs:1104-1163, src/process/macos.rs:1228-1247, src/process/metrics.rs:200-225, src/tui/app.rs:690, src/tui/app.rs:1323, src/tui/home/status.rs:22-33
  • Frequency: Every 1s while the diagnostics strip or System Health is open, or until the 6+ agent tip is earned (3 samples). Scales with process table size.
  • Problem: Each sample runs sysctl hw.memsize, kern.memorystatus_vm_pressure_level, vm.loadavg and vm.swapusage as separate forks, plus vm_stat, ps -A -o %cpu=, ps -axo pid,ppid,rss,time,lstart, and a batch_pane_metadata list-panes. The %cpu sum duplicates what the second ps already returns as cpu time. A tmux list-panes duplicates the snapshot poller's.
  • Fix: Use libc::sysctlbyname (already used for kern.bootsessionuuid at macos.rs:1325), libc::getloadavg and host_statistics64 for memory. Drop the ps -A %cpu call and derive host CPU from process_snapshot deltas or host_processor_info. Replace batch_pane_metadata in MetricsSampler::sample with refresh_pane_meta_cache or the cached Arc.
  • Verifier: Real: sample_memory plus sample_system fork 4 sysctl, vm_stat, ps, plus a second ps and list-panes per sample, on a background thread. TUI only, macOS only, and only while the strip is open or the tip is pending. Dropping ps -A %cpu is the easy win.
  • Measure: Run sudo fs_usage -w -f exec or dtruss -f against the TUI with the diagnostics strip open for 10s and count forks per second.

#321 Agent availability probe spawns which per agent and a login shell on every TTL expiry

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-subprocess, category subprocess
  • Where: src/tmux/mod.rs:2813-2840, src/tmux/mod.rs:3160-3186, src/tmux/mod.rs:3330-3385, src/tmux/mod.rs:3405-3430, src/server/api/system.rs:291, src/server/api/setup.rs:165-180
  • Frequency: Per /api/agents, /api/setup and TUI detection call once the 60s AGENT_AVAILABILITY_TTL has expired. Costs scale with the built-in agent count (about 17) and the shell's rc weight.
  • Problem: agent_available_direct and is_binary_on_path fork the which binary per agent, sequentially. The code already uses the in-process which::which crate in the startup snapshot and plugin paths. Every missing agent then forces a $SHELL -lc login shell (timeout 15s), re-run each time the 60s negative cache expires, blocking the request.
  • Fix: Replace Command::new("which") with which::which in agent_available_direct and is_binary_on_path. Raise the negative TTL to several minutes, or run the login-shell probe only on explicit Recheck or force=true, using agent_availability_snapshot otherwise.
  • Verifier: Fork of which per agent is real (tmux/mod.rs:3335, 3410) and which::which is already used in agent_availability_snapshot. But it is sequential only on a 60s TTL miss. Longer negative TTL would delay detection of fresh installs.
  • Measure: Time AvailableTools::detect_with_custom_agents with a cold cache and ~17 agents (some missing) under a heavy zsh rc; compare with a which::which variant.

#322 Daemon and TUI each run list-sessions and list-panes snapshots, with a third list-panes in the metrics sampler

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area sweep-subprocess, category subprocess
  • Where: src/server/status_poll.rs:468-472, src/tmux/mod.rs:722-780, src/tmux/mod.rs:1434-1450, src/tmux/mod.rs:2606-2650, src/process/metrics.rs:219, src/tui/app.rs:624
  • Frequency: Daemon tick every 2s (500ms with subscribers) runs 2 tmux forks. The TUI display poller runs 2 more every 1s even when idle. The metrics sampler adds 1 per second when diagnostics are open.
  • Problem: The daemon tick runs refresh_session_cache (list-sessions plus 3 show-options chained) and then batch_pane_metadata (list-panes -a). The list-panes output carries session_name, @aoe_kind and window_activity, enough to derive the session map. The TUI polls the same pair independently although it already receives daemon status updates.
  • Fix: In status_poll_loop call refresh_pane_meta_cache once and populate SESSION_CACHE from its result, or chain show-options ; list-panes -a into one tmux invocation like session_scan_command does. Let the TUI snapshot poller back off when the daemon is connected.
  • Verifier: Two tmux forks per tick exist (status_poll.rs:512-513), and session_scan_command is already one chained invocation. Deriving the session map from list-panes is plausible but sessions without panes and the TUI separate process complicate it. 'TUI backs off when daemon connected' is speculative.
  • Measure: Count tmux execs per minute with fs_usage -f exec | grep tmux while the daemon runs idle with 20 sessions, with and without the TUI open.

#323 Daemon startup recovery runs a per-candidate full ps -A -E and a synchronous tmux fork on the runtime thread

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-subprocess, category subprocess
  • Where: src/server/startup_recovery.rs:244-262, src/server/startup_recovery.rs:315-366, src/process/macos.rs:232-290, src/session/recovery.rs:98-120
  • Frequency: Once per daemon boot, per recovery candidate. After a reboot that is N+1 process-table dumps, each including every process's environment (MBs) on macOS.
  • Problem: The batched orphaned_agents_alive pass is good, but each cascade worker then calls batch_pane_metadata() directly on the async task, which blocks a tokio worker, and orphaned_agent_process_alive, which forks ps -A -ww -E again for one instance. Concurrency is bounded but the cost is N full dumps.
  • Fix: Wrap batch_pane_metadata in spawn_blocking in the worker. Reuse the Phase A orphan_flags result for the recheck and re-scan only for candidates whose generation changed, or share one ps result per boot window.
  • Verifier: Sync batch_pane_metadata runs on the async worker (startup_recovery.rs:315) and the per-candidate recheck calls orphaned_agents_alive again via spawn_blocking. Both are real but once per boot, concurrency-bounded, and the recheck guards against state drift. spawn_blocking wrap is a trivial fix.
  • Measure: Time the cascade after a simulated reboot with 20 candidates, logging per-worker duration of batch_pane_metadata and the ps -A -E scan.

#324 Branch list endpoint forks git for the current branch although git2 is already open

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-subprocess, category subprocess
  • Where: src/server/api/git.rs:245-258, src/git/worktree/mod.rs:444-450
  • Frequency: Per GET of the branch picker (wizard open or path change). One extra fork each time.
  • Problem: list_branches handler runs git branch --show-current via std::process::Command, while GitWorktree::get_current_branch and the list_branches helpers already read HEAD through libgit2. It also bypasses crate::git::command::run_git logging.
  • Fix: Replace the Command with crate::git::GitWorktree::get_current_branch(path).unwrap_or_default(), or read it from the repo handle opened by list_branches.
  • Verifier: The fork is real (git.rs:249) inside spawn_blocking on a user-initiated picker. Saves about 5ms. The swap is not behavior-identical: get_current_branch returns 'HEAD' on detached HEAD and errors on unborn branch, while git branch --show-current returns empty or the unborn name.
  • Measure: Time GET /api/git/branches with hyperfine or curl -w; compare handler time with and without the fork.

#325 docker status endpoint runs docker --version and docker info uncached on each request

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-subprocess, category subprocess
  • Where: src/server/api/system.rs:2175-2182, src/containers/runtime_base.rs:294-304, src/server/api/setup.rs:337-360, src/session/builder.rs:763-768
  • Frequency: Per GET /api/docker/status (each session wizard open), per /api/setup/runtimes, and twice per sandboxed session create. docker info can take hundreds of ms.
  • Problem: is_available and is_daemon_running spawn fresh processes each time. get_setup_runtimes probes three runtimes sequentially, even though its own comment notes docker info can be slow. There is no memo shared between wizard open, create preflight and the sandbox health sampler.
  • Fix: Cache the (available, daemon_running) pair per runtime in a OnceLock<Mutex<(Instant, bool)>> with a 10-30s TTL inside ContainerRuntimeBase. Run the three runtime probes in get_setup_runtimes concurrently with std::thread::scope.
  • Verifier: Uncached spawns are real, but docker_status runs in spawn_blocking only on wizard open and setup runtimes only on the Sandbox step. Create preflight does the same probes once per create. Sequential 3-runtime probe is a one-time setup cost. TTL cache adds stale-state risk after starting Docker.
  • Measure: time docker --version; docker info on a cold Docker Desktop; log latency of GET /api/docker/status via tracing.

4.sweep-memory

#326 BackgroundAgentProgress snapshots and completed background work never leave the log under default retention

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-memory, category disk-io
  • Where: src/acp/background_agent.rs:15-21, src/acp/background_agent.rs:409-425, src/acp/event_store/mod.rs:256-271, src/session/config/mod.rs:503-507, src/session/config/mod.rs:779-786
  • Frequency: One progress event every 1.5s per running sub-agent while its transcript grows. Each one carries up to 250 tool entries (MAX_TOOLS). Scales with sub-agent count and run time.
  • Problem: Every progress event stores the full tools snapshot. Only the newest one matters to folds. prune_completed_background_work runs only when max_events_per_session != 0, and the default replay_events is 0 (unlimited). So a 30-minute sub-agent leaves about 1,200 snapshots (MBs) that every WS connect, hydrate and lag rebuild re-read and re-fold.
  • Fix: In EventStore::record, in the same transaction, delete earlier BackgroundAgentProgress rows with the same $.BackgroundAgentProgress.agent_id when recording one. Do the same after BackgroundAgentCompleted. Do this regardless of the cap. has_in_flight_turn still sees the newest row's created_at.
  • Verifier: Progress is sent only when the transcript grew and at most once per 1.5s (background_agent.rs:409-425), so 1,200 per 30 min is an upper bound. Each snapshot holds up to 250 small tool structs (about 50 KB max). The pruning sweep is gated on max_events_per_session != 0 (mod.rs:263). The dedup-on-record fix is sound, but if search FTS indexes rows, deletes must keep it in sync.
  • Measure: sqlite3 on the event db: SELECT count(*), sum(length(event_json)) FROM events WHERE discriminant='BackgroundAgentProgress' GROUP BY session_id.

#327 ToolCallContent events store a full output snapshot on every update

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-memory, category disk-io
  • Where: src/acp/acp_client/update_events.rs:454-459, src/acp/acp_client/update_events.rs:525-529, src/acp/acp_client/tool_output.rs:76-92, src/acp/transcript.rs:665-678
  • Frequency: Per non-terminal tool_call_update that carries content. Depends on the adapter: once per tool for claude-agent-acp, repeatedly for adapters that stream terminal output. Scales as the square of output length per tool.
  • Problem: ACP update content replaces the previous content, and the transcript treats it that way (buffer_tool_output clears, then pushes). Each update is still persisted, broadcast and replayed as a new row with the accumulated text. Text is uncapped, unlike diffs (MAX_DIFF_TEXT_BYTES). N updates of a growing output store O(N^2) bytes, and every replay re-reads them.
  • Fix: In EventStore::record, delete earlier ToolCallContent rows with the same tool_call_id when a newer one or the ToolCallCompleted arrives (same transaction). Cap content in extract_tool_content_text with a tail-keeping limit, for example 256 KiB, following the cap_diff_text pattern.
  • Verifier: Code matches: each non-terminal update with text pushes a ToolCallContent holding the full uncapped text (update_events.rs:525-529), and the transcript replaces it (transcript.rs:665-678). The O(N^2) cost needs an adapter that streams cumulative content, and none was shown. ToolCallCompleted content is uncapped too. search.rs indexes ToolCallContent, so deletes must keep search consistent.
  • Measure: SELECT json_extract(event_json,'$.ToolCallContent.tool_call_id') id, count(*), sum(length(event_json)) FROM events WHERE discriminant='ToolCallContent' GROUP BY id ORDER BY 3 DESC LIMIT 20.

#328 AcpState background_agents, workflow_runs and subagents grow without bound in every fold

  • Impact low, effort M, verdict partly, evidence proven-by-code, area sweep-memory, category memory
  • Where: src/acp/state.rs:663-674, src/acp/state.rs:1440-1447, src/acp/state.rs:1572-1600, src/acp/state.rs:1464-1469, web/src/lib/acpTypes.ts:1477-1479
  • Frequency: Per sub-agent or workflow launch. The data lives in the daemon ControlStateCache, in each WS connection's fold and in each browser state, all for the lifetime of the session.
  • Problem: Background shells are capped (MAX_FINISHED_BACKGROUND_SHELLS=20). Ended background_agents (each with prompt, result and up to 250 tools), finished workflow_runs and subagents are never trimmed. The structs are cloned per fold_control_state call and serialized per event, so cost grows with every agent the session has ever run.
  • Fix: In AcpState::apply_event, after BackgroundAgentCompleted and close_workflow_run, keep only the newest N ended records (for example MAX_FINISHED_BACKGROUND_AGENTS=20), the same way background_shells are trimmed. Also trim idle subagents. Mirror the cap in the web reducer at acpTypes.ts:1477.
  • Verifier: Growth is real (no trim beyond MAX_FINISHED_BACKGROUND_SHELLS at state.rs:478), but tools already cap at MAX_TOOLS=250 (background_agent.rs:300). The proposed trim breaks inline Task cards: useBackgroundAgentFor finds records by toolCallId (backgroundAgentsContext.ts), and the TUI reducer reads them too. A fix would need a slimmed ended record, not deletion.
  • Measure: Log serde_json::to_vec(&state.background_agents).len() in fold_control_state for a session that ran 50+ sub-agents.

#329 Browser keeps up to 32 sessions' full transcripts in the in-memory LRU

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-memory, category memory
  • Where: web/src/hooks/acpSession/stateCache.ts:18-19, web/src/hooks/acpSession/stateCache.ts:153-170
  • Frequency: Each structured session opened in a tab stays resident until 32 newer sessions push it out. Scales with sessions opened times transcript rows.
  • Problem: STATE_CACHE_CAP=32 entries, each a full AcpState with an unbounded activity array (one row per message chunk, plus tool outputs). Users who browse many long sessions keep tens to hundreds of MB of rows in the tab, though only the mounted session renders them.
  • Fix: In lruInsert, trim each entry that is not the newest (and has no subscribers in stateListeners) to its tail window. Use the reopenState logic: keep rows from the last user boundary, at least DEFAULT_HISTORY_WINDOW, with matching oldestSeq. Replay already reloads older pages. Optionally lower STATE_CACHE_CAP to 8.
  • Verifier: lruInsert (stateCache.ts:153) keeps up to 32 full states untrimmed. reopenState drops rows only when no user boundary exists. Streamed chunks patch one row instead of adding rows, so the claimed row count is overstated. A bigger related cost: the effect at useAcpSession.ts:237 runs cacheSet, which calls persistState and JSON.stringify on the full state for every dispatch.
  • Measure: Chrome heap snapshot after opening 30 long sessions; compare retained size of stateCache Map.

#330 Each transcript delta rebuilds an id map and copies the whole activity array

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-memory, category cpu
  • Where: web/src/lib/acpTypes.ts:965-981, web/src/lib/acpTypes.ts:1001-1011, web/src/hooks/acpSession/reducer.ts:144-151, web/src/hooks/acpSession/reducer.ts:241-247
  • Frequency: Every transcript_delta (one per streamed chunk and per tool update) on each open structured view. Scales with activity length.
  • Problem: transcript_append goes through mergeServerRows, which builds a Map of every existing row id and slices the array, to add one row. transcript_patch does findIndex from the front, where the target row is usually last. pruneOptimisticRows builds a Set of all row ids. At 10k rows that is several O(n) passes and allocations per chunk, creating constant GC pressure.
  • Fix: In the reducer, handle transcript_append/patch with a tail search (findLastIndex) and a single concat or slice. Change pruneOptimisticRows to test only the incoming row ids against optimisticRows, not build a Set over all activity. Keep mergeServerRows for snapshot and replay batches.
  • Verifier: Real O(n) work per delta: mergeServerRows builds a Map and slices; patchServerRow runs findIndex and slices. But pruneOptimisticRows and settleServerPrompts return early when optimisticRows is empty, the usual case. A JSON.stringify of the full state on every dispatch (useAcpSession.ts:237 calls cacheSet, then persistState) dwarfs these passes.
  • Measure: Chrome Performance profile while streaming into a 10k-row session; compare self time of mergeServerRows/patchServerRow against persistState.

#331 TranscriptModel.find_tool_start scans all rows from the front

  • Impact low, effort S, verdict partly, evidence proven-by-code, area sweep-memory, category cpu
  • Where: src/acp/transcript.rs:936-941, src/acp/transcript.rs:704-713, src/acp/transcript.rs:561, src/acp/transcript.rs:610
  • Frequency: Every ToolCallStarted, ToolCallUpdated and ToolCallCompleted folded. On WS connect this covers the whole history (each connection), and on REST view=rows each page. Scales as tools times rows.
  • Problem: position() starts at row 0, and a new tool's start (or its absence) is found only after scanning every row. Folding a 10k-row history with 2k tool calls costs about 20M comparisons per connect or lag rebuild, on the async runtime thread.
  • Fix: Use rposition in find_tool_start and in the id lookups at lines 561 and 610, because updates target recent rows. Alternatively, keep a HashMap<String, usize> of tool_call_id to row index in TranscriptModel, rebuilt on the rare Remove delta.
  • Verifier: Scan is real but cheap: kind compare first, string compare only on ToolStart rows. rposition does not help new tool starts (absent id scans all rows), so the claimed fix is wrong there. A HashMap index is the correct fix. Rebuild cost is likely tens of ms.
  • Measure: Criterion bench folding a 10k-row, 2k-tool history into TranscriptModel; compare against a HashMap index prototype.

#332 TranscriptRow stores ToolCall inline, and every message chunk becomes its own row

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area sweep-memory, category memory
  • Where: src/acp/transcript.rs:21-57, src/acp/transcript.rs:315-335, src/acp/state.rs:53-73
  • Frequency: Per transcript row, held in each WS connection's TranscriptModel, in each view=rows page, in the TUI, and again in the browser. Scales with chunk count, not message count.
  • Problem: Option (about 260 bytes) and Option are inline in every row, including the per-chunk Message rows (msg-{seq}), which never use them. About 600 bytes of inline size per row means a 10k-chunk transcript costs about 6 MB per server-side copy before heap text.
  • Fix: Change the TranscriptRow fields to Option<Box> and Option<Box>. Serialization is unchanged. Optionally, coalesce consecutive same-group Message rows when building transcript_snapshot and view=rows output.
  • Verifier: ToolCall and DiffCommentsPayload are inline Options in every row, so Box would shrink rows. The 600-byte and 6 MB figures are unmeasured, and the claim is a bounded per-connection cost. Boxing is safe for serde but touches many construction sites.
  • Measure: Print std::mem::size_of::() in a test, then compare RSS with 10k rows per WS connection.

4.trace-acp-stream

#333 transcript_append rebuilds an id Map and copies the whole activity array per chunk

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-acp-stream, category cpu
  • Where: web/src/lib/acpTypes.ts:965-998, web/src/hooks/acpSession/reducer.ts:145-165, web/src/hooks/acpSession/reducer.ts:244-245
  • Frequency: Per chunk, per open session tab
  • Problem: mergeServerRows builds a Map over every existing row and slices the array for a single appended row; withServerRows also builds a Set of all ids when optimistic rows exist and flatMaps all rows while a prompt is in flight. Since each chunk is its own row, this is O(n) per chunk and O(n^2) per session.
  • Fix: Add a fast path in the transcript_append case: if the row id is new (track ids in a Set kept alongside activity, or compare against the tail since ids are seq-ordered), return activity.concat(row) without the Map; only run settleServerPrompts/pruneOptimisticRows when the appended row is a user_prompt.
  • Verifier: Confirmed O(n) per chunk: mergeServerRows builds a Map over all rows and slices; transcript.rs:328 makes each chunk a new msg-{seq} row. withServerRows passes the whole activity to settleServerPrompts while a prompt is in flight. But the Map pass is cheap next to finding 0's stringify and downstream O(n) activityMessages grouping per render, so isolated win is small.
  • Measure: Vitest micro-benchmark: mergeServerRows on 10k rows appending one row, 1000 iterations; compare with tail-check fast path.

#334 Event store commits one SQLite transaction per chunk on a single writer thread shared by all sessions

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area trace-acp-stream, category disk-io
  • Where: src/acp/supervisor/sink.rs:148-170, src/acp/supervisor/sink.rs:376-402, src/acp/event_store/mod.rs:236-272, src/events/mod.rs:100-112, src/events/mod.rs:178-181, src/acp/event_store/identity.rs:29-32
  • Frequency: Per chunk, all sessions serialized through one thread
  • Problem: Every token is to_string, inserted in its own transaction with a WAL commit, updating the rowid table, PK autoindex, a redundant idx_session_seq (same columns as the PK), created_at and discriminant indexes, plus an AFTER INSERT trigger upserting acp_history_versions. Broadcast waits on this commit, so concurrent streams add head-of-line latency.
  • Fix: In the acp-event-writer loop, after recv drain further jobs with try_recv (bounded, e.g. 256) and write them via a new EventStore::record_batch in one transaction with prepare_cached, then fold and broadcast in order. Drop idx_{events}_session_seq in a migration.
  • Verifier: Per-chunk transaction and redundant idx_session_seq (same columns as PK) are real. But WAL with synchronous=NORMAL skips fsync per commit, so each commit is sub-ms; prune_retention returns early at the default cap 0. Batching must keep per-publication persisted acks and attachment ordering.
  • Measure: Time EventStore::record in the acp-event-writer with tracing spans while 5 sessions stream; report p50/p99 and queue depth.

#335 acp_event_listener takes the global instances write lock on every chunk

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-acp-stream, category concurrency
  • Where: src/server/acp_events.rs:425-449, src/server/acp_events.rs:507-546, src/server/acp_events.rs:1131-1146
  • Frequency: Per chunk across all sessions
  • Problem: AgentMessageChunk is StatusPolicy::Authoritative and frames carry sidebar_status, so status_update is always Some and the listener acquires state.instances.write() and linearly scans instances, even though the status is almost always unchanged (Running). This contends with every API reader of instances.
  • Fix: Keep a listener-local HashMap<String, Status> of the last projected status per session and continue when status_update equals it and acp_change/load_session_capability are None. Alternatively check inst.status == projected under a read lock before taking the write lock.
  • Verifier: Confirmed: AgentMessageChunk is Authoritative (acp_events.rs:1137), so every chunk takes instances.write() and does a linear find. Hold time is microseconds. A listener-local status cache is unsafe because stops and errors change status elsewhere. A read-lock precheck of the apply_status_intent no-op path is the safe fix.
  • Measure: Instrument instances.write() wait and hold time in acp_event_listener under 5 concurrent streams plus /api/sessions polling.

#336 Runner parses each agent stdout line up to five times

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-acp-stream, category cpu
  • Where: src/process/runner/shared.rs:253-344, src/process/runner/jsonrpc.rs:17-35, src/process/runner/jsonrpc.rs:66-72, src/process/runner/jsonrpc.rs:124-146
  • Frequency: Per agent stdout line (every session/update) per running session
  • Problem: deliver_line runs parse_response_id, then parse_response while a prompt is in flight, parse_response_id again, parse_request_value_id, and finally parse_notification as a full Value DOM, each a full scan of the line, plus two async lock acquisitions of prompt_requests. Tool-output lines can be megabytes.
  • Fix: Parse once into a single envelope struct { id: Option<Value>, method: Option<String>, params/result: Option<Box<RawValue>>, error: Option<JsonRpcErrorPeek> } and branch on it; carry params as RawValue into ControlBody::Notify so encode_frame does not re-serialize a DOM.
  • Verifier: During a prompt, a notification line goes through 4 serde peeks (IgnoredAny skip-scans) plus one full Value DOM, with two prompt_requests locks. The peeks are cheaper than the DOM, and chunk lines are small. Merging the peeks into one envelope is a simple win. RawValue in ControlBody::Notify changes the control protocol type and costs more effort.
  • Measure: Criterion bench of deliver_line classification on a 300B agent_message_chunk line and a 1MB tool_call_update line, old path vs single peek.

#337 Daemon re-serializes and re-parses each notification through the shim and identity layers

  • Impact low, effort M, verdict partly, evidence proven-by-code, area trace-acp-stream, category cpu
  • Where: src/acp/acp_client/control.rs:111-122, src/acp/acp_client/control.rs:569-588, src/acp/acp_client/session_identity.rs:94-116, src/acp/acp_client/session_identity.rs:124-145, src/acp/acp_client/connection/mod.rs:247-255
  • Frequency: Per session/update notification
  • Problem: The control reader parses the frame to a Value DOM, wraps it in a json! line, serializes it to bytes for an in-memory duplex, the SDK parses it again, parse_message deep-clones params, then decode_update runs from_value into the typed SessionNotification. Two DOM builds, one encode and one deep clone before typing.
  • Fix: In SessionIngressNotification::parse_message, store the needed value without cloning by deserializing SessionNotification directly with SessionNotification::deserialize(params) (serde on &Value). In the reader, carry Notify params as Box and write the line with a byte-level splice instead of building a Value.
  • Verifier: Confirmed: reader builds a Value, json! wraps it, to_vec writes it to the duplex, the SDK re-parses it, parse_message clones params (session_identity.rs:116), then from_value types it. The clone is easy to drop. Byte splicing fights the SDK transport shim and the CONTROL_FRAME_BYTES field injection. Per small chunk the cost is microseconds.
  • Measure: Daemon flamegraph (cargo flamegraph or samply) while 5 sessions stream: share of time in serde_json under control reader and SessionIngressNotification.

#338 AoeIngress and SessionIngress serialize the typed update back to JSON just to read _meta

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area trace-acp-stream, category cpu
  • Where: src/acp/acp_client/aoe_ingress.rs:86-102, src/acp/acp_client/session_identity.rs:173-176, src/acp/aoe_meta/mod.rs:233-254
  • Frequency: Per notification (and per discarded frame for is_adapter_frame)
  • Problem: ingest calls serde_json::to_value(&notification.update) on every frame, allocating a full DOM of the update including tool output and diffs, only to read _meta.aoe. is_adapter_frame does the same again for frames routed away.
  • Fix: Add fn update_meta(&SessionUpdate) -> Option<&Meta> matching each variant's meta field and call the existing Envelope::from_meta (as envelope_of already does) and a typed is_anchored over the meta map.
  • Verifier: aoe_ingress.rs:86 runs to_value(&notification.update) on every frame via handle_notification (notifications.rs:294); session_identity.rs:173 repeats it for pending/foreign frames only. Waste is real but roughly equals the deserialize already paid; SessionUpdate is non_exhaustive so a typed meta getter needs a to_value fallback arm.
  • Measure: Criterion bench of ingest() with a 200 KB ToolCallUpdate diff, before and after a typed meta accessor; or perf/samply on daemon during a large Edit.

#339 Full SessionUpdate cloned per notification only for tool-context bookkeeping

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-acp-stream, category memory
  • Where: src/acp/acp_client/connection/notifications.rs:461, src/acp/acp_client/tool_context.rs:116-154, src/acp/acp_client/tool_context.rs:191-200
  • Frequency: Per notification
  • Problem: update_for_tool_context = notification.update.clone() deep-clones every update (chunk text, tool content, meta), but update_tool_context_cache only reads it for ToolCall/ToolCallUpdate raw_input.
  • Fix: Extract raw_input_for_tool_event inputs before mapping: capture Option<(String, Value)> (tool id, raw_input clone) only when the update is ToolCall/ToolCallUpdate with raw_input, and pass that to update_tool_context_cache instead of the whole update.
  • Verifier: Clone is real (notifications.rs:462) and only raw_input_for_tool_event reads it. But a chunk clone is a small string memcpy next to JSON parse, mapping and SQLite insert. Cheap fix: clone only for ToolCall/ToolCallUpdate, else skip. Negligible win.
  • Measure: Run criterion on 10k AgentMessageChunk notifications through handler with and without the clone; compare ns per notification against the SQLite insert.

#340 Event deep-cloned three times and session id re-allocated four times on the publish path

  • Impact low, effort M, verdict partly, evidence proven-by-code, area trace-acp-stream, category memory
  • Where: src/acp/supervisor/sink.rs:283-293, src/acp/supervisor/sink.rs:452-458, src/acp/control_cache.rs:33-57, src/acp/supervisor/mod.rs:878-884, src/server/acp_ws.rs:228-231
  • Frequency: Per chunk (plus one more clone per WS connection)
  • Problem: publish_from_worker clones the owned Event into a Publication, the writer clones it again into Arc for broadcast, apply_if_cached clones it for the fold, and each WS connection clones it for its own fold. session_seq, ControlStateCache::slot, Publication and AcpBroadcastFrame each allocate session_id.to_string(), the map lookups via entry() even on hits.
  • Fix: Change BroadcastSink::publish_from_worker to take Event by value, wrap it in Arc once in the drain, keep the Arc in Publication and broadcast it; make AcpState::apply_event take &Event. Use get() before entry() in session_seq and slot().
  • Verifier: Clones exist (sink.rs:276 event.clone(), sink.rs:457 Arc::new(event.clone()), control_cache.rs:57 clone into apply_event, acp_ws per-connection fold). Real but small, one chunk-sized memcpy each. Drain has only &Event so by-value change touches several callers; entry() allocs also minor.
  • Measure: Use dhat or a counting allocator over a 10k-chunk publish loop; compare allocation count and bytes per event before and after.

#341 block_in_place on every published chunk although the closure only does a try_send

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area trace-acp-stream, category latency
  • Where: src/acp/supervisor/mod.rs:889-901, src/acp/supervisor/sink.rs:361-366, src/acp/supervisor/drain.rs:322-327
  • Frequency: Per chunk per session drain task
  • Problem: publish_with_next_seq wraps the seq-lock section in blocking_io, which calls tokio block_in_place on the multi-thread runtime. For publish_from_worker the work is a non-blocking sync_channel try_send, yet each token hands the worker core off to a new thread.
  • Fix: Add a publish_with_next_seq variant for the drain's publish_from_worker path that locks the counter without blocking_io (the queue only blocks when full, where submit already uses blocking_io), keeping block_in_place for queue_persisted callers that wait on SQLite.
  • Verifier: Claim holds: publish_with_next_seq wraps in blocking_io (mod.rs:896) and publish_from_worker is only a try_send. But the lock is shared with queue_persisted callers that hold it while waiting on the store, so a plain lock can stall an async worker; block_in_place on an idle runtime is cheap.
  • Measure: Bench 100k publish_from_worker calls on a multi-thread runtime with and without block_in_place; compare throughput and tokio worker-thread spawn counts.

#342 One global 256-slot broadcast for all sessions; a lag triggers a full history replay per connection

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area trace-acp-stream, category latency
  • Where: src/server/state.rs:19, src/server/startup.rs:700, src/server/acp_ws.rs:213-219, src/server/acp_ws.rs:252-322
  • Frequency: Every chunk wakes every ACP WS connection of every session; lag recovery on bursts
  • Problem: Every WS handler and the listener receive every session's frames and string-compare session_id. With per-token frames from several sessions, 256 slots fill quickly behind a slow client (3 serializations per chunk), and RecvError::Lagged runs replay_from(session, 0) and refolds the entire history, then sends a full transcript snapshot.
  • Fix: Batch writes (finding above) and raise ACP_CHANNEL_CAPACITY, or replace the single sender with a per-session broadcast map (DashMap<String, broadcast::Sender>) so a connection subscribes to its own session only; the global listener keeps a separate channel.
  • Verifier: Confirmed: one broadcast(256) at startup.rs:700, every acp_ws handler filters by session_id (acp_ws.rs:222) and awaits socket sends inline, and Lagged does replay_from(session,0) plus full refold and snapshot. The filter cost is a string compare on an Arc frame; real cost appears only if Lagged actually fires. No evidence it does in practice.
  • Measure: Count the 'lagged' frames: add a counter or grep acp.ws debug logs during 3 concurrent streaming sessions with one throttled browser tab.

#343 Retention prune runs an OFFSET scan and NOT LIKE delete on every insert when a cap is set

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-acp-stream, category disk-io
  • Where: src/acp/event_store/mod.rs:256-262, src/events/mod.rs:255-316
  • Frequency: Per chunk, only when acp.replay_events > 0 (default 0)
  • Problem: prune_retention runs ORDER BY seq DESC LIMIT 1 OFFSET cap (walks cap index entries) and, once over the cap, a DELETE with 13 NOT LIKE clauses that rescans pinned rows below the cutoff on every insert, plus an attachments delete with a subquery.
  • Fix: Gate prune_retention like prune_completed_background_work: only when seq.is_multiple_of(64) (or a dedicated PRUNE_INTERVAL), accepting up to 64 rows of overshoot.
  • Verifier: Code matches: record() calls prune_retention every insert (event_store/mod.rs:256) and OFFSET scan walks cap index rows. Only when replay_events>0, which the finding says defaults to 0. The sweep-interval gate already exists a few lines below; a similar gate is trivial but overshoot changes the cap semantics.
  • Measure: Time EventStore::record for 50k inserts with cap 10000 on a temp SQLite DB, gated vs ungated prune; check events table size overshoot.

#344 insert_event formats and prepares its SQL on every chunk

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-acp-stream, category cpu
  • Where: src/events/mod.rs:219-237, src/acp/event_store/mod.rs:240-246
  • Frequency: Per chunk
  • Problem: insert_event builds the INSERT string with format! and calls conn.execute, which compiles a new statement each time; the same applies to prune SQL.
  • Fix: Precompute the SQL text in events::Schema and use conn.prepare_cached(...).execute(...) in insert_event (and in prune_retention).
  • Verifier: insert_event uses format! plus conn.execute (events/mod.rs:219-237), so it recompiles each time. prepare_cached is correct, safe and tiny. However insert cost is dominated by the transaction commit and fsync, so parse time is a small share. Prune SQL has a dynamic NOT LIKE clause count, so caching it is less clean.
  • Measure: Criterion bench of record() for 10k events with execute vs prepare_cached on a file-backed SQLite in WAL mode.

#345 Markdown component recreated props per render force re-parse of the streaming message

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area trace-acp-stream, category render
  • Where: web/src/components/acp/Markdown.tsx:46-58, web/src/components/acp/ThreadMessages.tsx:137, web/src/components/acp/ThreadMessages.tsx:170
  • Frequency: Per render of the streaming message (3x per chunk today)
  • Problem: Markdown passes a new components object literal and a new preprocess closure on every render, and AssistantMessage passes a new components object to MessagePrimitive.Parts, so memoization inside MarkdownTextPrimitive cannot hold; the growing message text is re-parsed by remark each update, O(L) per chunk.
  • Fix: Hoist the components maps to module-level constants (MARKDOWN_COMPONENTS, ASSISTANT_PART_COMPONENTS) and memoize preprocess with useCallback on text; rely on rAF batching to bound parses to one per frame.
  • Verifier: Markdown.tsx:46-56 does pass a fresh preprocess closure and components literal, and ThreadMessages.tsx:137 a fresh Parts components object. But the streaming text changes every chunk (and smooth reveal changes it per frame), so react-markdown re-parses regardless; hoisting saves only object churn, unless assistant-ui keys derived components on that identity (unverified, node_modules absent).
  • Measure: React Profiler on a long streaming reply: compare Markdown commit time and code-block remount counts with components hoisted to module constants.

4.trace-terminal-stream

#346 Snapshot-path keystroke echo waits a full 50ms fast tick because the input nudge samples before tmux echoes

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area trace-terminal-stream, category latency
  • Where: src/server/live_ws.rs:1746, src/server/live_ws.rs:1770, src/server/live_ws.rs:2007
  • Frequency: Per keystroke on paired shells and on any agent viewer on the capture fallback
  • Problem: After send-keys returns, send_nudge fires and the loop captures right away. The app has usually not echoed yet, so dedup drops the sample. wait_for_next then sleeps CAPTURE_INTERVAL_FAST_MS (50ms) with no change signal. Typed echo arrives 50ms plus two forks late, not about 10ms.
  • Fix: In handle_live_ws_inner, record the time of the last input. In wait_for_next, when no grid is armed and input happened within about 100ms, use a short follow-up interval (8 to 10ms) for the next 2 or 3 samples, then return to 50ms.
  • Verifier: The nudge fires after send-keys returns (live_ws.rs:1770), then the capture forks tmux, which takes several ms. A local shell echo usually lands first, so the race likely matters mainly for container shells or slow apps. The floor is also 16ms from sample_started, so the 50ms penalty applies only to a missed echo.
  • Measure: Log in the capture loop whether the first post-nudge sample is deduped, over 200 keystrokes on host and container paired shells.

#347 Grid path: the wasted pre-echo sample sets the 16ms floor that delays the real echo frame

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area trace-terminal-stream, category latency
  • Where: src/server/live_ws.rs:1770, src/server/live_ws.rs:2030, src/server/live_ws.rs:2032, src/tui/home/live_send.rs:667
  • Frequency: Per keystroke on every grid-transport web viewer
  • Problem: The binary-input handler nudges the capture loop, which samples an unchanged grid at once. wait_for_next then enforces FRAME_MIN_INTERVAL_MS measured from that sample, so an echo that lands 2ms later cannot publish for up to 16ms. The TUI fixed the same issue by keying its floor on the last publish (publish_floor_wait_ms); the web loop did not.
  • Fix: Measure the floor in wait_for_next from the last publish (track last_publish_at in the capture task), not from sample_started. Or skip send_nudge.notify_one() when the socket has a live grid, because vt_rx already wakes on the echo.
  • Verifier: wait_for_next (live_ws.rs:2032) sleeps FRAME_MIN_INTERVAL_MS from sample_started. The nudged grid sample is in-process and runs before the echo arrives over the VT socket, so the echo waits up to about 14ms. The TUI already keys off the last publish (live_send.rs:667). Either proposed fix is safe. The win is at most 16ms per keystroke.
  • Measure: Timestamp the binary input and the next published frame seq in live_ws.rs. Compare the keystroke-to-echo latency distribution before and after keying the floor off the last publish.

#348 Blocking tmux fork inside async capture task (Osc52Channel heartbeat)

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area trace-terminal-stream, category concurrency
  • Where: src/server/live_ws.rs:1463, src/tmux/vt.rs:3573
  • Frequency: Every 1.5s per snapshot-transport viewer with clipboard forwarding (all paired shells by default)
  • Problem: source.refresh_owner_heartbeat() runs directly on the tokio worker inside the capture task, not in spawn_blocking. Every 1.5s it forks tmux if-shell/set-option and blocks the worker thread for the fork and the tmux round trip, up to the command deadline. With many open shell tabs this stalls other WS tasks, including frame sends and input.
  • Fix: Move the heartbeat into the existing spawn_blocking capture closure for the snapshot branch. Or wrap it in tokio::task::spawn_blocking with a cloned Arc.
  • Verifier: live_ws.rs:1461-1463 calls Osc52Channel::refresh_owner_heartbeat inside tokio::spawn capture task; it forks tmux if-shell via deadline.run (10s TMUX_COMMAND_TIMEOUT). Rate limited to 1.5s per channel; Osc52 only when vt is None. Normal cost is a few ms per 1.5s, so worker stall is real but small except when tmux hangs.
  • Measure: tokio-console or tracing span around refresh_owner_heartbeat at live_ws.rs:1463, log elapsed and busy-worker time with 20 open snapshot shell tabs.

#349 Per-cell String allocation in VT row serialization (cell_sgr)

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area trace-terminal-stream, category cpu
  • Where: src/tmux/vt.rs:1735, src/tmux/vt.rs:1806, src/tmux/vt.rs:1822, src/tmux/vt.rs:1694
  • Frequency: Per grid sample that misses the cache: up to 60/s per channel while output streams, for every row x col in the window (up to 2000 rows when reading)
  • Problem: row_to_ansi_upto calls cell_sgr for every cell. For styled cells it builds a Vec of params (one to_string per number) plus a format!/join, then compares it to cur_sgr and clones it. A 50x200 colored screen costs tens of thousands of allocations per sample, all under the parser lock that also blocks the reader thread.
  • Fix: In row_to_ansi_upto, compare the attribute tuple (fg, bg, bold, dim, italic, underline, inverse) to the previous cell's tuple. Emit SGR only on change, writing the params straight into out with write!/itoa. Drop cell_sgr's Vec.
  • Verifier: cell_sgr (vt.rs:1735) builds Vec plus join/format per styled cell, then row_to_ansi_upto clones into cur_sgr. Runs under parser lock. Fast 16ms grid cadence applies only when window_lines <= screen*4 (wait_for_next), and sample_cache short-circuits unchanged grid_gen, so cost is bounded to small windows while streaming.
  • Measure: criterion bench of grid_content on a 50x200 fully colored parser, before and after; count allocations with dhat.

#350 grid_content allocates the whole scrollback each sample and re-serializes the full window on every chunk

  • Impact low, effort L, verdict partly, evidence plausible-needs-measurement, area trace-terminal-stream, category cpu
  • Where: src/tmux/vt.rs:1881, src/tmux/vt.rs:1897, src/tmux/vt.rs:3006, src/tmux/vt.rs:3026
  • Frequency: Per cache-missing sample, up to 60/s per channel while streaming; sample cache invalidates on every parsed chunk
  • Problem: grid_content allocates vec![None; total] for all scrollback plus screen rows, even for a screen-sized window. Any chunk bumps grid_gen, so the whole window is re-serialized, though usually only the bottom rows changed. The serialization holds the parser mutex, which delays the reader's next chunk.
  • Fix: Size buf to want (target_low..total) only. Keep per-row cached ANSI strings in SampleCache keyed by absolute row, and invalidate only visible-screen rows when grid_gen moves and scrollback did not shift. Re-serialize scrollback rows only when total_sb changes.
  • Verifier: buf is vec![None; total] with total <= SCROLLBACK_LINES(2000)+h, about 48KB, trivial. The loop only serializes screens until base <= target_low, so roughly the window, not all scrollback. Proposed per-row cache is unsafe: at the 2000-line cap total_sb stays constant while rows shift, so 'invalidate only when total_sb changes' serves stale rows.
  • Measure: Time grid_content under the parser lock via tracing span in sample_with_clock while running 'yes' in a single-pane shell with a 200-line window.

#351 Status poller forks list-panes plus capture-pane per busy session despite holding pane_id in metadata and a live grid

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-terminal-stream, category subprocess
  • Where: src/session/instance/status_update.rs:570, src/tmux/session.rs:833, src/tmux/session.rs:1274, src/tmux/mod.rs:327, src/server/status_poll.rs:463
  • Frequency: Every 500ms (with subscribers) or 2s, per session whose window_activity changed, so every streaming session, run serially in one spawn_blocking
  • Problem: update_status_from_manifest calls session.capture_pane, which resolves the target through live_pane_target_with_deadline (a list-panes fork when no in-process VtChannel exists) before forking capture-pane. PaneMetadata from batch_pane_metadata already carries pane_id. When the daemon holds a VtChannel for the session, its grid already has the screen, but the poller still forks capture-pane.
  • Fix: Add Session::capture_pane_at(target, lines) and pass metadata.pane_id from update_status_with_metadata. When crate::tmux::vt has a live channel for the session, read the last N screen rows from the grid (sample_with_deadline(lines)) and do not fork.
  • Verifier: capture() forks list-panes via first_pane_id when no VtChannel, then capture-pane; metadata.pane_id is the same first-window pane 0, so passing it saves one fork per busy session per tick. With a live VtChannel the list-panes fork is already skipped (channel_pane_id). Reading the grid instead is unsafe: sample_with_deadline itself forks reconcile/heartbeat and serializes differently.
  • Measure: Count tmux execs per status_poll tick with 10 streaming sessions: dtruss/execsnoop filtered on tmux, before and after passing pane_id.

#352 Idle visible grid viewer still forks about 3 tmux commands per second

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-terminal-stream, category subprocess
  • Where: src/server/live_ws.rs:169, src/server/live_ws.rs:1190, src/server/live_ws.rs:1982, src/tmux/vt.rs:2848, src/tmux/vt.rs:2822, src/tmux/session.rs:1797
  • Frequency: Per visible web agent viewer, continuously while open: pane-count probe 1/s, reconcile display-message 1/s, VT-owner heartbeat 1/1.5s, size-owner heartbeat 1/1.5s
  • Problem: window_pane_count (display-message #{window_panes}) and VtChannel::reconcile_grid (display-message pane_width/height/cursor) are separate forks on the same 1s cadence against the same pane. The VT-owner and size-owner heartbeats are two more if-shell forks on the same 1.5s cadence. Together that is about 3.3 forks/s per open session with no output.
  • Fix: Add #{window_panes} to pane_size_cursor's format and expose the last observed pane count from VtChannel, so live_ws reuses it and drops window_pane_count on the grid path. Chain the size-owner refresh and refresh_vt_owner into one tmux invocation (both are if-shell + set-option on the same session).
  • Verifier: Forks are real: window_pane_count (1s) plus reconcile display-message (1s) plus two 1.5s heartbeats. But size-owner heartbeat runs only for the owner, and each fork is a few ms off-thread. Merging pane count into pane_size_cursor is easy; chaining heartbeats is riskier.
  • Measure: Run an idle open session with tmux -L socket wrapper or dtruss counting tmux execs per minute; compare after merging probes.

#353 TUI and web each arm their own pipe-pane, so one surface viewing the same session always degrades to capture polling

  • Impact low, effort L, verdict partly, evidence proven-by-code, area trace-terminal-stream, category subprocess
  • Where: src/tui/home/live_send.rs:1504, src/server/live_ws.rs:1035, src/server/live_ws.rs:1043, src/tmux/vt.rs:2584
  • Frequency: Whenever the TUI has a session selected (even passive preview) while a web viewer opens it, or the reverse
  • Problem: pipe-pane is exclusive per pane, and VtChannel is per process. The TUI arms a channel for the selected session even in passive preview. A web viewer of that session gets PipeOwned and runs the 50ms two-fork capture-pane loop with full-window dedup. The TUI and daemon status poller also probe pane count and capture the same pane independently.
  • Fix: When a daemon is running, have the TUI's capture worker subscribe to the daemon's live-ws frames for the selected session (one VtChannel, in the daemon) and not call VtChannel::acquire_with_deadline itself. Or at minimum skip TUI VT arming in passive (non live-send) preview so the daemon keeps the pipe.
  • Verifier: Real: VtChannel::arm returns PipeOwned when another process holds the owner lease (vt.rs:2591), and live_ws then polls capture (50ms fast, 250ms idle). An explicit Claim re-arms the grid (live_ws.rs:1132, 1870). The cheap fix only moves capture polling to the TUI. Only daemon-fed TUI frames remove it, and that is L.
  • Measure: With TUI preview and web viewer on one session, count tmux forks for 60s: sudo dtrace -n 'proc:::exec-success /execname=="tmux"/ {@=count()}'

#354 Paired-shell and fallback keystrokes cost up to two tmux forks each

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-terminal-stream, category latency
  • Where: src/server/live_ws.rs:1752, src/tmux/session.rs:1361, src/tmux/session.rs:1274
  • Frequency: Per keystroke WS message on tmux < 3.8 (all agent sessions) and on every paired shell (no channel: 2 forks)
  • Problem: send_raw_bytes resolves the target with live_pane_target_with_deadline (a list-panes fork unless a VtChannel exists in the process) and then forks send-keys -H per batch. Shells never have a VtChannel, so each key is two serial forks inside an awaited spawn_blocking. That adds several ms per key and serializes fast typing.
  • Fix: Cache the resolved pane id per connection in handle_live_ws_inner and call a send_raw_bytes_to(target, bytes) variant. Coalesce binary messages already queued in ws_receiver (drain with now_or_never) into one send-keys call.
  • Verifier: send_raw_bytes (session.rs:1361) forks list-panes, then send-keys. channel_pane_id short-circuits when a VtChannel exists in-process, even an output-only one on tmux < 3.8. So agent sessions cost 1 fork per key, and only shells or PipeOwned cost 2. pane_input_bytes does not fork. Pane-id caching must handle respawn.
  • Measure: Instrument the spawn_blocking in live_ws.rs:1752 with an Instant timer per Binary message and log p50/p99 while typing in a paired shell.

#355 Every WS frame synchronously re-renders the whole LiveTerminalView tree

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area trace-terminal-stream, category render
  • Where: web/src/hooks/useSnapshotStore.ts:11, web/src/hooks/useLiveTerminal.ts:308, web/src/components/LiveTerminalView.tsx:123, web/src/components/LiveTerminalView.tsx:547
  • Frequency: Per frame/patch message: up to about 60/s per visible terminal while an agent streams
  • Problem: useLiveTerminal stores frame and a fresh stats object in a useSyncExternalStore snapshot consumed by LiveTerminalView (57 hook calls). Each message forces a synchronous render of that component and its non-memoized children (MobileTerminalToolbar, LiveControlStrip, banners, KeyboardFab, ArrowJoystick). Several messages decoded in one task each render separately, with no rAF coalescing.
  • Fix: Keep frame and stats in a separate store that only MobileLiveTerminal subscribes to (pass the store, not live.state.frame). Coalesce setState for frames to one per requestAnimationFrame in handleMessageText. Wrap MobileTerminalToolbar and LiveControlStrip in memo.
  • Verifier: Confirmed: there is no memo and no React Compiler, and the touch-only LiveTerminalView re-renders on every frame. The server caps frames at 16ms per FRAME_MIN_INTERVAL_MS. Overstated: useSyncExternalStore updates are SyncLane and flushed in a microtask, so messages decoded in one task already share one render. The chrome children are light, so the main cost is MobileLiveTerminal, which must render anyway.
  • Measure: Use React DevTools Profiler on a mobile-emulated live session while an agent streams, and compare the commit time of LiveTerminalView chrome against MobileLiveTerminal.

#356 Backgrounded or hidden tabs keep receiving frames and fork heartbeats

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-terminal-stream, category network
  • Where: web/src/components/MobileLiveTerminal.tsx:632, src/server/live_ws.rs:2020, src/server/live_ws.rs:132
  • Frequency: Every 250ms per hidden tab or inactive terminal pane while its pane produces output
  • Problem: setCadence(false) is shared by 'reading scrollback' and 'tab hidden'. The server still samples, diffs, deflates and sends changed frames to a hidden tab every 250ms and keeps all heartbeat forks running. The comment cites phone battery and data, but idle cadence only rate-limits these costs and does not stop them.
  • Fix: Add a {type:'cadence', paused:true} (or a visible flag) to LiveClientMessage. When it is set, wait_for_next keeps only the size-owner heartbeat and death checks and does not sample or publish. The first resume forces force_full.
  • Verifier: Hidden tab sets fast=false, so wait_for_next uses 250ms idle cadence and grid_arm is disarmed. Changed frames are still sent and heartbeats continue. Cost is bounded to 4 frames/s while pane changes; idle panes dedupe. Pause message is feasible but needs resume force_full.
  • Measure: Open a tab, hide it, stream agent output; count WS bytes/s and stats.publishes in devtools network panel.

#357 Client rebuilds an unused full-window string on every patch

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area trace-terminal-stream, category cpu
  • Where: web/src/hooks/useLiveTerminal.ts:281, web/src/components/MobileLiveTerminal.tsx:203
  • Frequency: Per patch message, up to about 60/s while streaming; O(window lines)
  • Problem: applyPatch produces lines, and then content = lines.join('\n') + '\n' joins the full window again. The only consumer, MobileLiveTerminal, prefers frame.lines and never reads content when lines is present.
  • Fix: Make LiveFrame.content optional, and on the patch branch store only lines. Have frameLines in MobileLiveTerminal read lines alone.
  • Verifier: Patch branch does lines.join plus newline each patch, but MobileLiveTerminal uses frame.lines ?? frame.content, so content is unused when lines exists. Cost is one join of the window per frame, microseconds to low ms. Tests may read content, so update them.
  • Measure: Vitest bench or performance.mark around the patch branch with a 4000-line window, 60 patches/s.

#358 Per-frame O(window) key building in LineParseCache while reading

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area trace-terminal-stream, category cpu
  • Where: web/src/lib/liveTermLines.ts:40, web/src/components/MobileLiveTerminal.tsx:208
  • Frequency: Per frame; window up to 4000 lines while reading, 250ms cadence
  • Problem: LineParseCache.lines builds a styleKey + row string key and does two Map lookups for every row on every frame, and the visual useMemo walks every line again. On a 2000-line reading window, a one-row patch still costs about 4000 string concatenations and hashes per frame.
  • Fix: Patches already name changed indices. Pass them through LiveFrame and have LineParseCache.lines reuse the previous frame's parsed rows for unchanged indices, after applying shift. Re-parse only listed rows and rows whose entry state changed.
  • Verifier: LineParseCache does build a key and two Map lookups per row each frame, and the visual useMemo walks lines anyway. At 250ms reading cadence that is a few ms per frame. Reusing by changed index must handle shift and entry-state carry, so risk exceeds gain.
  • Measure: React Profiler or performance.now around parseCache.lines with a 4000-line frame in a Vitest bench.

#359 TUI preview round-trips the grid through ANSI text and re-parses it every frame

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area trace-terminal-stream, category cpu
  • Where: src/tmux/vt.rs:2990, src/tui/home/preview.rs:134, src/tui/home/preview.rs:208
  • Frequency: Per published preview frame (up to about 40/s in live-send, 250ms passive) for the selected session
  • Problem: VtChannel serializes cells to ANSI (with per-cell SGR allocations), then ensure_parsed parses that string back into ratatui Text with parse_output_text. Each new frame invalidates the parse of the whole captured window.
  • Fix: Add a VtChannel method that returns ratatui Lines built directly from vt100 cells for the TUI. Keep ANSI only for the web wire format and the capture fallback.
  • Verifier: Round trip is real (grid_content builds per-row ANSI, ensure_parsed re-parses) but both steps are cached: sample_cache keyed by grid_gen, parsed_text cleared only on new capture. Cost is one window per changed frame, and a render sampler (PreviewTimings.parse) already exists. The ANSI form is shared with web and capture fallback, so a second path risks drift (#2433).
  • Measure: Read PreviewTimings.parse from the render sampler during live-send on a 200x60 pane with 10k scrollback; compare to frame budget.

4.trace-status-list

#360 Status tick re-parses every config file and reinstalls status rules for every profile

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area trace-status-list, category disk-io
  • Where: src/server/reload.rs:464-571, src/server/reload.rs:589-612, src/session/config/profile_config.rs:183-196, src/tmux/status_rules.rs:86-119, src/server/status_poll.rs:510
  • Frequency: Every status tick (500ms or 2s), times (profile count + 1). The disk-watch reload (every sessions.json write) repeats it.
  • Problem: ProfileSessionsCache caches only sessions.json. load_profiles still calls Config::load (config.toml and state.toml TOML parse), load_workspace_ordering, and projects::load_global on every tick. Per profile, load_profile_details runs load_profile_config twice and resolve_config. resolve_config runs install_from_config: it takes the global status-rule registry write lock and recompiles status_rules regexes. That lock blocks concurrent detection. The comment at profile_config.rs:191 ('the status poll hot path never loads config') is now false.
  • Fix: Cache ProfileDetails and the global metadata in ProfileSessionsCache, keyed by DataFileStamp of config.toml, state.toml, the profile config, and the projects files, as SessionsFileCache does. Call install_from_config only when the stamp changes. Otherwise reuse the cached CanonicalMetadata clone.
  • Verifier: Confirmed per tick: Config::load (config.toml+state.toml), plus per profile load_profile_config twice and resolve_config (another Config::load, merge, install_from_config write locks). Regex compile only runs when a user configured status_rules, and lock hold is microseconds on the same thread. Waste is real but likely low milliseconds per tick; stale comment at profile_config.rs:191 confirmed.
  • Measure: Wrap load_profiles in a tracing span with elapsed micros; log p50/p99 over 100 ticks with 3 profiles and a realistic config.toml.

#361 All five sidebar axes are rebuilt and sorted on every change, but only one is displayed

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area trace-status-list, category cpu
  • Where: web/src/hooks/app/useSidebarModel.ts:58-68, web/src/components/WorkspaceSidebar.tsx:169-176, web/src/lib/sidebarGroups.ts:116-300
  • Frequency: Every sessions-array identity change (3s poll, each status push, each mutation). Scales with workspaces times axes.
  • Problem: useSidebarModel always runs useRepoGroups, useSessionGroups, useStatusGroups, useNestedSidebarGroups, and useOrgGroups. Each groups and sorts the full workspace list. triageWorkspaces then flattens every axis, plus sessionWorkspaces, into one large array for useSidebarTriage. That is about 4x the grouping and sorting work and allocation needed for the axis the user is viewing.
  • Fix: Pass axis into each hook and have the inactive ones return a stable empty array: useMemo returns EMPTY when the axis differs. Nested and org need repo.groups only when their axis is active. Build triageWorkspaces from the active axis only.
  • Verifier: All axis hooks run every time (useSidebarModel.ts:58-62). nested and org derive from repo.groups, and repo must stay live for savedProjects and appearance. triageWorkspaces deliberately flattens every axis so overrides survive across axes. At a few hundred workspaces, the extra O(N log N) sorts likely cost under a millisecond. Gate only the session and status hooks.
  • Measure: performance.mark around useSidebarModel group builds with 500 synthetic sessions; compare total ms per sessions change.

#362 Sidebar comparators re-parse timestamps and recompute ranks on every comparison

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-status-list, category cpu
  • Where: web/src/lib/sidebarSort.ts:30-37, web/src/lib/sidebarSort.ts:173-183, web/src/lib/sidebarSort.ts:288-315, web/src/lib/sidebarGroups.ts:166, web/src/lib/sidebarGroups.ts:247
  • Frequency: Each grouping rebuild, times the active axes (see above). O(W log W times sessions per workspace).
  • Problem: compareWorkspacesByLastActivityDesc and compareWorkspacesByAttention call workspaceLastActivityMs (3 Date.parse calls per session), workspaceTriageTier, workspaceIsUrgent, and workspaceAttentionRank for both operands on every comparison. With W=300, a sort does about 2,500 comparisons and about 15k Date.parse calls, repeated for each axis and each subgroup on every update.
  • Fix: Use decorate-sort-undecorate in workspaceComparator's callers. Compute a key tuple once per workspace (tier, urgent, rank, fav, lastMs, id) into a Map before views.sort, and compare the tuples.
  • Verifier: Comparators do recompute Date.parse and ranks per comparison, but sort runs inside useMemo in WorkspaceSidebar, only on data change. Real N is tens of workspaces; at 300 it is roughly 1ms to a few ms. Decorate-sort is valid but a micro-win.
  • Measure: performance.now() around buildSidebarGroups in a Vitest bench with 300 workspaces x 3 sessions, per axis; compare against decorated variant.

#363 One setInterval per animated status glyph

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area trace-status-list, category render
  • Where: web/src/components/StatusGlyph.tsx:67-77, web/src/lib/rattles.ts:5-10, web/src/components/sidebar/RowBadges.tsx:69-90
  • Frequency: Every 180 to 400ms for each rendered Running, Waiting, or Starting row. Linear in visible active sessions.
  • Problem: Each StatusGlyph owns a setInterval and calls setFrame. At N=300 running sessions, that is about 1,500 timer callbacks and React commits per second on the main thread, and timers stay alive in background tabs (throttled to 1s). WakeupCountdown adds one more 1s interval per row with a wakeup.
  • Fix: Use one shared ticker per rattle interval: a module-level store with a single setInterval that starts on first subscriber and stops on last, read via useSyncExternalStore. Frames stay phase-aligned through the existing createdAt epoch math. Alternatively, render the spinner with a CSS steps() animation on a sprite.
  • Verifier: Confirmed: each animated StatusGlyph owns its own setInterval (dots 220ms, orbit 400ms, breathe 180ms) and the sidebar is not virtualized. But each tick re-renders one text leaf, and typical active N is about 10 to 30, so the cost is small. A shared ticker would batch updates into one commit per interval. The N=300 framing overstates the realistic win.
  • Measure: Chrome Performance panel, 10s recording with 50 Running sessions in the sidebar; compare scripting ms and commit count before and after the shared ticker.

#364 TUI clears remote-owner cache on every snapshot, so Org grouping reopens git repos per snapshot

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area trace-status-list, category cpu
  • Where: src/tui/home/lifecycle.rs:580-581, src/tui/home/status.rs:680-681, src/tui/home/rows.rs:358-375
  • Frequency: Every applied runtime snapshot (about every 500ms under load) while the TUI groups by Org. Scales with distinct repos.
  • Problem: refresh_projection_presentation and the metadata branch call remote_owner_cache.borrow_mut().clear(). resolve_org then calls get_remote_owner_with_key (a libgit2 open plus a remote read) for every distinct repo on the UI thread. This defeats the doc comment's 'memoized per repo path so grouping doesn't reopen a git repo on every rebuild'.
  • Fix: Stop clearing in refresh_projection_presentation. Clear only in the refresh_metadata branch when the set of repo paths changes, or on an explicit reload. Alternatively, use SessionResponse.remote_owner_key from the snapshot, which the daemon already resolves and caches permanently.
  • Verifier: Every applied snapshot calls refresh_projection_presentation (status.rs:851, lifecycle.rs:479), which clears remote_owner_cache (lifecycle.rs:581). Under Org grouping, resolve_org then reopens each distinct repo with libgit2 on the UI thread. Org grouping is opt-in, and the cost is about 1ms per distinct repo per snapshot. Fix: drop the clear at lifecycle.rs:581.
  • Measure: Wrap build_flat_items_by_org in a tracing span; with Org grouping and 20 repos, log its duration per applied snapshot before and after removing the clear.

#365 tmux inventory polled twice per daemon tick and again by the TUI display poller

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area trace-status-list, category subprocess
  • Where: src/server/status_poll.rs:512-513, src/tmux/mod.rs:744-785, src/tmux/mod.rs:1434-1520, src/tmux/mod.rs:2610-2643, src/tui/app.rs:624
  • Frequency: Daemon: 2 forks per tick (4/s with the TUI attached). TUI: 2 forks every 1s (CACHE_TTL/2). Constant in N, but the tmux server serializes them against the per-session captures.
  • Problem: status_poll_loop runs refresh_session_cache (list-sessions) and then batch_pane_metadata (list-panes -a). The second output already lists every session name, so the first fork is redundant. The TUI process runs its own aoe-display-snapshot thread with list-sessions plus list-panes every second, duplicating the inventory the daemon already publishes as agent_pane and auxiliary presence.
  • Fix: Have batch_pane_metadata publish SESSION_CACHE from its parsed session names, and drop the separate refresh_session_cache call in the tick. In the TUI, lengthen the snapshot poller to 5s while sidebar_source is Daemon, or answer render-time presence from the snapshot's agent_pane.
  • Verifier: Two forks per tick (2s idle, 500ms with subscribers) and TUI poller every 1s are real, and the TUI poller is not gated on sidebar_source. But list-sessions has distinct format and outcome semantics (NoServer/Unknown, refresh ids), so merging is not trivial. Fork cost is ms-scale.
  • Measure: Run dtruss/fs_usage -f exec counting tmux execs per minute with daemon plus TUI attached at 50 sessions; check tmux.cache trace duration_ms.

#366 Per-tick deep clones of every Instance in daemon reload

  • Impact low, effort M, verdict partly, evidence proven-by-code, area trace-status-list, category memory
  • Where: src/session/storage.rs:2106-2109, src/server/reload.rs:1502, src/server/status_poll.rs:482-496, src/server/reload.rs:806-821
  • Frequency: Every status tick. O(N) Instance clones, repeated several times.
  • Problem: The cached load returns rows.clone() (a full Vec deep clone). merge_loaded_rows clones each prior again (prior_by_id.get(..).cloned()). The tick also builds prev and PriorTickTracking maps, cloning ids and auxiliary targets. Then project_sessions builds N SessionResponse and deep-compares the whole contents. Instance carries many strings and vectors, so this is allocator churn of several MB/s at N=300.
  • Fix: Store cached rows as Arc<[Instance]> and clone-on-write only rows the tick mutates. In merge_loaded_rows, take ownership via HashMap::remove into a separate overlay map instead of cloning the prior. Key prev and tracking by an index into state.instances instead of cloned String ids.
  • Verifier: Cache hit does return rows.clone() (storage.rs:2106) and merge_loaded_rows clones prior per row, so deep clones per tick exist. But ticks are 2s idle, 500ms only with subscribers, and run in spawn_blocking. 'Several MB/s' is unmeasured; Arc refactor touches core state types.
  • Measure: Run dhat or a counting allocator on one tick with 300 synthetic Instances; or heaptrack the daemon with a subscriber attached.

#367 Hook status read opens the instance directory twice per session per tick

  • Impact low, effort S, verdict partly, evidence proven-by-code, area trace-status-list, category disk-io
  • Where: src/hooks/status_file.rs:46-67, src/session/instance/status_update.rs:311-315
  • Frequency: Every tick per live terminal session that reaches detection. Linear in N.
  • Problem: read_hook_status and read_hook_status_age each call open_instance_dir_read_only (an anchored, component-by-component open) and then read or stat 'status'. The same pair runs again in log_status_transition. That is about 4 to 6 extra syscalls per session per tick: small, but it adds up at N=300 with 500ms ticks.
  • Fix: Add read_hook_observation(instance_id) -> Option<(Status, Option<Duration>)>. It opens the directory once, then fstats and reads the file through the same fd. Use it in update_status_with_metadata_inner and detect_pane_now.
  • Verifier: Double open of the instance dir per session per tick is real (status_update.rs:313-315, ~2 extra syscalls). But log_status_transition (lines 106-107) runs only on a status change, not per tick, so the claim of 4 to 6 syscalls is overstated. Cost is microseconds per session.
  • Measure: Use sudo fs_usage -w -f filesys <daemon pid> over 10 ticks at 100 sessions; count openat/fstat per instance and compare with a combined read.

4.rust-build

#368 xtask builds the root crate with the typescript feature, a separate full build of the lib

  • Impact low, effort S, verdict partly, evidence proven-by-code, area rust-build, category dev-loop
  • Where: xtask/Cargo.toml:8-11, Cargo.toml:238, src/daemon/live.rs:19, src/daemon/live.rs:180-181, xtask/src/main.rs:69-80, xtask/src/main.rs:346
  • Frequency: Every cargo xtask <cmd> after a src change (gen-docs, check-skill, dev), and every cargo check/clippy/test --workspace. cargo xtask dev compiles the lib twice before it starts.
  • Problem: xtask depends on agent-of-empires with typescript, which changes the lib's feature hash. So xtask, and --workspace commands through feature unification, build a third copy of the 657k-line lib. The comment at xtask/Cargo.toml:8 says it stays on default features, which is false. cargo xtask dev then runs cargo build --features web, which is another full lib build.
  • Fix: Drop the typescript feature. Change the 13 cfg_attr(feature = "typescript", ...) in src/daemon/live.rs to cfg_attr(test, ...), make ts-rs a dev-dependency, and emit liveWire.ts from a #[test] #[ignore] fn export_live_wire that gen-live-wire runs with cargo test --lib. Or make ts-rs a normal unconditional dependency. Either way the lib keeps one hash.
  • Verifier: Confirmed: xtask enables typescript, which gives the lib a separate hash, and the comment at xtask/Cargo.toml:8 is stale. But xtask dev then builds with --features web, a different hash anyway, so that second build stays. CI runs xtask in its own docs job. The local win applies only when a developer runs gen-docs or check-skill. Making ts-rs unconditional is the simplest fix.
  • Measure: cargo build; touch src/lib.rs; cargo build; time cargo xtask gen-docs; then compare after removing the typescript feature.

#369 webauthn-rs pulls in vendored OpenSSL plus 26 extra crates next to aws-lc-sys and RustCrypto

  • Impact low, effort L, verdict partly, evidence plausible-needs-measurement, area rust-build, category compile-time
  • Where: Cargo.toml:163-165, Cargo.toml:214-216, src/server/passkeys.rs:20
  • Frequency: Every clean build, every new worktree target/, every cache miss. kache docs say native-linking crates still rebuild. Release and Nix builds always.
  • Problem: vendored enables git2/vendored-openssl. git2 has no https feature, so libgit2 never uses OpenSSL. In practice the flag only builds openssl-src (Perl configure plus a full C OpenSSL build, the slowest build step) for webauthn-rs. webauthn-rs also adds x509-parser, asn1-rs, nom 7, thiserror 1, base64 0.21, rand 0.9 and syn 2 users. That makes 3 crypto stacks: OpenSSL, aws-lc and RustCrypto.
  • Fix: Replace webauthn-rs in src/server/passkeys.rs with a pure-Rust verifier built on p256 (already a dependency with ecdsa) and a small CBOR/COSE parser, or a pure-RustCrypto WebAuthn crate. Then remove git2/vendored-openssl from the vendored feature. That drops openssl-sys, openssl-src and 26 crates.
  • Verifier: git2 0.21 has default = [] and no https, so vendored-openssl only adds openssl-sys/vendored. cargo tree shows openssl comes from webauthn-rs-core and webauthn-attestation-ca. This costs clean builds only. Hand-rolling WebAuthn verification in 1538-line passkeys.rs is a security risk, and openssl-src may run in parallel off the critical path.
  • Measure: cargo clean; cargo build --timings; check openssl-sys build-script time and critical path in cargo-timing.html

#370 jsonwebtoken plus aws_lc_rs used for one ES256 VAPID JWT

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area rust-build, category compile-time
  • Where: Cargo.toml:174, src/server/push_send.rs:97-112, Cargo.toml:171
  • Frequency: Compile time on every clean build. At runtime, once per Web Push send.
  • Problem: jsonwebtoken (with pem, simple_asn1, signature 2.2, which duplicates signature 3.0, and base64 0.22) exists only to sign one ES256 JWT in vapid_auth_header. p256 with ecdsa and pem is already a dependency and can sign it directly. aws-lc-rs stays because of rustls, so the win is removing about 4 unique crates and the duplicate signature.
  • Fix: In vapid_auth_header, load the key with p256::ecdsa::SigningKey::from_pkcs8_pem and base64url-encode the header and claims with the existing base64 crate. Sign with Signer::sign and append the raw r||s signature. Remove jsonwebtoken from Cargo.toml.
  • Verifier: jsonwebtoken is used only at push_send.rs:98. Key is already PKCS8 PEM (push.rs:166,186), so p256 SigningKey signs directly. Removing it drops jsonwebtoken, simple_asn1, pem, signature 2.2.0 and base64 0.22 (Cargo.lock:2525+). Runtime cost is negligible.
  • Measure: cargo tree -d | grep -E 'signature|base64'; compare cargo build --timings crate list before and after removal.

#371 Duplicate dependency versions from direct deps one major ahead of their dependents, plus an unused tower-http fs feature

  • Impact low, effort S, verdict partly, evidence proven-by-code, area rust-build, category compile-time
  • Where: Cargo.toml:191, Cargo.toml:153, Cargo.toml:132
  • Frequency: Every clean build and every dependency rebuild after a feature fork.
  • Problem: axum 0.8.9 depends on tokio-tungstenite 0.29 but the direct dep is 0.30 (dependabot #3120). That compiles tungstenite twice and adds sha1 0.11. reqwest pins tower-http 0.6 against the direct 0.7. parking_lot 0.13 is direct only; tokio and crossterm use 0.12, which duplicates lock_api and parking_lot_core. tower-http fs (ServeDir) is unused: no ServeDir/ServeFile in src. It pulls http-range-header.
  • Fix: Set tokio-tungstenite to 0.29 (same rustls-tls-native-roots feature), tower-http to 0.6 with compression-gzip and compression-zstd and without fs, and parking_lot to 0.12. Add dependabot ignore rules so these stay aligned with axum and reqwest, and switch deny.toml multiple-versions to deny for these crates.
  • Verifier: Duplicates are real in Cargo.lock: tungstenite 0.29/0.30, tower-http 0.6/0.7, parking_lot 0.12/0.13. The fs feature is unused (only compression in router.rs), so dropping it is a clean win. Pinning deps one major behind is churn; dependabot already tracks them.
  • Measure: cargo tree -d --features web; cargo build --timings, check tungstenite and tower-http unit times.

#372 Tests run argon2 and other crypto at opt-level 0

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area rust-build, category test-time
  • Where: Cargo.toml:263-274, src/server/login.rs:97-114, src/server/auth.rs:1249, src/server/passkeys.rs:1308
  • Frequency: About 45 test call sites hash or verify a passphrase with Argon2::default (19 MiB, t=2). Debug aoe binaries in e2e do the same per passphrase login. Runs every test run, locally and in CI.
  • Problem: profile.dev sets no opt-level for dependencies, so argon2 and blake2 run unoptimized. That is usually 20-50x slower than release, roughly 0.5-1.5 s CPU per hash. sha2, p256 and regex compilation are also slow at opt-level 0 in tests and debug daemons.
  • Fix: Add [profile.dev.package.argon2], blake2, sha2, p256, regex-automata and regex-syntax sections with opt-level = 3. These are dependency-only, compiled once, and cached by kache. For the test-only case, have the test helpers that build LoginManager use cheap argon2::Params behind cfg(test).
  • Verifier: No dev opt-level override exists (Cargo.toml:263-274). hash_passphrase/argon2_verify use Argon2::default (19 MiB, t=2) in login.rs:101,111, with many test callers. Real cost unmeasured. Dependency opt-level for argon2/blake2 is a cheap fix, though the compile-time tradeoff is untested.
  • Measure: cargo nextest run login:: with and without [profile.dev.package.argon2] opt-level=3; compare per-test times.

#373 rustdoc doctest pass and bin test harness add work for zero tests

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area rust-build, category test-time
  • Where: Cargo.toml:291-303, src/main.rs:1-515, src/task_util.rs:28, src/tui/styles/resolved.rs:65
  • Frequency: Every local cargo test run without nextest, which AGENTS.md lists as the pre-review step.
  • Problem: src has no runnable doctests: the only fences are ignore, json and text. cargo test still runs rustdoc --test, which parses and expands the whole 657k-line lib. src/main.rs has no tests, yet cargo test builds and links a test harness for the bin against the full lib, adding one more large link.
  • Fix: Add [lib] path = "src/lib.rs" with doctest = false, and test = false on the [[bin]] aoe target. Update the CI command nextest run --lib --bins to drop --bins if needed.
  • Verifier: main.rs has no tests, and lib doctests are only ignore or text fences (task_util.rs:28), so doctest=false is safe. But CI uses nextest, which skips doctests, so the win is local cargo test only. test=false on the bin conflicts with CI --bins at tests.yml:377-383.
  • Measure: time cargo test --lib with and without doctest=false; check target/debug/deps for the aoe bin test harness link.

#374 e2e-tests and web features fork the lib build; CI and local runs compile the 657k-line crate per feature set

  • Impact low, effort M, verdict partly, evidence proven-by-code, area rust-build, category compile-time
  • Where: Cargo.toml:218-238, src/agents.rs:991-995, src/tui/app.rs:518, src/tui/home/status.rs:184, AGENTS.md (Commands section)
  • Frequency: Every switch between cargo test and cargo test --features e2e-tests --test e2e (or web). Each feature set is a full lib plus bin compile.
  • Problem: A package feature changes the lib hash even when unused. e2e-tests gates about 10 test hooks in lib code (fake-agent AgentDef, runtime_settled reporter). This is deliberate, to keep hooks out of release, but it forces a full second compile to run e2e. AGENTS.md already warns about disk cost.
  • Fix: Replace the feature gate on the e2e target with [[test]] name = "e2e" test = false, so plain cargo test skips it and --test e2e runs it. Move the lib hooks behind a runtime check of an AOE_E2E env var read once into a LazyLock<bool>. Accept the small shipped code in exchange for one lib build.
  • Verifier: There are 16 cfg(e2e-tests) sites. CI already avoids the fork: tests.yml:113 builds lib, integration and e2e in one web,e2e-tests set, and the macOS job uses e2e-tests for every step. Only local switching pays the extra build. fake-agent sits in the static AGENTS slice with index-stability concerns, so a runtime gate would ship it and need filtering everywhere.
  • Measure: Locally: cargo test --no-run, then time cargo test --features e2e-tests --test e2e --no-run

#375 Release profile uses fat LTO with codegen-units=1 on a 657k-line crate

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area rust-build, category ci-time
  • Where: Cargo.toml:276-279, .github/workflows/build-binaries.yml:143, .github/workflows/nightly.yml:9
  • Frequency: Per release tag and per nightly (cron daily when enabled), across 4 targets. Also any local cargo build --release.
  • Problem: lto = true (fat) with cgu=1 serializes LLVM optimization of the whole program on one core. For this crate size that is likely the largest part of release build wall time. The binary size gain over thin LTO is typically a few percent.
  • Fix: Set lto = "thin" and keep codegen-units = 1, or lto = "fat" with codegen-units = 16. Measure ls -l target/release/aoe and build time once on build-binaries.yml before and after, and keep fat only if the size delta matters.
  • Verifier: Fat LTO with cgu=1 is confirmed (Cargo.toml:276-279), used by build-binaries.yml:143 on release tags only. Tests use dev profiles, so PR CI is unaffected. Win applies only to release and nightly wall time; binary size and perf tradeoff is unmeasured.
  • Measure: Time cargo build --release --features web with lto=true vs lto=thin; compare ls -l target/release/aoe sizes.

4.rust-tests

#376 Five default-key #[serial] e2e tests drain the 6-thread e2e pool

  • Impact low, effort S, verdict partly, evidence proven-by-code, area rust-tests, category test-time
  • Where: tests/e2e/filewatch_tui_dynamic_profile.rs:14, tests/e2e/filewatch_tui_dynamic_profile.rs:35-48, tests/e2e/filewatch_tui_dynamic_profile.rs:88, tests/e2e/filewatch_tui_reload.rs:17, tests/e2e/filewatch_tui_reload.rs:67-78, tests/e2e/update_command.rs:9, tests/e2e/update_command.rs:58-65, tests/e2e/harness.rs:55-86, .github/workflows/tests.yml:112-117
  • Frequency: Every e2e run (web-e2e leg, macOS acp_ subset, local). Five barrier events per run, each held for the whole TUI test (filewatch_tui_reload waits up to 7s on the 5s heartbeat).
  • Problem: A default-key #[serial] test waits for every running #[parallel] test to finish and blocks new ones from starting. With --test-threads=6, each of these tests drains the pool. The filewatch tests need serial only because HomeGuard sets HOME so an in-process Storage::new can write sessions.json. update_command needs it only for AOE_UPDATE_BASE_URL.
  • Fix: In both filewatch files, drop HomeGuard and Storage. Write profiles/

    /sessions.json with std::fs::write, as filtered_profile_switch already does at line ~96. Then mark the tests #[parallel]. Give update::install::update_via_tarball a base_url parameter (the CLI passes the env value), or move the test to an in-module tokio test. Then delete HomeGuard.

  • Verifier: Four default-key #[serial] tests, not five (dynamic_profile x2, tui_reload, update_command). HomeGuard is only needed for the in-process Storage writes; h.run_cli(add -p profile) or raw fs::write would work. update_command is in-process and short, so its drain costs little. Lib test already covers the URL override.
  • Measure: Run the e2e binary with --test-threads=6 and log per-test start/end; sum idle thread-seconds around the serial tests.

#377 cli_launch_waits_for_a_hook_beyond_the_read_timeout busy-waits a fixed 20s negative window

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area rust-tests, category test-time
  • Where: tests/e2e/cli.rs:2217-2290, tests/e2e/cli.rs:2268-2276, src/daemon/mod.rs:58, .github/workflows/tests.yml:182-186
  • Frequency: Every e2e run. It costs at least 20s of one test thread. It runs in both the web-e2e leg and the bare-core leg, because the cli:: filter selects it.
  • Problem: To prove the CLI outlives the 15s DaemonClient DEFAULT_TIMEOUT, the test loops for a fixed 20s while checking that the child has not exited. It then releases the hook. The 20s is pure wall time on every run, and bare-core runs it with only 3 threads.
  • Fix: Add a debug-only env override for daemon::DEFAULT_TIMEOUT, for example AOE_DAEMON_CLIENT_TIMEOUT_MS read under cfg(debug_assertions). Set it to 1000 through h.set_env in this test and shrink the window to 2s. The timeout choice itself is already unit-tested with tokio::time::advance (src/daemon/mod.rs:1889).
  • Verifier: #[parallel] test at tests/e2e/cli.rs:2216 busy-polls a fixed 20s window against the 15s DEFAULT_TIMEOUT (src/daemon/mod.rs:58). bare-core filter cli:: runs it with 3 threads. Costs about 20s of one thread per run; wall impact is small unless it sits on the critical path.
  • Measure: cargo test --features e2e-tests --test e2e -- cli_launch_waits_for_a_hook --exact; record duration before and after the override.

#378 Every e2e harness home runs all 57 data migrations from v0, with one fsynced write per migration

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area rust-tests, category test-time
  • Where: tests/e2e/harness.rs:432-531, tests/e2e/harness.rs:1339-1352, src/migrations/mod.rs:424-498, src/migrations/mod.rs:550-556, src/session/storage.rs:176-199
  • Frequency: Once per TuiTestHarness (257 constructions in tests/e2e) on the first aoe process: TUI, CLI, or autostarted daemon. Scales with the migration count, which grows over time.
  • Problem: with_home seeds config.toml but no .schema_version, so the first aoe invocation takes the lifecycle transaction and runs every migration. set_version calls atomic_write (file sync_all plus dir fsync) after each one. The harness itself documents that this can exceed 10s on loaded CI and raised wait_for_ready to 30s to cover it. Fresh-install migration is already covered by tests/integration/migration_pipeline.rs.
  • Fix: In TuiTestHarness::with_home, write config_dir/.schema_version = agent_of_empires::migrations::current_schema_version(). Tests that exercise migrations already overwrite it (cli.rs:1983). Then lower wait_for_ready back toward the default timeout.
  • Verifier: Claim holds: get_current_version returns 0 without .schema_version, so each pending migration runs and set_version fsyncs. But a real fresh install takes this same path, so the harness mirrors users. 57 tiny fsyncs are likely well under 1s; the 30s budget comment blames loaded CI, not proven fsync cost.
  • Measure: Time aoe list on a fresh isolated HOME with and without a pre-seeded .schema_version, on the CI runner.

#379 argon2 runs unoptimized in tests and debug daemons

  • Impact low, effort S, verdict confirmed, evidence plausible-needs-measurement, area rust-tests, category test-time
  • Where: Cargo.toml:161, Cargo.toml:263-274, src/server/login.rs:97-114, src/server/login.rs:1389-1690, src/server/passkeys.rs:229-244, src/server/auth.rs:1249
  • Frequency: Each LoginManager::new(Some(..)) / with_persistence / PasskeyManager::with_persistence call (about 34 test sites in src), each argon2_verify login, and every e2e daemon started with --passphrase (for example serve_lock.rs:372).
  • Problem: The dev profile keeps dependencies at opt-level 0, so Argon2::default() (19 MiB, t=2) hashing and verification run as unoptimized code. Each hash takes much longer than in release. Tests that rotate or reload passphrases hash several times per test.
  • Fix: Add [profile.dev.package.argon2] opt-level = 3 and [profile.dev.package.blake2] opt-level = 3 to Cargo.toml. These crates are small, so the compile cost is negligible. This speeds up unit tests and debug-binary e2e daemons that use passphrases.
  • Verifier: login.rs:97-113 uses Argon2::default() (19 MiB, t=2). Cargo.toml has only [profile.dev.package."*"] debug=false, with no opt-level override. That makes about 56 hash/verify call sites in src+tests, plus e2e daemons started with a passphrase, run unoptimized argon2/blake2. The fix is safe because the crates are small. The wall-clock win is spread across parallel nextest processes.
  • Measure: Time one test, e.g. cargo nextest run login::tests before and after adding [profile.dev.package.argon2] and [profile.dev.package.blake2] opt-level=3.

#380 Lib doctest pass runs on every cargo test though the crate has no runnable doctests

  • Impact low, effort S, verdict confirmed, evidence plausible-needs-measurement, area rust-tests, category dev-loop
  • Where: Cargo.toml:291-303, AGENTS.md:71-73
  • Frequency: Every local cargo test without target filters. Scales with crate size (about 657k lines in src).
  • Problem: Every fenced block in src doc comments is ignore, text, or json; none runs. AGENTS.md already says to write examples as unit tests, and nextest in CI skips doctests. Plain cargo test still invokes rustdoc --test over the whole crate, which costs extra minutes on a crate this size.
  • Fix: Add a [lib] table with doctest = false to Cargo.toml (keep the existing name and path defaults).
  • Verifier: src/lib.rs exists and Cargo.toml has no [lib] table. The only fenced blocks are tagged ignore, json or text, and the 4 bare fences are closing fences, so zero doctests run. CI uses nextest or --lib/--test filters, so only local plain cargo test pays the rustdoc pass over 657k lines. Adding [lib] doctest=false is safe.
  • Measure: Run cargo test --doc with the build warm and time the rustdoc pass.

#381 The e2e-tests feature changes the lib, so running e2e after cargo test recompiles the whole crate

  • Impact low, effort M, verdict partly, evidence proven-by-code, area rust-tests, category compile-time
  • Where: src/agents.rs:990-995, src/tui/app.rs:518-519, src/tui/home/status.rs:184-190, src/tui/remote_home/mod.rs:179-187, src/tui/structured_view/mod.rs:350-366, Cargo.toml:229-235
  • Frequency: Each local switch between cargo test and cargo test --features e2e-tests --test e2e, plus disk for a second full target copy (AGENTS.md:46-53 warns about this).
  • Problem: Ten cfg(feature = "e2e-tests") sites sit in src (the fake-agent AgentDef and the runtime-state reporter). Any e2e run therefore builds the lib and bin at a different feature hash from the default test build. That doubles crate compiles and target size for developers who run both suites.
  • Fix: Gate these sites with cfg(debug_assertions) plus the runtime env check the harness already sets (AOE_E2E_RUNTIME_STATE; add AOE_E2E_FAKE_AGENT for the AgentDef, filtered in agents()). Remove the feature's effect on the lib, so e2e-tests only gates the [[test]] target.
  • Verifier: The cfg sites are real (agents.rs:991,2653; app.rs; status.rs; remote_home; structured_view; agent_registry.rs:200). But the proposed fix does not stop the recompile. Cargo hashes the lib unit on the package's activated feature set, so enabling e2e-tests still rebuilds the lib even when no code reads the feature. The win needs the feature removed entirely, e.g. an env-gated e2e target. CI jobs already use one feature set each.
  • Measure: After cargo test, run cargo test --features e2e-tests --test e2e --no-run -v and count 'Compiling agent-of-empires' or fresh lines.

#382 Two standalone test binaries each link the full lib for one test

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area rust-tests, category compile-time
  • Where: tests/branch_exists_spawn_failure.rs:55-123, tests/filewatch_degradation.rs:35-61, tests/integration/main.rs:8-12
  • Frequency: Every test build (CI core-rest, macOS, local). Each adds one full debug link of agent_of_empires plus its dependencies.
  • Problem: Both files stay out of the consolidated integration binary only because they mutate PATH or AOE_FILE_WATCH process-wide. The integration main.rs says consolidation was done because separate links are costly. These two cost an extra link and test binary each for a single fast test.
  • Fix: Add seams. FileWatchService::new_with(enabled: bool), which new() calls with the env read, and a git program parameter on the run_git path used by GitWorktree::branch_exists (the test passes a nonexistent path). Then move both cases into in-module unit tests and delete the two files.
  • Verifier: Both files exist and are isolated by design (PATH, AOE_FILE_WATCH). The file_watch seam is trivial (env read at file_watch.rs:259). branch_exists calls run_git_with_timeout with hardcoded git, and the test also covers edit_worktree_workdir, so a program seam is invasive. Win is one or two debug links.
  • Measure: cargo build --timings --tests, read link time of the two test binaries; or compare cold cargo test --no-run with and without them.

#383 Harness Drop always spawns aoe acp stop --all and aoe serve --stop for spawned harnesses

  • Impact low, effort S, verdict partly, evidence proven-by-code, area rust-tests, category test-time
  • Where: tests/e2e/harness.rs:1664-1687, src/cli/acp.rs:848-868, src/cli/serve.rs:2740-2760
  • Frequency: Once per harness that spawned a TUI (103 spawn_tui sites) or set stop_daemon_on_drop. Two full debug-binary execs each.
  • Problem: When spawned is true, Drop runs acp stop --all even with an empty worker registry, and runs serve --stop even with no serve.pid. Each one starts a full debug aoe process (clap, config, logging) only to find nothing to do.
  • Fix: In TuiTestHarness::drop, run acp stop --all only when app_dir/acp-workers holds a *.json record. Run serve --stop only when app_dir/serve.pid exists, and drop the || self.spawned term.
  • Verifier: Drop does run acp stop --all and serve --stop whenever spawned, and acp stop prints 'No matching agent workers' when the registry is empty. But a TUI can auto-start the daemon, so serve.pid is often present and the serve skip rarely applies. Saves about one debug exec per harness, run in parallel.
  • Measure: Time Drop with Instant around the two cli_command calls across the e2e suite, or run strace/dtruss -c on exec counts.

#384 Harness wait helpers poll every 100ms, each poll forking tmux

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area rust-tests, category test-time
  • Where: tests/e2e/harness.rs:1379-1394, tests/e2e/harness.rs:1397-1412, tests/e2e/harness.rs:1363-1376, tests/e2e/harness.rs:1572-1586, tests/e2e/harness.rs:218-232, tests/e2e/harness.rs:1416-1429
  • Frequency: Per wait call: 265 wait_for( sites plus wait_for_absent, wait_for_runtime_ready, wait_for_exit, and wait_for_port (34 start_daemon) across the e2e suite.
  • Problem: Each unsatisfied wait adds about 50ms of average latency after the condition becomes true. assert_screen_contains also sleeps 200ms between its 5 retries. wait_for_input_ack already shows 10ms polling is fine. Across hundreds of waits per run, this adds tens of seconds of thread time.
  • Fix: Use one POLL = Duration::from_millis(20) constant in wait_for_timeout, wait_for_absent, wait_for_runtime_ready, wait_for_exit, and wait_for_port. Use 50ms in assert_screen_contains.
  • Verifier: Polls are 100ms and fork tmux capture each time, as claimed. Lowering to 20ms multiplies tmux forks 5x across parallel tests, risking CPU contention and flakiness on CI. Latency saving is about 50ms per wait. Moderate change (50ms) is safer; wait_for_port and wait_for_runtime_ready are cheap to speed up.
  • Measure: Run e2e with the poll constant at 100, 50 and 20ms, compare total wall time and flake rate over 5 runs.

#385 prompt_until_accepted re-execs the aoe binary every 250ms and is duplicated

  • Impact low, effort S, verdict partly, evidence proven-by-code, area rust-tests, category test-time
  • Where: tests/e2e/harness.rs:767-788, tests/e2e/serve.rs:3722-3738, tests/e2e/fork_structured_e2e.rs:66-81
  • Frequency: 12 prompt_until_accepted call sites, each polling until the ACP worker handshakes (often several seconds).
  • Problem: Each retry is a full aoe acp prompt process, and the 250ms sleep adds about 125ms of average latency per call. serve.rs keeps a private copy of the same loop, and fork_structured_e2e polls sessions.json at 250ms.
  • Fix: Delete the serve.rs copy and call TuiTestHarness::prompt_until_accepted. Cut the sleep to 50ms in that helper and in fork_structured_e2e's acp-id wait.
  • Verifier: The serve.rs prompt_until_accepted is a real duplicate of the harness helper (differs only in message text and prompt), so dedup is valid. But each retry costs a full process exec, so shortening the sleep to 50ms mostly adds exec load. Saves about 125ms per call at best; fork_structured poll of sessions.json is cheap to shorten.
  • Measure: Count retries per prompt_until_accepted call by logging loop iterations during an e2e run; check iteration time versus the 250ms sleep.

#386 node_executable() spawns node on every require_node! and install_acp_shim

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area rust-tests, category test-time
  • Where: tests/e2e/harness.rs:131-158, tests/e2e/harness.rs:620-631, tests/integration/common/mod.rs:49-70
  • Frequency: 27 require_node! plus 18 install_acp_shim calls per e2e run, each a full Node startup (tens of ms).
  • Problem: Each ACP test runs node -p process.execPath twice. The integration crate already caches this in a OnceLock (common::shim_node). require_tmux! similarly forks tmux -V per test.
  • Fix: Cache node_executable() and tmux_available() results in static OnceLock values in harness.rs, the same way common::shim_node does.
  • Verifier: node_executable() spawns node uncached at harness.rs:131, called by node_available (require_node!) and install_acp_shim (line 631); tmux_available spawns tmux -V per test. OnceLock is safe. Win is about 45 node starts times tens of ms, spread across parallel tests; no benefit if e2e runs one process per test.
  • Measure: hyperfine 'node -p process.execPath' for per-call cost, multiply by 45; or add a counter and run the e2e suite.

#387 No nextest config: no slow-timeout, terminate-after, or threads-required

  • Impact low, effort S, verdict partly, evidence proven-by-code, area rust-tests, category ci-time
  • Where: .github/workflows/tests.yml:157-168, .github/workflows/tests.yml:375-385
  • Frequency: Every core-rest and macOS nextest run.
  • Problem: There is no .config/nextest.toml. A hung test (daemon, node shim, tmux) runs until the job timeout (90 min on macOS) instead of failing in seconds. Heavy integration tests (acp_, cli_read_) run at full CPU parallelism next to lib tests, with no throttling.
  • Fix: Add .config/nextest.toml with [profile.default] slow-timeout = { period = "30s", terminate-after = 4 }. Add an [[profile.default.overrides]] filter 'test(/^acp_/) | test(/cli_read_/)' with threads-required = 2.
  • Verifier: No .config/nextest.toml exists, but core-rest already has a 40 min job cap. macOS (90 min) uses nextest only for lib/bins/cli_read_daemon; its acp e2e step uses cargo test, so the config would not cover it. A 2 min terminate-after risks killing slow legit tests; threads-required slows runs.
  • Measure: Pull nextest JUnit/timing from recent core-rest runs; list tests over 30s and the longest test duration before choosing a slow-timeout.

#388 Fixed sleeps in tool_sessions and acp_live_e2e retry loops

  • Impact low, effort S, verdict partly, evidence proven-by-code, area rust-tests, category test-time
  • Where: tests/e2e/tool_sessions.rs:150-161, tests/e2e/tool_sessions.rs:184-185, tests/e2e/acp_live_e2e.rs:176-190, tests/e2e/plugin_command_executor_e2e.rs:184-195
  • Frequency: Per run of these tests. acp_live_e2e and plugin_command_executor loop up to 20s in 300 to 500ms steps.
  • Problem: tool_sessions sleeps 150ms before assert_screen_contains, which already retries. The 200ms sleep before a negative assertion has no causal precondition, while send_keys already fences on the input barrier. acp_live presses a and waits 300ms against a 1Hz poll, and plugin_command resends every 500ms.
  • Fix: Delete both tool_sessions sleeps; send_keys/type_text already synchronize the render. In acp_live_e2e, wait_for the approval marker on the home row before pressing a once. In resend_until_file_contains, wait_until the file appears with 50ms polling before resending.
  • Verifier: The 150ms sleep before assert_screen_contains is redundant, since that helper retries 5x200ms. The 200ms negative-assert sleep is arguably a deliberate render window: the input barrier acks input, not render. Loops in acp_live and plugin_command are poll-bound and save under 1s each.
  • Measure: Run the three tests with timing (cargo test --features e2e-tests --test e2e tool_sessions -- --report-time) before and after removing the sleeps.

4.web-tests

#389 Vitest typecheck mode is always on, spawning tsc on every vitest run

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-tests, category dev-loop
  • Where: web/vite.config.ts:52-56, web/tsconfig.vitest.json, web/src/lib/__tests__/acpTypes.types.test.ts:1-16
  • Frequency: Every npm run test:unit run, local and CI (vitest job); also each watch restart. Scales with production source reachable from acpTypes.ts.
  • Problem: test.typecheck.enabled: true makes vitest launch a separate tsc process over tsconfig.vitest.json (extends the app config with DOM libs) to check one 16-line file. That is a full TS program build, a few seconds of CPU, on every unit run, even when only one test is targeted.
  • Fix: Set typecheck.enabled to false in vite.config.ts and run vitest run --typecheck.only in one CI step, or fold tsconfig.vitest.json into npm run typecheck:tests.
  • Verifier: typecheck.enabled is true and spawns tsc over the app program for a 16-line file. But it runs in parallel with the test workers and typecheck:tests already runs separately in ci.yml. Targeted runs that skip the types file likely skip tsc. Win is a few seconds of CPU.
  • Measure: Time npx vitest run with and without --typecheck.enabled=false, and compare CI vitest job duration.

#390 Setup file loads RTL and react-dom for every file, including node-environment tests

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-tests, category test-time
  • Where: web/src/test-setup.ts:1-9, web/vite.config.ts:57
  • Frequency: Once per test file (vitest isolates each file), ~417 times per run. Node-only files are the ~114 without a jsdom docblock.
  • Problem: setupFiles statically imports @testing-library/react (react, react-dom, dom-testing-library) and fake-indexeddb/auto before any test, even for pure-logic files in the node environment where cleanup() is a no-op. Those modules are re-evaluated in every isolated worker context.
  • Fix: In test-setup.ts, gate on typeof document !== 'undefined' and await import('@testing-library/react') to register the afterEach cleanup only for jsdom files. Load fake-indexeddb only in tests that need it.
  • Verifier: Setup does import RTL and fake-indexeddb for every file, and 112 files lack a jsdom docblock. But node_modules are externalized and cached. Cost is tens of ms per file, mostly parallel. Gating risks breaking tests that rely on indexedDB or auto cleanup.
  • Measure: Run vitest with --reporter=verbose and compare the 'setup' column for node-env files before and after gating.

#391 SessionWizard tests wait on real 800 ms and 1 s timers

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area web-tests, category test-time
  • Where: web/src/components/session-wizard/__tests__/SessionWizard.test.tsx:741-754, web/src/components/session-wizard/__tests__/SessionWizard.test.tsx:763-767, web/src/components/session-wizard/__tests__/SessionWizard.test.tsx:909, web/src/components/session-wizard/__tests__/SessionWizard.test.tsx:984, web/src/components/session-wizard/__tests__/SessionWizard.test.tsx:1924, web/src/components/session-wizard/SessionWizard.tsx:141-148, web/src/components/session-wizard/SessionWizard.tsx:706
  • Frequency: Every vitest run: about 6 tests each pay PROGRESS_DELAY_MS=800 ms of real time to reach 'Continue in background', plus a 1000 ms real retry backoff in the test at line 763.
  • Problem: The progress panel appears after a real setTimeout of 800 ms and retries back off 1000*(attempt+1) ms. The 'create progress' describe uses real timers with {timeout: 3000} waits. This 2238-line file bounds the slowest-file floor of the vitest job. Other describes in the same file already use fake timers.
  • Fix: Use vi.useFakeTimers() in the 'SessionWizard create progress' describe and call vi.advanceTimersByTimeAsync(800) (1000 for the retry case) instead of findByText(..., {timeout: 3000}).
  • Verifier: PROGRESS_DELAY_MS=800 and a 1000*(attempt+1) retry backoff are real timers. The create-progress describe uses real timers with timeout 3000. Other describes already use fake timers with shouldAdvanceTime, and the wizard mixes polls with fetch mocks, so conversion is easy but saves only a few seconds in one file.
  • Measure: Run npx vitest run SessionWizard.test.tsx --reporter=verbose and read the per-test durations for the progress tests.

#392 check-env-isolation scans 25 MB of Rust twice per file and runs in both lint and vitest

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-tests, category ci-time
  • Where: web/scripts/check-env-isolation.mjs:1-17, web/scripts/check-env-isolation.mjs:100-126, web/scripts/check-env-isolation.mjs:178-200, web/tests/helpers/isolatedEnv.test.ts:126-130, web/package.json:12
  • Frequency: Twice per CI run (web-lint via npm run lint, vitest job via isolatedEnv.test.ts), plus every local lint and unit run. Scales with Rust source size (733 files, ~25 MB).
  • Problem: The script reads every .rs file, then calls inventorySource(source, true) and inventorySource(source, false) per file; each runs a masking regex over the full text. It also loads the whole typescript package to transpile one helper. The vitest case needs a 30 s budget in a child process. AGENTS.md says the duplication is deliberate.
  • Fix: Mask each file once and derive both inventories from the same masked text in the loop at lines 100-126. Replace ts.transpileModule with a direct import of the helper. Export a function so the vitest case calls it in-process.
  • Verifier: Real: 733 files, 25 MB, regex masking twice per file, run in lint and in isolatedEnv.test.ts. But web/AGENTS.md deliberately keeps both invocations. The scan likely takes about 1 s, and the 30 s timeout is only a ceiling. A single-pass mask is a small win.
  • Measure: Run time node web/scripts/check-env-isolation.mjs in web/.

#393 Live harness teardown polls full ps -ax synchronously in 50 ms loops

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area web-tests, category test-time
  • Where: web/tests/helpers/aoeServe.ts:243-262, web/tests/helpers/aoeServe.ts:329-337, web/tests/helpers/aoeServe.ts:403-408, web/tests/helpers/aoeServe.ts:355-375
  • Frequency: Per live test (161 tests, 6 parallel workers in CI) at teardown, plus once per runner record. Scales with host process count, which is high with 6 Chromium workers and 6 daemons.
  • Problem: processSnapshot runs spawnSync('ps', ['-ww','-axo',...]) over the whole host, blocking the worker event loop. stopOrphanRunners calls it once per runner record, then every 50 ms until groups exit (up to 25 s). stopTerminalProcesses repeats it for up to 4 s.
  • Fix: In processSnapshot, scope to known pids with ps -o ... -p <pids> or pgrep -g. Use async execFile in the poll loops and back off from 50 ms to 200 ms. Snapshot once before the loop in stopOrphanRunners instead of per record.
  • Verifier: processSnapshot is synchronous ps -axo, polled every 50 ms, and called per runner record inside the loop. But a ps over a few hundred processes takes about 10-30 ms. Wait time is dominated by watchdog exit, not ps. Scoping by pid is risky because the code deliberately discovers orphans by command prefix.
  • Measure: Wrap processSnapshot with performance.now() logging and sum the time per teardown in a live run.

#394 Every live test spawns a new aoe daemon, shims and isolated HOME

  • Impact low, effort L, verdict partly, evidence plausible-needs-measurement, area web-tests, category test-time
  • Where: web/tests/helpers/liveTest.ts:77-92, web/tests/helpers/aoeServe.ts:370-420, web/tests/helpers/aoeServe.ts:630-700, web/playwright.live.config.ts:5-9
  • Frequency: Per live test: 161 tests, fullyParallel: true, 6 workers in CI. Pays HOME and shim creation, daemon boot (debug binary), readiness polling at 100 ms, then SIGTERM and runner teardown.
  • Problem: The serve, serveAcp fixtures are test-scoped. Read-only specs (listing, display, navigation) do not need a fresh daemon. Readiness polls every 100 ms and seedFn runs aoe add through spawnSync of the debug binary per seeded session. The debug-build choice is justified in CI (2 min vs 6 min).
  • Fix: Add worker-scoped fixtures ({scope:'worker'}) in liveTest.ts for specs that only read state. Batch repeated seeds into one aoe add or write sessions directly. Lower the waitForServer poll interval (aoeServe.ts ~line 461) to 25 ms.
  • Verifier: Per-test daemon is real, but about 94 of 175 fixture uses are spawnServe with custom options, and most specs mutate state. A worker-scoped daemon would break the isolation the fixture promises. Lowering the 100ms poll to 25ms saves about 50ms per spawn, which is negligible. Batching seeds is the only cheap lever: each seedFn runs aoe add and then serve --stop.
  • Measure: Time spawnAoeServe phases (seedFn, stopSeedDaemon, waitForServer, cleanup) per test and sum them across a CI live run.

#395 Per-test V8 coverage dump and merge across ~620 Playwright tests

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area web-tests, category ci-time
  • Where: web/tests/helpers/coverageCapture.ts:30-70, web/tests/helpers/mockedTest.ts:57-60, web/scripts/merge-coverage.mjs:55-90, .github/workflows/tests.yml:526-558
  • Frequency: Per mocked test (461) and per live test (161) in CI, plus one monocart merge after each job. Scales with bundle size and test count.
  • Problem: page.coverage.startJSCoverage collects detailed block coverage, and each test serialises function range data for every app script to its own JSON file. The merge step reloads and remaps all of them against sourcemaps. The source payload and external sourcemaps were already optimised, so this is the remaining cost.
  • Fix: In coverageCapture.ts, accumulate per worker with a worker-scoped fixture and write one file per worker, merging with monocart add(), instead of ~620 files. Confirm file count and total size in CI before changing.
  • Verifier: Real but small: source is already stripped, so each file holds only function ranges. Cost is mostly V8 detailed-block collection and monocart remap, not file count. Worker-scoped merge would need cross-page range merging and loses data on worker crash. Only runs in coverage jobs.
  • Measure: In CI, time the 'coverage:merge' step and run 'du -sh web/coverage/playwright; ls | wc -l'; compare Playwright job with AOE_COVERAGE unset.

#396 web is built and type-checked in four separate CI jobs

  • Impact low, effort M, verdict partly, evidence proven-by-code, area web-tests, category ci-time
  • Where: .github/workflows/tests.yml:111-113, .github/workflows/tests.yml:497-501, .github/workflows/tests.yml:526-530, .github/workflows/tests.yml:636-644, web/package.json:7, build.rs:157-170
  • Frequency: Every CI run: web-e2e cargo leg (build.rs runs npm run build), bundle-analysis, playwright mocked, and playwright live (cargo build, so build.rs again). Each runs tsc -b && vite build after its own npm ci.
  • Problem: Four runners repeat tsc -b plus the vite production build. bundle-analysis and playwright-mocked differ only by AOE_COVERAGE, and tsc -b output is the same in all four.
  • Fix: Run tsc -b once in the web-lint job and add a build:bundle script (vite build only) used by test jobs and build.rs; keep tsc -b in build for local use. Alternatively upload web/dist from one job for bundle-analysis to reuse.
  • Verifier: Builds repeat in web-e2e, bundle-analysis, mocked, live, but they differ by env (coverage, inline maps, Codecov plugin), so artifacts are not shareable. web-lint does not run tsc -b, only typecheck:tests. AOE_WEB_DIST already lets build.rs reuse a prebuilt dist. Win is only tsc time (tens of seconds).
  • Measure: Time 'tsc -b' versus 'vite build' separately in a CI run via 'time npx tsc -b' and 'time npx vite build'.

#397 Vitest CI coverage emits html and text reporters CI does not consume

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-tests, category ci-time
  • Where: web/vite.config.ts:58-61, .github/workflows/tests.yml:413-414, .github/workflows/tests.yml:465-468
  • Frequency: Once per CI vitest job; scales with covered file count (include: src/** also instruments untested files).
  • Problem: Reporters are text, json, html, lcov. CI uses only lcov.info and coverage-final.json (merge script). The text reporter prints a full table for all files into the log, and html writes a page per file that is then uploaded as an artifact.
  • Fix: Set reporter: process.env.CI ? ['json','lcov'] : ['text-summary','html'] in the coverage config in vite.config.ts and upload only json and lcov.
  • Verifier: Reporters text and html are not read by merge script (it uses coverage-final.json) or Codecov (lcov). But html is uploaded as a 14-day debug artifact, and text is log noise. Saving is seconds of report writing; dropping them removes the artifact people may use.
  • Measure: Run 'npm run test:unit -- --coverage' with and without html/text reporters and compare wall time and du of coverage/vitest.

#398 ESLint runs over all tests with no cache

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-tests, category dev-loop
  • Where: web/package.json:12, web/eslint.config.js:10-75
  • Frequency: Every npm run lint locally and the web-lint CI job; scales with ~417 unit tests and ~130 Playwright specs (30k+ lines of tests).
  • Problem: eslint . lints all test files cold on every run with no --cache. The react-hooks compiler rules and react-you-might-not-need-an-effect run on source. typescript-eslint uses non type-aware recommended, so cost is moderate, but local reruns repeat all work.
  • Fix: Change the lint script to eslint . --cache --cache-location node_modules/.cache/eslint. Optionally add a changed-files lint script.
  • Verifier: eslint has no --cache; true. But CI runs it once on a fresh checkout so the cache gives no CI win. Only local reruns benefit, and flat config changes invalidate it. Needs .eslintcache or cache-location gitignored. Local-only low win.
  • Measure: In web/, run 'time npx eslint .' cold, then with '--cache --cache-location node_modules/.cache/eslint' twice.

4.ci-main

#399 Vendored OpenSSL and libgit2 C builds gate the main crate compile in every Rust job (not cached by kache)

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area ci-main, category ci-time
  • Where: .github/workflows/tests.yml:111-113, .github/workflows/tests.yml:159-161, .github/workflows/tests.yml:636-645, Cargo.toml:214-216
  • Frequency: Every Rust job on every PR, queue and push run: 3 cargo-linux legs, playwright-live, clippy, msrv, docs.
  • Problem: kache does not cache build-script runs. Its report lists build_script_run misses of 54s and 31s. Log timestamps for core-rest: openssl-src starts at 17:23:36, but git2 (the last dependency of agent_of_empires) starts only at 17:24:47. That is about 70s of the critical path in each job. aws-lc-sys is also built in parallel (rustls default provider), so two C crypto libraries are compiled.
  • Fix: On Linux test legs and playwright-live set env OPENSSL_NO_VENDOR: '1' and apt-install libssl-dev with liblzma in the rust-toolchain action. This drops openssl-src from the chain. The release and nix builds still exercise vendored. Optionally pick the rustls ring provider to drop aws-lc-sys.
  • Verifier: vendored is a default feature (Cargo.toml:214), and OPENSSL_NO_VENDOR does skip the openssl-src build. It does not remove the libgit2 C build. aws-lc-sys (jsonwebtoken, rustls) also builds in parallel and may become the new critical path, so the saving could be well below 70s. Test legs would also stop matching the shipped config.
  • Measure: Run cargo build --timings with and without OPENSSL_NO_VENDOR=1 on a clean target, then compare when agent_of_empires starts in cargo-timing.html.

#400 bare-core leg recompiles the whole crate at a second feature set just for the no-Node guard

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area ci-main, category ci-time
  • Where: .github/workflows/tests.yml:199-224, .github/workflows/tests.yml:159-161
  • Frequency: Every Tests run (PR, queue, push).
  • Problem: 'Cargo build without a Node toolchain' takes 114s (measured). It builds the lib with default features {default-plugins, vendored}. The bare-core test build used {vendored, e2e-tests}, so the lib and bin compile again. core-rest has already built exactly that default-feature lib and the aoe bin in 'Build tests (default features)'.
  • Fix: Move the guard into core-rest: create the node/npm/npx stubs and prepend them to PATH only for the 'Build tests (default features)' step. The ACP shim npm ci runs in an earlier step. Then drop the bare-core step. This saves about 114s of an 8-vCPU runner per run.
  • Verifier: bare-core builds {vendored,e2e-tests}; the guard's default build is a different feature set, so lib+bin recompile. core-rest's nextest --no-run already builds that default set. build.rs only touches npm under web. Saves runner minutes, not wall time: bare-core is shorter than web-e2e.
  • Measure: Compare bare-core leg duration versus web-e2e and core-rest in recent Actions runs; gh run view --json jobs step timings.

#401 web-e2e builds a full lib-test binary to run five web-gated unit tests

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area ci-main, category ci-time
  • Where: .github/workflows/tests.yml:111-136
  • Frequency: Every Tests run. web-e2e is 502-542s, on par with playwright-live as the critical path.
  • Problem: --lib in 'Build tests (web, e2e)' adds a cfg(test) compile of agent_of_empires with web. kache shows 2 crate compiles, about 3 min and 2 min, run in parallel. The build lasted 202s from git2 start to Finished, with the lib-test as the tail. All that compile serves 'Cargo test (web-gated test blocks)', which ran in 4s.
  • Fix: Drop --lib from the web-e2e build and test steps. Run those 5 lib tests elsewhere: give core-rest a second nextest step only if it already compiles web, or gate them in the clippy job with a cargo test --all-features --lib <filters> using the AOE_WEB_DIST placeholder. This saves about 60s on web-e2e, and is worth it only together with the playwright-live cuts.
  • Verifier: Claim holds: --lib adds a web lib-test compile for 5 filtered tests. But the fix is not feasible: core-rest has no web, and clippy only runs check, so a test run there needs a new compile. Moving tests just moves the cost. Gain is only the tail, if lib-test is last.
  • Measure: Run cargo build --timings for web,e2e-tests with and without --lib; compare wall time and the unit graph tail.

#402 Nix Build jobs start an 8-vCPU RunsOn runner and clone full history just to run git diff and skip

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area ci-main, category ci-time
  • Where: .github/workflows/ci.yml:322-396, .github/workflows/ci.yml:398-457
  • Frequency: Every CI run (PR, queue, push), 2 jobs each. Measured 9-12s each when skipped.
  • Problem: nix-build and nix-build-web each provision a RunsOn 8cpu instance and checkout with fetch-depth: 0, only to find that flake.nix, flake.lock or package-lock.json did not change, which is almost always the case. That is EC2 boot and billing plus a full-history clone for nothing.
  • Fix: Move the 'Detect relevant changes' logic into a ubuntu-latest gate job, using github-script compareCommitsWithBasehead like macos-gate (no full clone). Expose relevant as an output and put needs: [gate] with if: needs.gate.outputs.relevant == 'true' on both RunsOn jobs.
  • Verifier: Both jobs boot an 8cpu RunsOn runner and fetch-depth 0 before a git diff on flake files that rarely change. A ubuntu-latest gate with github-script, as macos-gate does, works. Skipped required checks still pass. Saves about 10-20s of billed EC2 time per job, no wall win.
  • Measure: Read Nix Build and Nix Build Web job durations from gh run view; confirm skipped runs take 9-12s.

#403 MSRV job type-checks the crate twice (core, then web)

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area ci-main, category ci-time
  • Where: .github/workflows/ci.yml:129-142
  • Frequency: Every CI run on an 8-vCPU RunsOn runner.
  • Problem: 'Check the locked graph on rust-version (core)' takes 135-138s and the web check another 63-64s (measured). --features web is a superset of core's dependency graph and code. Only 3 cfg(not(feature = "web")) sites exist in src/, so the core pass adds little MSRV signal.
  • Fix: Drop the core step and keep only cargo +$MSRV check --locked --workspace --features web with the AOE_WEB_DIST placeholder. Alternatively, run MSRV only when Cargo.toml, Cargo.lock or rust-toolchain.toml change, plus always in merge_group.
  • Verifier: Web is a near-superset, but three cfg(not(web)) sites in render.rs, tunnel.rs and mod.rs are only checked by the core pass. Deps compile once and are shared, so dropping core saves only the lib recheck, not 135s. Path-gating is unsafe because std API use can break MSRV from any src change.
  • Measure: Time the web MSRV check alone on a cold target dir versus core then web; compare total seconds.

#404 Bundle Analysis and Codecov uploads run in merge_group, where nobody reads them

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area ci-main, category ci-time
  • Where: .github/workflows/tests.yml:470-497, .github/workflows/tests.yml:428-458
  • Frequency: Every merge_group run (each queue entry, max 5 concurrent).
  • Problem: Bundle Analysis (50-89s, npm ci plus a production build) is not a required check, and its stats matter only on PRs and main. In the queue it repeats PR work. The Codecov coverage and test-results uploads in merge_group also produce reports for a transient gh-readonly-queue branch.
  • Fix: Add github.event_name != 'merge_group' to the bundle-analysis job if. If push runs are trimmed (first finding), keep Bundle Analysis on push for the main baseline.
  • Verifier: Bundle Analysis is absent from the main ruleset's required checks, and the if has no merge_group exclusion, so it repeats PR work per queue entry on ubuntu-latest. Excluding merge_group is safe. Dropping Codecov uploads on queue runs is riskier because of the after_n_builds: 3 setting. Saves minutes, not wall time.
  • Measure: Count merge_group Bundle Analysis runs and durations: gh run list --event merge_group --workflow Tests --json databaseId, then view job times.

#405 Coverage merge writes unused html and v8 reports on the critical-path job

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area ci-main, category ci-time
  • Where: web/scripts/merge-coverage.mjs:223-236, .github/workflows/tests.yml:665-668
  • Frequency: Every Tests run: playwright-live (37s measured) and playwright-mocked (15s).
  • Problem: 'Build LCOV from collected Playwright coverage' runs at the end of the slowest job. Its final CoverageReport also generates v8 and html reports. CI only uploads lcov.info to Codecov, plus the merged dir as an artifact nobody needs for gating. The comment there points at a ci.yml coverage job that no longer exists.
  • Fix: Read an env flag (for example CI) in merge-coverage.mjs and emit only lcov plus json-summary in CI. Leave the full reporter set for local runs. Remove the stale ci.yml reference.
  • Verifier: Claim holds: reporters list v8, html, json-summary, json at merge-coverage.mjs:223-236, and ci.yml has no coverage job or consumer of coverage-summary.json. But merged dir is uploaded as artifact (tests.yml:593, 706), so html is a human debug aid. Win is likely 1-3s per job.
  • Measure: Time npm run coverage:merge in web/ after a live run, with and without v8/html reporters, plus artifact upload step duration from a recent run's logs.

4.ci-other

#406 Release/nightly binaries built with fat LTO + codegen-units=1 on 3-core macOS runners (47-51 min)

  • Impact low, effort M, verdict partly, evidence measured, area ci-other, category ci-time
  • Where: .github/workflows/build-binaries.yml:149, Cargo.toml:[profile.release], Cargo.toml:[profile.dev-release]
  • Frequency: Once per stable release (about every 3-4 days, 4 matrix legs) and once per nightly if enabled (daily). Observed Build step: darwin-arm64 3059s, darwin-amd64 2827s, linux 1383-1443s (run 43669069399). Release wall-clock is gated by the slowest macOS leg.
  • Problem: The whole release is serialised behind a single-threaded fat-LTO link on the slowest runners. Nightly uses the identical profile although nobody needs max-optimised nightlies, and no dependency or rustc cache exists in this workflow.
  • Fix: Add a [profile.nightly] (inherits release, lto="thin", codegen-units=16) and pass --profile nightly from nightly.yml via a build-binaries input. For stable, benchmark lto="thin" vs fat with scripts/bench-startup.py before deciding. Output path changes to target//nightly.
  • Verifier: Nightly is disabled (vars.NIGHTLY_ENABLED unset, every run skipped), so the nightly profile saves nothing today. Stable release took 53 min, gated by macOS (~52 min). Fat LTO for stable is a deliberate size and speed tradeoff; thin LTO needs a binary benchmark first.
  • Measure: Build with CARGO_PROFILE_RELEASE_LTO=thin on macos-latest; compare Build step time, binary size, and scripts/bench-startup.py output.

#407 Web frontend and Node are installed and built 4 times per release, with npm install instead of npm ci

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area ci-other, category ci-time
  • Where: .github/workflows/build-binaries.yml:84-111, .github/workflows/build-binaries.yml:97-105, build.rs:143-150
  • Frequency: Per release and per nightly, in each of 4 matrix legs. Observed 40-58s npm install + 16-30s vite build per leg, plus 34-41s dnf/NodeSource Node install and 37-96s container init on the Linux legs. macOS minutes are the expensive ones.
  • Problem: The identical web/dist is rebuilt 4 times with an unlocked npm install and no npm cache. Linux manylinux containers also install Node 22 from NodeSource just for this. build.rs already supports AOE_WEB_DIST to use a prebuilt dist and skip npm entirely.
  • Fix: Add a web job in build-binaries.yml: setup-node with cache: npm, npm ci, npm run build, upload web/dist artifact. Matrix legs download it and set AOE_WEB_DIST; delete the NodeSource/dnf nodejs step and the macOS setup-node step.
  • Verifier: Verified: 4 legs run npm install and vite build, and build.rs:139-150 accepts AOE_WEB_DIST. The legs run in parallel and the repo is public, so wall-clock savings are about 1-2 min of 53. Switching to npm ci is a correctness gain. A separate web job adds a serial dependency.
  • Measure: Compare release run job durations before and after; gh run view --json jobs for per-step timings.

#408 Docs deploy compiles the whole Rust crate uncached on every src/** push (about 5.5 min)

  • Impact low, effort S, verdict partly, evidence proven-by-code, area ci-other, category ci-time
  • Where: .github/workflows/docs.yml:5-14, .github/workflows/docs.yml:44-48, xtask/Cargo.toml:10, xtask/src/main.rs:328
  • Frequency: Every push to main touching src/, docs/, website/, assets/ (about 6-8 per day). Observed 332s in the Build xtask step (run 43911157638); scales with crate size, since xtask depends on the full agent-of-empires lib.
  • Problem: cargo build -p xtask builds agent-of-empires plus all deps from scratch each run just to emit CLI markdown, a schema and TS declarations. Unlike ci.yml, docs.yml does not use the kache S3 cache. Most src/** pushes cannot change the generated docs.
  • Fix: Add the .github/actions/kache step (job needs id-token: write, which the workflow already has at workflow level) with manifest-key docs. Cheaper still: have docs.yml build only on a git diff of src/cli, src/session/config, src/acp/aoe_meta*, src/daemon/live* instead of all src/**.
  • Verifier: Real but the fix is wrong. gen-docs writes only docs/cli/reference.md, no schema or TS. ci.yml:209-213 already fails PRs whose committed reference.md is stale, so docs.yml can drop Rust toolchain, Build xtask and gen-docs entirely, plus src/** and xtask/** from paths. Runs take 5-6 min, not a required check, public repo.
  • Measure: gh run list -w 'Deploy Website' -L 20 --json createdAt,updatedAt before and after removing the cargo steps.

#409 CodeQL runs on every main push for all 4 languages, including a 13 min Rust analysis

  • Impact low, effort S, verdict partly, evidence measured, area ci-other, category ci-time
  • Where: .github/workflows/codeql.yml:10-14, .github/workflows/codeql.yml:25-35, .github/workflows/codeql.yml:28-31
  • Frequency: Every push to main (about 6-8 per day) plus weekly cron. Observed Rust analysis 801s (run 43911157701), total 10-27 min per push; runs queue behind each other because concurrency has no cancel-in-progress.
  • Problem: The comment says it is not on PRs because Rust alone holds a runner about 15 min, yet it still runs per push. A docs-only or web-only merge still triggers the Rust, Python and actions analyses. Results are not a required check, so latency does not matter.
  • Fix: Add paths-ignore or per-language filters, or drop the push trigger and rely on the weekly cron plus workflow_dispatch. Alternatively add cancel-in-progress: true to the concurrency group so only the newest main commit is analysed.
  • Verifier: Rust analysis 13.6 min, total 11-30 min per main push, confirmed. But concurrency already keeps only one pending run (GitHub cancels older pending), so no unbounded queue. Not required, public repo minutes are free, so no user or CI-visible latency. A single matrix workflow cannot path-filter per language without splitting.
  • Measure: gh run list --workflow codeql.yml -L 50 --json createdAt,updatedAt,conclusion; sum runner minutes per day.

#410 Nix flake builds dependency artifacts twice (web and non-web) and the web frontend source is the whole web/ dir

  • Impact low, effort M, verdict partly, evidence proven-by-code, area ci-other, category ci-time
  • Where: flake.nix:57, flake.nix:105-113, flake.nix:119-122, flake.nix:149-168
  • Frequency: Every cold nix flake check, every nix-build PR job (flake.nix/flake.lock PRs), every cachix-push run when cargoArtifacts miss; Cargo.lock bumps invalidate both.
  • Problem: cargoArtifacts and cargoArtifactsWithWeb are two separate buildDepsOnly runs; the web feature only adds rust-embed and qrcode, so most dependency compilation is duplicated. webFrontend uses src = ./web, so edits to web tests or docs files change its derivation hash and rebuild npm and vite.
  • Fix: Share one dep cache by building cargoArtifacts with --features web and reusing it for aoe, clippy and test (crane tolerates the superset). Restrict webFrontend with lib.fileset.toSource to src, index.html, package*.json, vite/tsconfig and public.
  • Verifier: Two buildDepsOnly sets exist (flake.nix:113,147), but no CI job builds both: PR nix-build builds packages.default, cachix-push builds only aoe-with-web, nix-build-web builds only the frontend. No CI runs nix flake check. Duplication only hurts local flake check. webFrontend src=./web rebuilds on test edits, minor.
  • Measure: time nix flake check -L locally on a cold store, compare with cargoArtifacts built using --features web reused.

#411 Nightly docker job waits for all binary builds and rebuilds unchanged sandbox images daily

  • Impact low, effort S, verdict partly, evidence proven-by-code, area ci-other, category ci-time
  • Where: .github/workflows/nightly.yml:118-125, .github/workflows/nightly.yml:44-60
  • Frequency: Once per nightly (daily when NIGHTLY_ENABLED=true and main moved); currently skipped.
  • Problem: docker has needs: [prepare, build] though the images contain no aoe binary, so it starts after the 50 min macOS builds and adds about 55 min wall-clock. It also rebuilds and pushes both sandbox images every night even when docker/ is unchanged, repeating the QEMU cost.
  • Fix: Change to needs: [prepare] and add a prepare output docker_changed from git diff --quiet $LAST_NIGHTLY_SHA HEAD -- docker/; gate the docker job on it. Plan step already has the last nightly tag.
  • Verifier: needs: [prepare, build] is real, but nightly is off (NIGHTLY_ENABLED gate) and needs: build also propagates the skip and stops pushing images when binaries fail. docker.yml uses cache-from/to type=gha mode=max, so unchanged docker/ is mostly layer cache hits, not full QEMU rebuilds. Dropping build needs an explicit skip condition.
  • Measure: Once nightlies run, compare docker job durations via gh run view --json jobs on nights with and without docker/ changes.

#412 Cargo builds in docs, e2e-recording and build-binaries do not use the repo's kache S3 cache

  • Impact low, effort S, verdict partly, evidence proven-by-code, area ci-other, category ci-time
  • Where: .github/workflows/e2e-recording.yml:42-47, .github/workflows/build-binaries.yml:138-139, .github/actions/kache/action.yml:20-33
  • Frequency: e2e-recording: each time the needs-recording label is added (compiles the e2e test target from scratch). Releases/nightly: every run. Docs: see docs finding.
  • Problem: ci.yml wires .github/actions/kache, but e2e-recording only has the RunsOn S3 action, so cargo test --no-run is a cold full compile. The kache role selector maps non-push-main events (tags, schedule) to the PR role, which is why build-binaries skipped it. Under fat LTO the gain is partial, so this is low priority for releases.
  • Fix: In e2e-recording.yml add permissions: id-token: write and - uses: ./.github/actions/kache with manifest-key e2e-record before Build tests. Skip build-binaries until the profile change above lands.
  • Verifier: e2e-recording has no kache step (tests.yml/ci.yml do) but runs only when needs-recording is labeled, so rarely. Release profile uses lto=true, codegen-units=1, so kache hits are weak. build-binaries skip is right. docs.yml cargo xtask build is the bigger uncached build.
  • Measure: Compare Build tests step duration across recent e2e-recording runs with gh run view; estimate label frequency with gh run list --workflow e2e-recording.yml.

#413 Website and docs builds use unlocked npm install without node cache

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area ci-other, category ci-time
  • Where: scripts/build-site.sh:30, website/package.json:5-9, .github/workflows/docs.yml:40-43
  • Frequency: Every docs.yml run (about 6-8 per day) and every local build-site.sh run.
  • Problem: npm install re-resolves and re-downloads Astro/Tailwind dependencies each run; setup-node has no cache: npm. build-site.sh also duplicates the asset copying done by npm run copy-assets, which npm run build runs again, so assets are copied twice.
  • Fix: Use npm ci in build-site.sh line 30, add cache: npm and cache-dependency-path: website/package-lock.json to the docs.yml setup-node step, and delete the cp block in build-site.sh (steps 1) since npm run build runs copy-assets.
  • Verifier: build-site.sh uses npm install although website/package-lock.json exists; docs.yml setup-node has no cache. Asset cp block is redundant with npm run build's copy-assets (which copies more, so deleting the block is safe). Runs only on path-filtered pushes; saving is seconds.
  • Measure: Compare the Build site step time in recent docs.yml runs before and after adding npm ci and cache: npm.

#414 release-plz installs Rust and does a full-history checkout on every main push and daily cron

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area ci-other, category ci-time
  • Where: .github/workflows/release-plz.yml:75-93, .github/workflows/release-plz.yml:7-12
  • Frequency: Every push to main (about 6-8 per day), daily cron, plus pull_request:closed events that spawn skipped runs for each closed PR. Observed 1.2-2.4 min per run.
  • Problem: Each push does fetch-depth: 0 (all 149k objects, 141 MiB pack) and installs the toolchain although release-plz only needs git history and cargo metadata. Pushes in quick succession each run serially because cancel-in-progress is false.
  • Fix: Keep fetch-depth 0 but add filter: blob:none via a git fetch --filter=blob:none step or a partial-clone checkout input (filter: blob:none). Skip the push trigger when the changed paths are only docs/ or website/ with paths-ignore.
  • Verifier: release-plz genuinely needs full commit history, and fetch-depth 0 is intentional. blob:none could trim the fetch but release-plz diffs packaged files and would refetch blobs lazily. paths-ignore is risky: the release PR must refresh on every main push. Toolchain install is likely cached.
  • Measure: Time the checkout and toolchain steps via gh run view --log on a recent release-plz run; test a filter: blob:none run.

#415 Nightly and rust-toolchain-bump/dependabot-auto-merge check out full history unnecessarily

  • Impact low, effort S, verdict partly, evidence proven-by-code, area ci-other, category ci-time
  • Where: .github/workflows/nightly.yml:44-47, .github/workflows/rust-toolchain-bump.yml:26-28, .github/workflows/dependabot-auto-merge.yml:49-53
  • Frequency: Nightly: daily. Toolchain bump: weekly. Dependabot auto-merge: every opened/synchronize event on a Dependabot PR (about 10 per month, more on bursts).
  • Problem: fetch-depth: 0 clones all 149k objects for jobs that need only tags (nightly Plan, git tag -l, git describe) or one diff. Costs seconds to tens of seconds per run; low impact since these are cheap jobs.
  • Fix: nightly.yml Plan: use fetch-depth: 1 plus git fetch --tags --depth=1, or fetch-tags: true with filter: blob:none. rust-toolchain-bump.yml does not read history at all; remove fetch-depth: 0.
  • Verifier: Claim that rust-toolchain-bump reads no history is wrong: it runs git log HEAD..$OBSERVED_SHA, so it needs history. Nightly uses git describe --tags, which walks commits, so shallow breaks it; only fetch-tags with filter: blob:none is safe. Dependabot fetches the base for a diff. Jobs are cheap.
  • Measure: Compare the Checkout step duration for fetch-depth 0 against filter: blob:none on nightly.yml using gh run view.

#416 Dockerfile has no layer ordering for cache stability: unpinned latest installers and @latest npm in one image

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area ci-other, category ci-time
  • Where: docker/Dockerfile:42-96, docker/Dockerfile.dev:12-51
  • Frequency: Every image build (per release and nightly); runtime impact per pulled image (image size scales with 15+ CLIs, tens of MB each).
  • Problem: Many curl | bash and npm install -g @latest layers sit in a single stage with no BuildKit cache mounts, so a fix to one adapter pin invalidates all later layers. dev image runs apt-get update twice and installs rustup, nvm LTS, uv and bun with no --mount=type=cache, bloating the dev layer.
  • Fix: Reorder so stable layers (apt, nodejs) come first and volatile CLIs last, merge the npm -g installs into one RUN with --mount=type=cache,target=/root/.npm, and merge the two apt-get install blocks in Dockerfile.dev (gh, tmux, unzip) into one.
  • Verifier: Layers are curl installers and npm -g in one stage. Reordering and merging helps only if the build workflow uses a registry or gha layer cache; I found no cache-from or cache-to in .github. Cache mounts would not shrink the final image. Merging npm -g RUNs is cosmetic.
  • Measure: Run docker history on the published image for per-layer sizes; check the docker build workflow for cache-from and cache-to settings.

4.web-bundle

#417 lucide-react/dynamic puts a 1,900-icon import map in the entry and emits ~1,900 chunks

  • Impact low, effort S, verdict partly, evidence measured, area web-bundle, category bundle-size
  • Where: web/src/lib/pluginUi.ts:5-26
  • Frequency: Every cold load (map parsed in entry); binary carries all chunks always.
  • Problem: Importing DynamicIcon and iconNames from lucide-react/dynamic pulls every icon's dynamic import into the entry. Sibling build: 2,394 import() wrappers (~174 KB) plus a 65 KB __vite__mapDeps array in index-*.js, and 1,876 of 2,247 asset files are <2 KB icon chunks embedded in the binary. Only plugins that declare an icon name need this.
  • Fix: In lucideIcon(), load the module lazily: keep a module-level promise import("lucide-react/dynamic") and render a React.lazy wrapper, validating against iconNames after it resolves. Better: restrict plugin icons to a curated static map (e.g. 50 names) imported by name, dropping lucide-react/dynamic entirely.
  • Verifier: Confirmed: the sibling index has a ~1,900-entry DynamicIcon import map, and 1,845 asset files are under 2 KB. But plugins may name any lucide icon (lucideIcon at pluginUi.ts:16 is called from 9 sites), so a curated map breaks the plugin contract. The lazy-import fix needs async validation, and SlotChrome.renders uses it synchronously. That fix saves only about 240 KB raw (about 35 KB gzip). Chunks stay embedded.
  • Measure: grep -o 'import(./[a-z0-9-]*-[A-Za-z0-9_-]*.js)' dist/assets/index-*.js | wc -c, then gzip-compare entry before and after

#418 Startup data fetches wait behind loginStatus round trip

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area web-bundle, category latency
  • Where: web/src/App.tsx:268-321, web/src/App.tsx:371-382, web/src/lib/api.ts:2547-2556
  • Frequency: Every page load / PWA cold launch.
  • Problem: loginStatus() starts in a useEffect after the 2.4 MB entry parses and renders; AppContent (sessions, about, plugins, web UI state) mounts only after it resolves, then refreshAppSettings fires. That is two serial RTTs after JS eval before the session list fetch starts. Over a remote tunnel this adds 100-300 ms to first meaningful paint.
  • Fix: Start loginStatusPromise = loginStatus() at module scope in main.tsx (before createRoot) and consume it in App's effect. When the cached last response said no login required, render AppContent optimistically and kick useSessions/fetchSettings in parallel, falling back to LoginPage on LOGIN_REQUIRED_EVENT.
  • Verifier: The gate is real: AppContent and useSessions mount only after loginStatus() resolves (App.tsx:271-279, 317). The claim of two serial RTTs is wrong because refreshAppSettings runs in parallel with the AppContent mount, so the gate costs one RTT. AppShellSkeleton already paints meanwhile. Moving the call to main.tsx saves only a few ms. The optimistic render conflicts with the documented rule that early reads are rejected on login-walled servers.
  • Measure: Chrome DevTools network waterfall over a remote tunnel; measure the gap between the /api/login/status response and the start of the sessions request.

#419 Fonts and theme-bootstrap.js served with no-cache, revalidated on every load

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area web-bundle, category latency
  • Where: src/server/assets.rs:117-124, web/index.html:17-28, web/src/index.css:2-45
  • Frequency: Every page load: 2 preloaded fonts, up to 4 more on first use, plus the render-blocking theme-bootstrap.js.
  • Problem: cache_control_for gives immutable only to assets/-; /fonts/*.woff2 and /theme-bootstrap.js get no-cache, so each load does conditional requests (304) through the full auth middleware stack. theme-bootstrap.js is a synchronous head script, so its revalidation RTT blocks HTML parsing.
  • Fix: Move fonts into web/src/assets/fonts and reference them relatively in index.css so Vite hashes them (immutable); drop the manual index.html preloads or replace with a Vite plugin emitting hashed preloads. In cache_control_for, give theme-bootstrap.js and fonts/ public, max-age=86400, stale-while-revalidate=604800.
  • Verifier: cache_control_for gives immutable only to assets/; fonts and theme-bootstrap.js get no-cache (304 via ETag). Auth exempts these paths, so middleware cost is small. Real cost is one serial RTT before parse resumes, visible only over remote/tunnel. Short max-age on fonts and the script is safe.
  • Measure: DevTools Network, throttled 150ms RTT: compare theme-bootstrap.js and font 304 timing and FCP before and after adding max-age.

#420 marked + DOMPurify shipped for one memory-recall card despite react-markdown already bundled

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-bundle, category bundle-size
  • Where: web/src/components/acp/NamedToolCards.tsx:6-7, web/src/components/acp/NamedToolCards.tsx:333-335, web/src/components/plugin/BlockMarkdown.tsx:1-30
  • Frequency: Every cold load (NamedToolCards is in the eager tool-card tree).
  • Problem: A second markdown engine (marked, ~40 KB min) plus DOMPurify (~20 KB min) is bundled only to render synthesized memory text. The comment says needs the assistant-ui runtime, but plain react-markdown (already used by BlockMarkdown and MarkdownFileView without that runtime) does not, and it skips raw HTML so no sanitizer is needed.
  • Fix: Render synthesized text with ReactMarkdown + remarkGfm and skipHtml (reuse the BlockMarkdown pattern or a shared PlainMarkdown component), then remove marked and dompurify from web/package.json.
  • Verifier: marked and DOMPurify are used only in NamedToolCards.tsx, so removal is real. But the card sits in the lazy StructuredView chunk, not the cold-load entry. Savings are roughly 25 KB gzip on first session open. Swapping engines risks rendering differences; sanitizer rationale needs recheck.
  • Measure: Run vite build with rollup-plugin-visualizer; check marked and dompurify size inside the StructuredView chunk.

#421 serve_embedded_file copies each asset into a new Vec per 200 response

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-bundle, category cpu
  • Where: src/server/assets.rs:101-110
  • Frequency: Per non-304 asset request; scales with asset size (2.4 MB entry, 10.7 MB worker).
  • Problem: file.data.to_vec() allocates and memcpys the whole embedded file on every 200 response, although in release rust-embed data is Cow::Borrowed(&'static [u8]).
  • Fix: Build the body without copying: match file.data { Cow::Borrowed(b) => Body::from(Bytes::from_static(b)), Cow::Owned(v) => Body::from(v) } in serve_embedded_file.
  • Verifier: file.data.to_vec() does copy the whole embedded file per 200, and rust-embed data is borrowed static. But assets are immutable, so 200s happen about once per client. A 10 MB memcpy costs a few ms. The Bytes::from_static fix is correct but marginal.
  • Measure: Time a cold GET of the largest asset with curl -w %{time_total} against a release build, before and after the change.

#422 Service worker registered during startup before first render

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-bundle, category startup
  • Where: web/src/main.tsx:16-18, web/public/sw.js:7-23
  • Frequency: Every page load.
  • Problem: navigator.serviceWorker.register('/sw.js') runs synchronously at module eval, so the sw.js fetch (no-cache, through auth middleware) and SW script evaluation compete with the entry's API calls on cold load. The SW has no fetch handler, so nothing needs it before load.
  • Fix: Defer registration in main.tsx: window.addEventListener("load", () => navigator.serviceWorker.register("/sw.js"), { once: true }), or call it from a requestIdleCallback after first render.
  • Verifier: register('/sw.js') runs at module eval in main.tsx, and sw.js is no-cache. But register() is async, the SW has no fetch handler, and browsers already defer SW install work. Deferring to the load event is safe but gains little. Push code may rely on registration.
  • Measure: Chrome Performance trace on cold load: check whether the sw.js fetch delays entry API calls or LCP, with and without deferral.

4.web-acp-render

#423 BackgroundAgentsContext value is a fresh object on every chunk, re-rendering every tool card consumer

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-acp-render, category render
  • Where: web/src/components/acp/StructuredView.tsx:135-147, web/src/components/acp/StructuredView.tsx:123, web/src/components/acp/backgroundAgentsContext.ts:40-44, web/src/components/acp/backgroundAgentsContext.ts:121, web/src/components/acp/ToolCards.tsx:51
  • Frequency: Per AcpRuntime render (each streamed chunk); AcpFileRefContext value per StructuredView render (session list polls).
  • Problem: The provider value is an inline object inside the render-prop, so every consumer (useSubagentFor in every ToolCard, SubagentDetail, AsyncSubagentCard, WorkflowToolCard) re-renders on each chunk even if messages were memoized. useSubagentFor and useBackgroundAgentFor also linear-scan arrays per card per render. AcpFileRefContext value is likewise inline, re-rendering every Markdown link/image and file-path chip.
  • Fix: Move the provider into a BackgroundAgentsBridge component that builds the value with useMemo over [sessionId, backgroundAgents, subagents, cancelSubagent, workflowRuns, backgroundTasks, openPane, readOnly] and precomputes a Map for subagent lookup. In StructuredView, useMemo the AcpFileRefContext value on [onOpenFileRef, fileRefSession].
  • Verifier: Inline values confirmed at StructuredView.tsx:123 and :136. Today the render-prop output re-renders AcpChrome on every chunk anyway, and finding 0 re-renders every message, so memoizing the value gains little until finding 0 lands. Linear finds over a small subagent array cost nothing. Useful only as a follow-up to finding 0.
  • Measure: After fixing finding 0, use React Profiler 'why did this render' on ToolCard during streaming and count renders caused by context changes.

#424 Markdown re-parses full message text per chunk and per smooth frame; inline components object

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area web-acp-render, category render
  • Where: web/src/components/acp/Markdown.tsx:40-61, web/src/components/acp/Markdown.tsx:147-163, web/src/components/acp/ThreadMessages.tsx:145-178
  • Frequency: Live message: every smooth-reveal frame (~60/s) while streaming. History messages: each chunk while finding 1 holds. Scales with message length and number of tables.
  • Problem: MarkdownTextPrimitive runs remark/rehype over the entire text each render, so a long streamed answer costs O(length) per frame. components is a new object each render, which can invalidate the primitive's memoized component map. TableSourceContext value changes per chunk, so every table in the live message re-renders and re-runs tableSource via context, bypassing any memo.
  • Fix: Hoist the components object to a module-level const. Wrap Markdown in React.memo on (text, smooth, breaks). For the live message, split text into closed top-level blocks (blank line outside a fence) and render each closed block as a memoized Markdown, re-parsing only the trailing open block.
  • Verifier: Re-parse per smooth frame is real but is assistant-ui's streaming design. Inline components object is likely harmless: all values are stable module-level functions and the primitive memoizes per component. React.memo on Markdown may not help since the primitive subscribes to part state. Block-splitting is the only real win and is invasive.
  • Measure: Chrome Performance trace while streaming a 20 KB answer with tables; sum remark/rehype time per frame in the live message.

#425 No virtualization or content-visibility; the rendered window grows with every new row for the life of the view

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area web-acp-render, category memory
  • Where: web/src/hooks/useHistoryWindow.ts:38-43, web/src/components/acp/StructuredView.tsx:352, web/src/components/acp/ThreadMessages.tsx:44, web/src/components/acp/ThreadMessages.tsx:134
  • Frequency: Continuous: DOM and React tree size grow with every row appended since the view mounted; per-chunk reconcile and layout cost grow with it.
  • Problem: useHistoryWindow adds every new row to visibleRows, so after hours of streaming the window holds everything since mount, and ThreadPrimitive.Messages renders all of it. No message root uses content-visibility, so style/layout of offscreen messages is paid on every content resize. Retained hidden session views keep their full DOM too.
  • Fix: Add [content-visibility:auto] [contain-intrinsic-size:auto_240px] to the MessagePrimitive.Root classNames in UserMessage/AssistantMessage (not the last message). In useHistoryWindow, reset visibleRows to DEFAULT_HISTORY_WINDOW when the reader is pinned at bottom and a turn ends, so the window stops growing unbounded.
  • Verifier: Growth is real: useHistoryWindow.ts:38-42 adds every appended row, and no content-visibility exists anywhere in web/src. The proposed reset does not work as written: pinnedWindowStart (line 48) only lets start move earlier (#3707), so shrinking visibleRows leaves start unchanged. Fixing that means reworking the anchor pin. content-visibility can also break useTranscriptScroll's height and bottom-pin logic.
  • Measure: Stream a 2h session with many tool calls, then record a DevTools Performance trace and compare the DOM node count and the per-chunk Layout and React commit time at 150 rows versus 2000 rows.

#426 Whole chrome (banners, ComposerDock, Composer) re-renders on every streamed chunk

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-acp-render, category render
  • Where: web/src/components/acp/AcpRuntime.tsx:237-275, web/src/components/acp/StructuredView.tsx:205-421, web/src/components/acp/StructuredView.tsx:426-597, web/src/components/acp/StructuredView.tsx:575-582
  • Frequency: Per AcpRuntime render (each WS chunk), per visible session.
  • Problem: The ctx object and the inline arrows (onToggleCollapsed, onPrefill, onInsertPrimer, onCompact, signIn object, queuedReason result) are rebuilt each render and nothing is memoized, so SessionBanners, UsageLimitSection, QueuedPromptsStrip, Composer, ComposerControls and SessionConfigControls reconcile on every text chunk though none of their inputs changed. This competes with typing in the composer during streaming.
  • Fix: Wrap Composer and ComposerDock in React.memo; build signIn with useMemo; wrap the inline handlers in useCallback. In AcpRuntime, split ctx into a memoized stable actions object (all acp callbacks) and the state, so memoized children only see changed props.
  • Verifier: Nothing is memoized, and useAcpSession does not batch chunks, so the chrome re-renders on every WS message. React.memo on ComposerDock would not help because it takes ctx, and ctx.state is a new object on every chunk. The working fix is React.memo on Composer plus a memoized signIn object and stable callbacks. Splitting ctx is unnecessary. The gain is reconcile work only.
  • Measure: Run React Profiler during streaming and record the commit time of the Composer and AcpChrome subtrees per chunk, before and after memoizing Composer.

#427 Scroll observer forces synchronous layout after each programmatic repin and samples anchors twice

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-acp-render, category render
  • Where: web/src/components/acp/useTranscriptScroll.ts:290-297, web/src/components/acp/useTranscriptScroll.ts:341-345, web/src/components/acp/useTranscriptScroll.ts:194-232, web/src/components/acp/useTranscriptScroll.ts:392-399, web/src/lib/toolAnchor.ts:17-37
  • Frequency: Per content ResizeObserver callback, about once per frame while text streams with the reader pinned; the layout effect runs every AcpChrome render.
  • Problem: The pinned path writes vp.scrollTop then calls resample(), whose sampleToolAnchors calls querySelectorAll and getBoundingClientRect, forcing layout right after the write. The write then fires a scroll event whose onScroll calls resampleToolAnchors again. When pinned at bottom, the anchors are not needed. The unconditional useLayoutEffect also reads scrollHeight/clientHeight on every chunk commit.
  • Fix: In the contentRo pinned branch (line 341), skip resample and set a anchorsDirty flag; sample lazily in onScroll only when readerMoved is true. In onScroll, return early when vp.scrollTop equals the value just written by repin. Give the line-392 useLayoutEffect a dependency on a fold counter instead of running every render.
  • Verifier: Pinned branch does write scrollTop then resample() (querySelectorAll + binary-search rects), and onScroll resamples again. But sampling is already bounded by binary search, and anchors feed fold correction so skipping is risky. The layout effect is two cheap reads; a fold-counter dep would break its purpose.
  • Measure: Chrome Performance trace while streaming pinned: look for forced reflow attributed to contentRo callback in useTranscriptScroll.ts, check ms per frame.

#428 Tool output media builds multi-MB data URIs per render and loads images eagerly

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-acp-render, category memory
  • Where: web/src/components/acp/ToolOutputMedia.tsx:28, web/src/components/acp/ToolOutputMedia.tsx:40-46, web/src/components/acp/ToolOutputMedia.tsx:61-82, web/src/components/acp/ToolOutputMedia.tsx:95-104, web/src/components/acp/ToolCards.tsx:58-67, web/src/components/acp/artifactMedia.tsx:56, web/src/components/acp/artifactMedia.tsx:95
  • Frequency: Per render of every tool card with image/audio/resource output (each chunk while finding 1 holds); per mount for fetches. Scales with media byte size.
  • Problem: dataUri concatenates the base64 payload into a new string each render, and React compares the multi-MB src string each commit. ToolOutputMedia renders outside card expansion, so images decode and full resource text renders in TextPre for collapsed cards. No has loading="lazy" or decoding="async".
  • Fix: In ToolOutputBlockView, useMemo a Blob from base64 once per block and expose URL.createObjectURL (revoke on unmount) instead of dataUri. Add loading="lazy" decoding="async" to the img tags in ExpandableImage and ArtifactImage. Render TextPre through HighlightedBlock with maxLines so large text resources truncate.
  • Verifier: Real: dataUri rebuilt per render, no loading/decoding attrs, no memo on ToolCard. But inline media is capped at 4MB base64 server-side (MAX_INLINE_MEDIA_B64), and same-content string compare is a fast memcmp. Blob URL fix adds revoke lifecycle; decoding=async is the cheap win.
  • Measure: React Profiler on a 4MB image tool card while text streams; compare commit time of ToolOutputBlockView.

#429 Collapsed and expanded tool cards split full outputs every render

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-acp-render, category cpu
  • Where: web/src/components/acp/CoreToolCards.tsx:68, web/src/components/acp/CoreToolCards.tsx:131, web/src/components/acp/CoreToolCards.tsx:279, web/src/components/acp/ToolCardChrome.tsx:333-341
  • Frequency: Per render of each Execute/Read/Search card (meta line count runs even when collapsed); HighlightedBlock work per render when expanded. Scales with output size.
  • Problem: ExecuteToolCard runs unwrapMarkdownFence regex and split("\n") over the whole output for the header line count, ReadToolCard splits content, SearchToolCard splits and filters all lines, all per render. HighlightedBlock re-runs the fence regex, splits all lines, slices and joins, and hasAnsi on every render.
  • Fix: Wrap these in useMemo keyed on the output string (result?.text). In HighlightedBlock, useMemo {unwrapped, lines, shown, truncated, ansi} on [text, unwrapFence, showAll, maxLines]. Count lines with a loop over indexOf instead of split.
  • Verifier: Splits and regexes do run each render (no memo anywhere in tool cards, no React Compiler). But it is linear and only for tool cards re-rendered by parent; completed outputs are modest. useMemo is trivial and safe; real win only for multi-MB outputs.
  • Measure: React Profiler flamegraph with a 5MB Execute output while a later message streams; check ExecuteToolCard self time.

#430 RawBlock and wrapped code render unbounded output, one span per line

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-acp-render, category render
  • Where: web/src/components/acp/ToolCardChrome.tsx:264-282, web/src/components/acp/WrapToggle.tsx:59-64, web/src/components/acp/Markdown.tsx:210-214, web/src/components/acp/CoreToolCards.tsx:376-377
  • Frequency: Per expand of a Generic/MCP card (failed cards open by default) and per render of an unhighlighted code block with wrap on.
  • Problem: RawBlock has no maxLines, so a large MCP or generic tool output renders in full. With wrap enabled (acp.wrap_tool_output), WrapLines creates one React element per line, so a 50k-line output means 50k spans, re-reconciled on every re-render of the card.
  • Fix: Give RawBlock the same maxLines plus 'Show N more lines' truncation HighlightedBlock uses (default 40). Memoize WrapLines output with useMemo on text, or render wrapped plain text with CSS (white-space: pre-wrap plus text-indent hanging via padding-left/negative indent) instead of per-line spans.
  • Verifier: RawBlock has no maxLines and WrapLines makes one span per line, unmemoized; claim holds. But it is only used by the generic card (CoreToolCards:376-377), rendered only when expanded, and wrap is a non-default opt-in. Rare path; output size likely capped upstream.
  • Measure: Expand a generic MCP card with 50k-line output and wrap on; Profiler commit time, plus DOM node count.

#431 Composer @-file adapter remaps the whole repo file list on every keystroke

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-acp-render, category cpu
  • Where: web/src/components/acp/useComposerHooks.ts:139-156
  • Frequency: Per keystroke while the @ popover is open. Scales with repo file count.
  • Problem: The useMemo builds a flatAdapter whose query callback runs files.map(...), allocating an item object and running an extension regex for every file in the index on each query, before fuzzyFilter.
  • Fix: Hoist the mapping out of the callback: in useTriggerAdapters, const items = useMemo(() => files.map(...), [files]) and have the flatAdapter callback call fuzzyFilter(items, query, 30).
  • Verifier: Claim holds: files.map plus regex per query before fuzzyFilter, which itself maps/filters/sorts all items anyway. Hoisting removes one allocation pass of maybe three. Only matters for tens of thousands of files; fuzzyFilter dominates. Trivial safe fix.
  • Measure: console.time around fileAdapter search with a 50k-path files array; compare with hoisted items.

#432 useShikiTheme reads and parses localStorage and adds a window listener per code block

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-acp-render, category cpu
  • Where: web/src/hooks/useShikiTheme.ts:11-27, web/src/components/acp/Markdown.tsx:174, web/src/components/acp/ToolCardChrome.tsx:332
  • Frequency: Per mount of each fenced code block and HighlightedBlock; scales with code blocks in the window.
  • Problem: Each instance's useState initializer calls readCachedResolvedTheme (localStorage read plus JSON.parse of the full resolved theme) and registers its own window THEME_CHANGED listener. A transcript with hundreds of blocks pays hundreds of parses on mount or remount.
  • Fix: Turn useShikiTheme into a module-level store: parse once, keep one window listener, and expose it via useSyncExternalStore returning a stable {theme, appearance} object.
  • Verifier: Claim is accurate: each instance runs localStorage read plus JSON.parse in its useState initializer and adds its own window listener (useShikiTheme.ts:12-26). But it runs once per mount, the payload is a few KB, and shiki highlighting per block dwarfs it. Module store is safe but gains ms.
  • Measure: Chrome profiler on a 300-block transcript mount; time readCachedResolvedTheme via performance.measure and compare it with the highlightSnippet total.

4.web-data-layer

#433 Session and plugin polls keep running in hidden tabs

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-data-layer, category network
  • Where: web/src/hooks/useSessions.ts:251-288, web/src/hooks/usePluginUiState.ts:55-94, web/src/hooks/useDiffFiles.ts:88-92
  • Frequency: Sessions every 3s, plugin UI state every 3s (500ms boosted), diff files every 10s, per open tab including background tabs
  • Problem: None of these loops check document.visibilityState. A user with several dashboard tabs (or a backgrounded PWA) keeps hitting /api/sessions, /api/plugins/ui-state and the git-diff endpoint around the clock, and each tick also does JSON parse plus React work. useSystemHealth already stops when hidden; these do not.
  • Fix: Add the same visibility gate used in useSystemHealth: in useSessions tick, usePluginUiState tick and useDiffFiles interval, skip scheduling while document.hidden and run one immediate tick on visibilitychange to visible. Since useSessionStatusStream already pushes status moves, also raise POLL_INTERVAL to ~10-15s while that socket is open.
  • Verifier: Confirmed: the useSessions and usePluginUiState loops have no visibility gate. useDiffFiles polls only while the diff panel is active (App.tsx:943). Browsers throttle chained timers in hidden tabs (Chrome's intensive throttling drops them to about once per minute after 5 minutes), so the 'around the clock' cost is overstated. Raising the interval while the status socket is open needs a check that nothing else depends on the poll.
  • Measure: Hide a dashboard tab for 10 minutes and count /api/sessions and /api/plugins/ui-state requests in the server access log.

#434 Plugin UI poll publishes new entries and revisions identity every 3s

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-data-layer, category render
  • Where: web/src/hooks/usePluginUiState.ts:69-76, web/src/lib/pluginUiContext.tsx:26-42, web/src/lib/pluginPanes.ts:41-50, web/src/hooks/app/useAppPanes.ts:27-32, web/src/hooks/app/useSidebarModel.ts:36-48
  • Frequency: Every 3s (500ms during 15s boost after actions)
  • Problem: setEntries and setRevisions always receive new objects, so every usePluginUiEntries/usePluginUiRevision consumer re-renders each poll. usePluginPanes then builds a new array, which re-fires useAppPanes' syncPlugins effect and pluginPaneById memo, and invalidates useSidebarModel's pluginSort memo. Only pages has the identity guard.
  • Fix: In usePluginUiState.tick, apply the same keep-identity guard used for pages to entries and revisions (compare a JSON string of state.entries / state.revisions to the last one held in a ref). In usePluginPanes, wrap the map in useMemo keyed on entries and sessionId.
  • Verifier: Real: entries/revisions get new identity every poll. But useAppPanes and useSidebarModel are dead code (only a test imports useSidebarModel). Real consumer is App.tsx:534 and 680 (root App re-renders each poll), plus WorkspaceSidebar, Composer, PluginSlots. syncPluginTabs returns same layout, so mutate bails out. Fix the guard in tick; memoizing usePluginPanes is optional.
  • Measure: React DevTools Profiler, idle dashboard, 30s recording: count App and WorkspaceSidebar commits caused by PluginUiEntriesContext. Compare before and after adding the JSON guard.

#435 Diff list change refetches the open file even when that file is unchanged

  • Impact low, effort M, verdict partly, evidence proven-by-code, area web-data-layer, category network
  • Where: web/src/hooks/useDiffFiles.ts:39-50, web/src/hooks/useFileContents.ts:27-34, web/src/hooks/useFileContents.ts:96-127, web/src/components/diff/DiffFileViewer.tsx:68
  • Frequency: Every 10s diff poll while the diff panel is open and any file in the session changes (constant during an agent turn)
  • Problem: useDiffFiles bumps a single global revision when any file changes, and useFileContents keys its cache on that revision. Every change to any file forces a full refetch of old_content+new_content+patch for the viewed file, and stale revision entries fill the 32 MB LRU.
  • Fix: Pass a per-file fingerprint instead of the global revision to useFileContents (e.g. ${status}:${additions}:${deletions}:${old_path} of the matching RichDiffFile), so cacheKeyFor changes only when that file's diff stats change. Keep the global revision for the file list only.
  • Verifier: Claim holds: any diff-list change bumps the global revision (useDiffFiles.ts:44-49), which rekeys useFileContents. The proposed stats fingerprint is unsafe: an edit can leave additions/deletions unchanged, and a base change alters content, so the view goes stale. A safe fix needs a server content hash or etag per file. Cache is bounded at 60 entries and 32 MB.
  • Measure: DevTools Network during an agent turn with the diff viewer open: count /file-contents requests per minute where the viewed file's response bytes are identical.

#436 Live terminal rebuilds full content string on every patch

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-data-layer, category cpu
  • Where: web/src/hooks/useLiveTerminal.ts:268-287, web/src/components/MobileLiveTerminal.tsx:105-110, web/src/components/MobileLiveTerminal.tsx:203
  • Frequency: Per live terminal patch message (fast cadence, many per second while output streams); scales with rows+history (up to 4000 lines while reading)
  • Problem: On a patch, handleMessageText computes content = lines.join("\n") + "\n" over the whole window, but consumers read frame.lines first and only fall back to content when lines is absent. The join allocates a large string per patch for nothing.
  • Fix: In useLiveTerminal handleMessageText, leave content unset (make LiveFrame.content optional or a lazy getter) for patch frames, since lines is always set there. Update MobileLiveTerminal.frameLines fallback accordingly.
  • Verifier: Claim holds: patch path joins all lines (useLiveTerminal.ts:283) and only MobileLiveTerminal falls back to content. But applyPatch already copies the lines array, and the string is one cheap join (about 50 rows normally, up to 4000 only while reading). Real, small win.
  • Measure: Chrome Performance profile of a streaming live terminal; time handleMessageText with and without the join, at rows=50 and 4000.

#437 Single-row transcript append and patch scan and copy the whole activity array

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-data-layer, category cpu
  • Where: web/src/lib/acpTypes.ts:965-999, web/src/lib/acpTypes.ts:1001-1012, web/src/hooks/acpSession/reducer.ts:244-247
  • Frequency: Per transcript_delta (Append/Patch) during streaming; scales with transcript length
  • Problem: mergeServerRows builds a Map of every existing id to place one appended row, and patchServerRow does findIndex from the start although patches nearly always target the tail. Both then slice the array. Per chunk this is O(n) Map construction plus O(n) copy.
  • Fix: Add a fast path in reducer transcript_append: if no row with that id exists in the last few entries, return existing.concat(row) without building indexById. In patchServerRow, search backwards from the end. Keep the Map path for multi-row merges.
  • Verifier: Code matches: mergeServerRows builds a Map of all rows per append and patchServerRow uses findIndex from the head, plus slice copies. But withServerRows runs pruneOptimisticRows and settleServerPrompts over activity too, so the fast path removes only part of the O(n). Backward search is safe.
  • Measure: Vitest bench: reduce 2000 transcript_patch actions on a 5000-row activity; time the reducer before and after.

#438 Duplicate startup fetches of /api/about, /api/plugins and /api/settings

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-data-layer, category startup
  • Where: web/src/hooks/useProjects.ts:43, web/src/hooks/useDashboardUpdate.ts:25, web/src/hooks/app/useAppPanes.ts:37-46, web/src/App.tsx:722-735, web/src/App.tsx:243, web/src/App.tsx:2543, web/src/lib/api.ts:157-166
  • Frequency: Once per page load and again on several visibility/reconnect triggers
  • Problem: App, useProjects and useDashboardUpdate each GET /api/about at mount. App and useAppPanes run identical fetchPlugins effects that build the same pluginIdentityById map. App fetches /api/settings twice. Each duplicate costs a round trip and JSON parse during first paint.
  • Fix: Add a single-flight helper in api.ts (a Map<url, Promise> cleared on settle) used by fetchAbout, fetchPlugins and fetchSettings so concurrent callers share one request. Delete the duplicated fetchPlugins effect in App.tsx and read pluginIdentityById from useAppPanes.
  • Verifier: Duplicates are real: App.tsx:727 and useAppPanes.ts:37 run identical fetchPlugins effects, about is fetched by 3 hooks, settings twice. But these are loopback GETs at mount. A generic single-flight on fetchSettings(profile) risks stale reads after saves. Dedupe plugins and about only.
  • Measure: Playwright or DevTools Network tab on a cold load; count GETs to /api/about, /api/plugins and /api/settings.

#439 Tab return fires a burst of unthrottled refetches

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-data-layer, category network
  • Where: web/src/hooks/useProjects.ts:62-66, web/src/hooks/useUpdateBanner.ts:34-40, web/src/hooks/useSandboxImageBanner.ts:102-105, web/src/hooks/usePushSubscription.ts:322-325
  • Frequency: Every visibilitychange to visible and every window focus (frequent on mobile PWA and when switching windows)
  • Problem: useProjects listens to both focus and visibilitychange, so one tab return runs fetchAbout+fetchProjects twice (first aborted after hitting the server). useUpdateBanner, useSandboxImageBanner and usePushSubscription refetch on every return with no throttle, unlike useDashboardUpdate's 30s CHECK_THROTTLE_MS.
  • Fix: Apply a per-hook minimum interval like useDashboardUpdate's CHECK_THROTTLE_MS (30-60s) in useUpdateBanner.onVisibility, useSandboxImageBanner.onVisibility and usePushSubscription. In useProjects, drop the window focus listener or skip a load started within the last few seconds.
  • Verifier: useProjects does fire both focus and visibilitychange and aborts the first load (useProjects.ts:62-66). The other hooks refetch on each visibility flip without throttle. But each is one small local GET, and useUpdateBanner already supersedes in-flight polls. Throttling risks stale banners after a pull or update.
  • Measure: DevTools Network, filter /api; switch tabs 5 times in a minute and count requests to about, projects, update-status, sandbox image and push.

#440 Trash list is polled every 3s forever after one trash lookup

  • Impact low, effort M, verdict confirmed, evidence proven-by-code, area web-data-layer, category network
  • Where: web/src/hooks/useSessions.ts:56-57, web/src/hooks/useSessions.ts:245-248, web/src/hooks/useSessions.ts:276-277, web/src/App.tsx:488-492
  • Frequency: Every 3s for the rest of the tab lifetime once loadTrash ran (trash view or a link to a missing session)
  • Problem: trashWantedRef is set true and never cleared, so every list poll is followed by a second GET /api/sessions?state=trashed plus a full setState pass over all rows, even after the user leaves the trash view.
  • Fix: Expose an unloadTrash (or make loadTrash return a release function) from useSessions that clears trashWantedRef, and call it from App when the trash view closes and the opened session is resolved. Alternatively only sync trash when trashed_count changed.
  • Verifier: trashWantedRef is set at useSessions.ts:246 and never cleared. syncTrash runs after every 3s list poll (line 276), plus a setState pass over all rows. Simple unload is risky: epoch fences, absentRef and pushedRef depend on it. Gating on trashed_count change is safer.
  • Measure: Open the trash view once, close it, then count GET /api/sessions?state=trashed per minute in the Network tab; expect about 20.

#441 In-memory ACP cache holds up to 32 full transcripts

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area web-data-layer, category memory
  • Where: web/src/hooks/acpSession/stateCache.ts:18-19, web/src/hooks/acpSession/stateCache.ts:155-163
  • Frequency: Grows per opened session over a long-lived tab; scales with transcript length including loaded older pages
  • Problem: STATE_CACHE_CAP keeps 32 complete AcpState objects, including every activity row and older pages loaded via loadOlder, with no size bound. Users switching through many long sessions keep tens of MB of row objects alive.
  • Fix: Bound the LRU by row count as well (e.g. total activity rows across entries), or trim activity of non-current entries in lruInsert to the last initialHistoryWindow rows and reset their oldestSeq so replay reloads older pages on demand.
  • Verifier: Cap of 32 is real and memory is untrimmed (persist uses toPersistedState). But only sessions opened this tab count, and loadOlder pages are user-driven. reopenState already drops rows lacking a user boundary. Likely a few MB typical; tens of MB needs extreme transcripts.
  • Measure: Chrome DevTools heap snapshot after opening 32 long sessions with loadOlder; sum retained size of stateCache Map.

4.web-other-components

#442 Plugin UI poll replaces entries every 3s (0.5s boosted) and fans out to every sidebar row

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area web-other-components, category render
  • Where: web/src/hooks/usePluginUiState.ts:70-76, web/src/lib/pluginUiContext.tsx:29-48, web/src/components/plugin/PluginSlots.tsx:51-99, web/src/components/sidebar/RowBadges.tsx:296, web/src/lib/pluginUi.ts:70-77
  • Frequency: Every 3s, or every 500ms for 15s after each plugin action poke; per row work is O(entries), total O(sessions x entries)
  • Problem: setEntries(state.entries) and setRevisions run unconditionally with new arrays, unlike pages which is compared. Each row's PluginRowLine, RowBadges and RowColumn re-render and run sessionEntries (full filter) up to 4 times per row, plus WorkspaceSidebar's pluginSorts/facets recompute, even when nothing changed.
  • Fix: In usePluginUiState compare the new entries/revisions to the previous (JSON string or per-entry key+payload compare) and keep the old reference when equal. Optionally pre-index entries by session_id in PluginUiProvider so each row does a Map lookup.
  • Verifier: usePluginUiState.ts:71-72 sets entries and revisions unconditionally while pages are JSON-compared. Entries context consumers (PluginRowLine, PluginRowColumn) re-render inside memo rows on a second 3s timer. Win is small until finding 0 is fixed, since rows already re-render every session poll.
  • Measure: React Profiler with plugins enabled: count PluginRowLine renders over 30s idle, then with JSON-equal check on entries.

#443 Session and plugin polls keep running in hidden tabs

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-other-components, category network
  • Where: web/src/hooks/useSessions.ts:253-285, web/src/hooks/usePluginUiState.ts:60-97, web/src/hooks/useSystemHealth.ts:30-85
  • Frequency: Continuously while a dashboard tab is open: /api/sessions and plugin ui-state each every 3s, forever, per tab and per device
  • Problem: useSystemHealth stops on document.hidden, but useSessions and usePluginUiState have no visibility check. Background tabs keep fetching, parsing JSON and re-rendering the whole tree, and keep the daemon building snapshots for idle clients.
  • Fix: Gate scheduleNext in both tick loops on document.visibilityState, stop the timer on visibilitychange hidden, and run one immediate refresh on visible, as useSystemHealth does. Keep the push stream for attention sounds if that path needs it.
  • Verifier: Correct: only useSystemHealth gates on document.hidden; useSessions and usePluginUiState chain setTimeout without visibility checks. Overstated: Chrome and Safari throttle chained timers in hidden tabs (1/min after about 5 min), so steady-state cost is far below every 3s. Main win is the first minutes and daemon load from multi-device tabs.
  • Measure: Hide tab 10 minutes, count /api/sessions and plugin ui-state requests in daemon access log or DevTools network.

#444 StringDiff tokenizes every line on the main thread with no cache or size cap

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-other-components, category cpu
  • Where: web/src/hooks/useHighlightedLines.ts:22-44,59-89, web/src/components/diff/StringDiff.tsx:18-43, web/src/lib/diffPair.ts:48-60
  • Frequency: Per Edit/Write tool card mount in a transcript (again on each remount from scroll or session switch); scales with old/new text length and lines per card
  • Problem: parseDiffFromFile uses a huge context so all unchanged lines are kept, then tokenizeHunks calls shiki codeToTokens once per line synchronously (losing grammar state per line), and DiffLine renders every line as DOM. A Write of a large file blocks the main thread; results are not cached across remounts.
  • Fix: Cache tokens by (path, theme, hash of old/new) in an LRU in useHighlightedLines. Tokenize the whole hunk in one codeToTokens call or via the pierre worker pool, and cap rendered lines with a 'show more' fold above ~300 lines.
  • Verifier: Code matches: full-context diffPair, one sync codeToTokens per line, no cache. But Edit/Memory cards use useToolCardExpansion(status) with defaultOpen=false (ToolCardChrome.tsx:85-87), and body renders only when expanded (line 213), so it runs only on user expand of a large Write, not per mount. Single whole-text codeToTokens also fixes lost multi-line grammar state.
  • Measure: Expand a Write card of a 2000-line .ts file; record Performance trace and measure the useHighlightedLines effect long task duration.

#445 web settings update() always emits a new snapshot, re-rendering all 18 consumers

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area web-other-components, category render
  • Where: web/src/hooks/useWebSettings.ts:111-175, web/src/components/diff/DiffFileList.tsx:68-70, web/src/components/WorkspaceSidebar.tsx:123, web/src/components/MobileLiveTerminal.tsx:147
  • Frequency: On every update() call: each diff-pane mount (unconditional effect), each dir toggle, font pinch, sidebar toggle. Consumers include sidebar, live terminals, diff viewers
  • Problem: update() writes localStorage then sets cachedRaw=null, so the next snapshot is a new object even when the JSON is identical. DiffFileList's mount effect calls update({collapsedDiffDirs}) with unchanged data, re-rendering the whole sidebar and live terminal trees. Consumers also select one field but subscribe to all.
  • Fix: In update(), compare the serialized next value with the current raw string and return early if equal. Drop the mount-time write in DiffFileList (write only inside toggleDir). Add a selector overload (useWebSetting(key)) so rows subscribe to one field.
  • Verifier: update() sets cachedRaw=null, so getStableSnapshot re-parses to a new object even for identical JSON. DiffFileList's mount effect writes unconditionally. Real but only once per diff-pane mount and per toggle. Early-return on equal serialized value is a trivial, safe fix. Selector overload is optional.
  • Measure: React Profiler: open the diff pane with a live terminal mounted; count MobileLiveTerminal/WorkspaceSidebar commits triggered by the mount effect.

#446 Each animated StatusGlyph owns a setInterval, ticking even when the sidebar is hidden

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-other-components, category cpu
  • Where: web/src/components/StatusGlyph.tsx:62-83, web/src/components/sidebar/SessionRow.tsx:223-228, web/src/lib/rattles.ts:5-10
  • Frequency: Per Running/Waiting/Starting/Creating session, every 180-400ms while mounted (also on mobile where the sidebar is translated off-screen); scales with active session count
  • Problem: N active rows create N intervals plus N initial timeouts and setState calls, each firing a React render; the timers keep running in the off-screen mobile drawer and are not shared. animate is never wired to prefers-reduced-motion by the sidebar.
  • Fix: Replace the per-component interval with one shared ticker per rattle interval in a module store read via useSyncExternalStore, started on first subscriber and stopped on last. Pass animate=false when the drawer is closed or reduced motion is set.
  • Verifier: Each StatusGlyph runs its own setInterval (180-400ms) plus setState; this is confirmed. Cost scales with active sessions only (typically a handful), each render is a one-text-node component. A shared ticker is feasible but the gain is small. Pausing when the drawer is hidden is the better fix.
  • Measure: Chrome Performance profile with 20 Running sessions and the sidebar idle for 10s; compare scripting time with animate=false.

#447 Settings slider issues a PATCH for every drag step

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area web-other-components, category network
  • Where: web/src/components/settings/FormFields.tsx:278-316, web/src/components/settings/SchemaSection.tsx:100-109, web/src/components/settings/customWidgets.tsx:86-98, web/src/lib/settingsStore.ts:235-265
  • Frequency: Per input event while dragging a range slider (one per step crossed), queued serially through the settings tail
  • Problem: SliderField calls onChange on every input event, which goes straight to saveField and a PATCH that makes the daemon rewrite profile or config TOML. Dragging across many steps queues that many serialized disk writes, unlike TextField which commits on blur.
  • Fix: Keep a local value in SliderField and call onChange on pointerup/keyup/blur (the native change event) while showing the live value from local state.
  • Verifier: SliderField onChange fires on every input event and SchemaSection passes save straight through. saveField publishes optimistically, then queues each send serially on e.tail, so one PATCH per step crossed. Bounded by step count, but each PATCH rewrites TOML. Commit on pointerup/change is safe.
  • Measure: Drag a settings slider across its range with the browser Network tab open; count PATCH requests.

#448 Live terminal frame path does O(window) work per frame, including an unused joined string

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area web-other-components, category cpu
  • Where: web/src/hooks/useLiveTerminal.ts:270-282,308-314, web/src/lib/liveTermLines.ts:36-63, web/src/components/MobileLiveTerminal.tsx:203-232
  • Frequency: Per streamed frame at up to ~20 per second (50ms fast capture) at the live edge; window is 2 screens, up to 4000 lines in reading mode
  • Problem: Each patch copies all lines (applyPatch) and builds lines.join+newline into content, which the renderer never reads when lines exists. LineParseCache.lines then builds a key string and Map entry for every line, and visual re-walks all lines to rebuild rows/source arrays, though most lines are unchanged.
  • Fix: Drop content construction in the patch branch (make it optional). Carry parsed line arrays alongside raw lines and re-parse only the patch's changed rows, then update visual incrementally for them.
  • Verifier: Patch branch does build lines.join content that renderers read only as a fallback when lines is absent. LineParseCache still keys every line (cached, so no re-parse). Cost is O(window) string work at 20Hz, tens of microseconds to ~1ms. The join drop is cheap; the incremental parse rewrite is not worth it.
  • Measure: performance.now() around the onmessage handler and the useMemo at MobileLiveTerminal.tsx:203 with a 4000-line reading window streaming at 20 fps.

#449 Diff file list renders every file unvirtualized with inline closures

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area web-other-components, category render
  • Where: web/src/components/diff/DiffFileRows.tsx:63-127,143-177, web/src/components/diff/DiffFileList.tsx:66,135-177, web/src/hooks/useDiffFiles.ts:39-43
  • Frequency: Per render of DiffFileList (each focus move, hover via onMouseEnter, each changed 10s poll); scales with changed-file count
  • Problem: FileRow is not memoized and gets fresh onClick/nav/padding objects, FlatList/TreeView map all rows, and onMouseEnter sets focusedIndex on every hover so a 2000-file merge diff re-renders 2000 buttons per hover. The poll also JSON.stringifies the full file list every 10s.
  • Fix: Wrap FileRow in memo with stable callbacks (pass index, resolve the file in one parent handler) and move focus state to a data attribute or a per-row subscription. Window the list with a virtualizer above ~300 rows. Fingerprint with a cheap hash of path+counts.
  • Verifier: FileRow is not memoized and onMouseEnter sets focusedIndex, so each hover re-renders every row. Real for very large diffs. The 10s fingerprint JSON.stringify is negligible and only reruns on poll. Typical diffs are small; memo plus stable callbacks is worthwhile, a virtualizer is not.
  • Measure: React Profiler on a 2000-file diff: record hovering across rows and read DiffFileList commit duration.

#450 Command palette actions rebuilt every poll while closed, scored twice, unvirtualized

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-other-components, category cpu
  • Where: web/src/hooks/useCommandActions.ts:89-300, web/src/components/command-palette/CommandPalette.tsx:88-98,145,208-240
  • Frequency: Rebuild every 3s poll (sessions identity changes); scoring per keystroke while open; scales with session count
  • Problem: useCommandActions rebuilds the full action list including one entry per session whenever sessions changes, even when the palette is closed. While open, grouped runs cmdk's command-score on all actions and cmdk's filter runs it again, then every surviving item renders as DOM with a StatusGlyph timer.
  • Fix: Build actions lazily only while the palette is open (pass open into useCommandActions or memoize on a session-id/title signature). Reuse the grouped scores instead of rescoring, and cap the empty-query list to the first ~50 sessions.
  • Verifier: Rebuild on sessions change is an O(n) push loop with no scoring; closed palette's grouped memo hits the empty-search fast path. Double scoring (grouped plus cmdk filter) is real but only per keystroke with tens of sessions. The empty-query render of all sessions is the only real cost.
  • Measure: React Profiler: open palette with 200 mock sessions, type one character, compare CommandPalette commit time.

#451 Dock/diff viewers each create their own 4-worker highlighter pool

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-other-components, category startup
  • Where: web/src/components/diff/pierre/DiffWorkerPoolProvider.tsx:10-41, web/src/components/diff/DiffFileViewer.tsx:306-318, web/src/components/diff/FullFileViewer.tsx:49-54
  • Frequency: Each mount of DiffFileViewer or FullFileViewer (opening the diff pane, switching between diff and whole-file views, theme change keys the pool)
  • Problem: The provider with poolSize 4 sits inside each viewer, not above the pane. Switching a file between the patch view and FullFileViewer (a different tree position) or closing and reopening the pane may spawn up to 4 module workers, each initializing shiki, instead of reusing a warm pool.
  • Fix: Hoist one DiffWorkerPoolProvider to the diff/files pane container (or app level, lazily) so viewers share it for the pane's lifetime. Verify whether @pierre/diffs already shares a singleton pool before moving.
  • Verifier: Provider's own comment says failure 'terminates the poisoned singleton', so @pierre/diffs WorkerPoolContextProvider appears to share a library singleton across mounts. Pool is keyed only on theme. node_modules was absent, so unverified. Likely already handled; hoisting is small gain.
  • Measure: In DevTools, switch a file between diff and full-file views and watch Sources > Threads for new worker creation.

#452 Kept-alive structured views stay laid out while hidden

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area web-other-components, category render
  • Where: web/src/components/StructuredSessionStack.tsx:38-55
  • Frequency: Per layout pass (window resize, sidebar drag, dock resize) with persistentStructuredViews on; scales with up to 5 kept transcripts
  • Problem: Non-selected persistent views use invisible (visibility:hidden), which still lays out the full transcript DOM and participates in every resize reflow. No content-visibility is used anywhere in the web source.
  • Fix: Add content-visibility: hidden (with contain-intrinsic-size) to the unselected wrapper in StructuredSessionStack. It skips layout and paint but preserves DOM and scroll position, avoiding the scroll reset that display:none caused.
  • Verifier: Hidden views use invisible plus inert, so layout still runs for up to 5 kept transcripts on resize; claim holds. content-visibility:hidden would skip it, but risks transcript virtualizer measurement and scroll restore, which the file's re-insertion comment guards. Win unmeasured.
  • Measure: Chrome Performance trace of sidebar drag with 5 kept long transcripts; compare Layout time with and without content-visibility.

#453 Sidebar drag-resize re-renders the full sidebar tree on each mousemove

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area web-other-components, category render
  • Where: web/src/components/sidebar/useSidebarWidth.ts:24-55, web/src/components/WorkspaceSidebar.tsx:111-273, web/src/components/sidebar/SidebarGroupHeader.tsx:50
  • Frequency: Per mousemove (up to 60 to 120/s) while dragging the sidebar edge
  • Problem: setWidth lives in WorkspaceSidebar state, so each move re-runs the component, rebuilds ctx and rowProps closures, and re-renders all SidebarGroupHeaders (memo defeated by inline group={{...}} and closure props).
  • Fix: Apply the width through a CSS variable written to the element in the mousemove handler (as --aoe-sidebar-width already is) and commit state once on mouseup; or memoize header props.
  • Verifier: onMove calls setWidth on every mousemove, so WorkspaceSidebar re-renders per move; width is also published to --aoe-sidebar-width only via a post-commit effect. Writing the CSS var directly and committing on mouseup is feasible. Cost scales with sidebar row count, small for typical use.
  • Measure: React Profiler recording of a sidebar drag with 100 sessions; count WorkspaceSidebar commits and total ms.

#454 File editor polls version every 2s without visibility gating

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area web-other-components, category network
  • Where: web/src/components/diff/TextFileEditor.tsx:52-82
  • Frequency: Every 2s per open editor, including background tabs, for the whole edit session
  • Problem: The conflict check re-arms a 2s timeout regardless of document visibility and issues a version-only file request each time, adding daemon file stats while the user is away.
  • Fix: Skip scheduling when document.hidden and rely on the existing window focus and a visibilitychange listener to check immediately on return; consider 5s while the draft is unmodified.
  • Verifier: The check loop re-arms a 2s timeout with no document.hidden gate; only a window focus listener exists. Each tick is a versionOnly file stat. Browsers already throttle background timers, and it needs an open editor, so the win is small but the fix is trivial.
  • Measure: Open an editor, background the tab, and count GET /file?version_only requests per minute in the server access log.

#455 Plugin bridge calls are uncached and requireListed re-fetches the session list per call

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-other-components, category network
  • Where: web/src/components/plugin/PluginPageView.tsx:98-141,262-285
  • Frequency: Per page request: each sessions.list, plugins.uiState, session.archive, session.trash, session.contextMenu call from an iframe page
  • Problem: Each bridge call hits the daemon with no coalescing; archive, trash and contextMenu each call fetchPluginSessions first. A page that polls plugins.uiState duplicates the dashboard's own 3s poll, and bulk actions from a kanban page issue N+N requests. No per-page rate limit exists.
  • Fix: In runCall keep a short-lived (1s) in-flight/result cache for fetchPluginSessions and fetchPluginUiState keyed by pluginId, and serve requireListed from it. Optionally push uiState changes over the port instead of letting pages poll.
  • Verifier: requireListed does refetch fetchPluginSessions per archive/trash/contextMenu with no cache, so bulk actions cost N extra list fetches. But these are user-triggered, one plugin page, no hot loop. The dashboard has no uiState poll in this area. Small win, and a cache risks stale authorization checks.
  • Measure: Open a kanban page, bulk-archive 20 sessions, count /api/plugins/*/sessions requests in the browser network tab.

#456 Wizard project picker downloads the full session list to derive recent projects

  • Impact low, effort S, verdict partly, evidence proven-by-code, area web-other-components, category network
  • Where: web/src/components/session-wizard/steps/projectPicker.ts:115-133
  • Frequency: Each time the wizard's project step mounts (and on Retry); payload scales with session count
  • Problem: useProjectPicker calls fetchSessions() (the whole sidebar envelope) just to collectRecentProjects, even though App already holds the same rows from its 3s poll and fetchRecentProjects exists.
  • Fix: Pass the already-loaded sessions into the wizard (or read from a shared store) and drop the fetchSessions call from the Promise.all in useProjectPicker.
  • Verifier: useProjectPicker does call fetchSessions() on each mount and Retry, duplicating the App poll. But it fires only when the user opens the wizard, add-project modal or extra-repos picker, once per open. Hook has three callers, so passing sessions means prop plumbing. Minor payload cost.
  • Measure: Open the wizard with 200 sessions and check the /api/sessions response size and latency in the network tab.

4.gap-create-launch-latency

#457 Global identity flock held across docker probes and git2 opens in plan_instance

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-create-launch-latency, category concurrency
  • Where: src/server/session_spawn.rs:313-432, src/session/builder.rs:762-772, src/session/builder.rs:780, src/session/builder.rs:946-1072, src/session/storage.rs:1013-1015
  • Frequency: Every create. Concurrent creates, such as aoe-batch-launch or plugin fan-out, serialize behind it
  • Problem: spawn_structured_session takes acquire_session_identity_lock, an app-wide exclusive flock, before plan_instance. Under that lock plan_instance runs docker --version and docker info for sandboxed creates (one fork each, docker info often 100-500ms), a full config resolve, about 4 git2 repo opens, list_worktrees and project_base_branches. Then it runs a full store.update. N parallel creates queue for N times that cost.
  • Fix: Move the lock-independent parts out of the locked section: run the sandbox runtime probes, resolve_config_with_repo, find_main_repo/is_bare_repo/list_worktrees and project_base_branches in a new builder::prepare_plan_inputs(&params, profile) before acquire_session_identity_lock. Keep only title/branch dedupe and store.update under the lock.
  • Verifier: The app-wide identity flock (session_spawn.rs:314) is held through plan_instance, which runs docker --version/info (builder.rs:762-772), resolve_config_with_repo and the git reads, and through store.update. Moving the docker probes and config resolve out is safe. list_worktrees feeds worktree path collision checks, so it should stay under the lock. This only hurts concurrent fan-out.
  • Measure: Launch 5 sandboxed structured creates in parallel and log how long each waits on acquire_session_identity_lock and how long it holds it.

#458 Network git fetch on every worktree create, with no freshness window

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-create-launch-latency, category network
  • Where: src/git/worktree/create.rs:146-165, src/git/worktree/create.rs:48-99, src/git/worktree/create.rs:204-224
  • Frequency: Every worktree or workspace create (one fetch per repo), up to 10s each
  • Problem: create_worktree_tracked always runs git fetch <remote> <branch> before it creates the branch. It also runs prune, plus an unlock on a path already shown not to exist. The fetch is a network round trip, often 0.5-3s and capped at 10s, on the critical path before the agent can start. A second create from the same repo seconds later fetches the same ref again.
  • Fix: In fetch_base/fetch_with_warning, skip the fetch when refs/remotes/<remote>/<base> (or FETCH_HEAD) was updated less than N seconds ago, for example 60s. Use a worktree.fetch_max_age_secs setting declared with #[setting]. Also skip unlock_worktree unless $GIT_DIR/worktrees/*/gitdir names this path.
  • Verifier: The fetch runs on every create (create.rs:150-161), with a 10s cap. It is intentional: it gives the freshest base (#1511), and its timings are already logged. The unlock claim is wrong: a stale entry exists exactly when the path is missing, and the comment at line 144 explains this. A ref-mtime TTL is unreliable with packed refs. Use an in-process (repo, remote, branch) TTL for fan-out instead.
  • Measure: Run grep 'fetch step done in' over the daemon log across 20 real creates to get the fetch latency distribution.

#459 About 10 uncached full config resolves per create

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-create-launch-latency, category latency
  • Where: src/server/api/sessions/create.rs:1115, src/server/api/sessions/create.rs:312-321, src/server/api/sessions/create.rs:1172-1199, src/server/session_spawn.rs:178, src/server/session_spawn.rs:243, src/session/builder.rs:780, src/server/session_spawn.rs:449, src/session/instance/hooks.rs:329, src/session/instance/hooks.rs:367-373, src/server/session_spawn.rs:973, src/acp/supervisor/launch.rs:435-440, src/session/config/profile_config.rs:183-196
  • Frequency: Per create; each resolve reads and parses global, app_state, profile and repo TOML, opens git2 via repo_config_source_path, and reinstalls status rules
  • Problem: These are separate resolves of the same profile and repo config: handler validation, validate_structured_choice (plus a profile resolve in preparation_hooks), native.configuration, check_repo_trust, plan_instance, the post-provision resolve, run_pre_launch_hooks twice, launch_configuration, spawn_config and MCP resolution. There is no cache. Each one parses TOML and redoes install_from_config.
  • Fix: Resolve once in spawn_structured_session. Pass an Arc<Config> into plan_instance (a new parameter), run_pre_launch_hooks/run_launch_hooks (replace the store.configuration calls) and SpawnRequest (a new resolved_config field used by spawn_config). Or add an mtime-keyed cache inside profile_config::resolve_config.
  • Verifier: Repeated uncached resolves are real: resolve_config reads global, app_state and profile TOML and reinstalls status rules on every call, and the repo variant adds a git2 open. Each costs about 1-3ms, so 10 resolves cost tens of ms against a multi-second create (fetch, hooks, agent spawn). Threading one Config through also changes when config edits made mid-create take effect.
  • Measure: Wrap resolve_config in a tracing span with its duration and sum the spans for one create in the daemon log.

#460 Repeated full sessions-file loads and rewrites on one create

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-create-launch-latency, category disk-io
  • Where: src/server/session_spawn.rs:421, src/server/session_spawn.rs:627, src/server/session_spawn.rs:803, src/server/session_spawn.rs:816, src/server/session_spawn.rs:974, src/acp/supervisor/launch.rs:255, src/acp/supervisor/launch.rs:294, src/acp/supervisor/launch.rs:362, src/acp/supervisor/launch.rs:1179-1229, src/server/session_spawn.rs:1176-1199, src/session/storage.rs:2528-2580
  • Frequency: Per structured create: about 5 full read+write commits and 4 more uncached full loads. Each scales with session count in the profile
  • Problem: Every store.update runs update_under_lock: a full load_bundle, the mutation, a full rewrite, then adopt_committed_profiles. The create commits the Creating row, publication, Starting and adopt_runtime_fields, then commit_created_launch. The spawn task calls native.load() once and with_durable_launch three more times (admit before config, after config, after handshake). None of these reads uses SessionsFileCache.
  • Fix: Fold the publication update (session_spawn.rs:627) into the Starting update (803) when no hooks ran. In with_durable_launch, use storage.load_complete_with_groups_cached with a SessionsFileCache held on LaunchAdmission, so unchanged files are not reparsed. Drop the redundant native.load() at session_spawn.rs:974, since spawn_inner's first admit checks the same generation.
  • Verifier: The count holds: store.update runs update_under_lock with a full load_bundle and rewrite, and with_durable_launch (launch.rs:1179) calls store.load() uncached. But this runs once per create, off the async runtime via spawn_blocking, and the ACP handshake dominates. The check at session_spawn.rs:974 also takes title locks and runs launch_configuration, so dropping it changes failure semantics.
  • Measure: Wrap load_bundle and the rewrite in update_under_lock with tracing spans, then time one structured create with 50 and with 500 sessions in the profile.

#461 Kiro launch forks kiro-cli twice per launch, with no timeout

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-create-launch-latency, category subprocess
  • Where: src/session/instance/hooks.rs:831-840, src/hooks/kiro.rs:161-193, src/hooks/kiro.rs:101-104
  • Frequency: Every host Kiro session launch or restart with hook events
  • Problem: install_sidecar_host_hooks calls post_install_host (set_kiro_default_agent_if_builtin) after every successful install, even when the hooks file was unchanged (log_unchanged). That runs kiro-cli settings chat.defaultAgent and possibly kiro-cli agent set-default through Command::output(), synchronously and with no timeout. A hung kiro-cli blocks the launch indefinitely.
  • Fix: Make the sidecar install fn return whether it wrote (bool, as install_codex_json_hooks does), and call post_install only on a write. Wrap both kiro-cli calls in crate::process::run_with_timeout with a 5s cap.
  • Verifier: hooks.rs:831-838 calls post_install_host whenever install returns Ok and events are non-empty. The Kiro installer returns Ok(()) on log_unchanged (kiro.rs:101-104), so every launch runs one or two synchronous kiro-cli Command::output() calls with no timeout. Only host Kiro users pay this. The hang risk matters more than the latency.
  • Measure: Time kiro-cli settings chat.defaultAgent --format json with hyperfine, and add a span around post_install() in install_sidecar_host_hooks.

#462 First prompt waits on a full runtime publish after the handshake

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-create-launch-latency, category latency
  • Where: src/server/session_spawn.rs:1066-1078, src/server/session_spawn.rs:1157-1200, src/server/runtime.rs:278-300
  • Frequency: Per structured create that carries an initial_turn (plugins, CityHall, MCP create with prompt)
  • Problem: After spawn_inner succeeds, finish_structured_launch commits Idle and then awaits state.runtime.publish. That publish takes publish_lane, projects every session (project_sessions) and computes ordering. Only after it finishes does drain_pending_initial_turn deliver the first prompt. The prompt therefore waits on an O(N sessions) projection that it does not depend on, and on any queued publish.
  • Fix: In finish_structured_launch, replace state.runtime.publish(state).await? with state.runtime.request_publish() (coalesced), or in the spawn task start drain_pending_initial_turn before awaiting the publish. The publish is still issued, just not ahead of the prompt.
  • Verifier: Code matches: publish awaited before drain at session_spawn.rs:1066-1078. But publish is in-memory projection (ms for typical N). request_publish only wakes a loop, changing ordering and the error-propagation of ?; clients may rely on Idle being published before the prompt. Win is tiny.
  • Measure: Wrap state.runtime.publish in finish_structured_launch with Instant timing and tracing log; create a session with initial prompt at 50 sessions.

#463 Status-hook install resolves profile config 3 to 5 times per launch

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-create-launch-latency, category latency
  • Where: src/session/instance/hooks.rs:629-631, src/session/instance/hooks.rs:655-659, src/session/instance/hooks.rs:744-754, src/session/instance/container.rs:356-358, src/session/instance/container.rs:1712-1714
  • Frequency: Per terminal launch and per sandboxed launch, through install_agent_status_hooks and ensure_host_folder_trust
  • Problem: install_agent_status_hooks calls resolve_config_or_warn, then resolved_host_environment, which calls profile_host_environment and resolves again. ensure_host_folder_trust resolves once, then calls resolved_host_environment twice, two more resolves. Each one rereads and parses three TOML files and reinstalls status rules.
  • Fix: Have run_launch_hooks resolve once and pass &Config into install_agent_status_hooks and ensure_host_folder_trust. Add resolved_host_environment_with(&config.environment) (the existing resolved_host_environment_from) and compute the environment once in each function.
  • Verifier: Verified: install_agent_status_hooks resolves twice (hooks.rs:629, 655-659 via profile_host_environment), ensure_host_folder_trust three times (container.rs:356, two resolved_host_environment calls). No cache in resolve_config_or_warn. Each is small TOML parse, sub-ms to few ms per launch; fix is trivial but win small.
  • Measure: Count resolve_config calls per launch via a tracing counter, and time resolve_config_or_warn with criterion on a typical profile.

#464 Web wizard fetches /api/about before every create POST

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-create-launch-latency, category latency
  • Where: web/src/components/session-wizard/SessionWizard.tsx:695, web/src/lib/api.ts:1571-1573, src/server/api/system.rs:2303-2310
  • Frequency: Every wizard Launch with an idempotency key (all web creates), one extra serial round trip
  • Problem: sendCreate awaits fetchCreateBootId(), which fetches the full /api/about, before it sends POST /api/sessions. The about handler takes the namespace read lock and does a synchronous resolve_config_or_warn file read on the async runtime. On remote or mobile links this adds a full RTT before creation starts. The boot id only changes when the daemon restarts.
  • Fix: Fetch create_boot_id once when SessionWizard mounts (it already prefetches settings and profiles) and reuse it in sendCreate. Separately, wrap the resolve_config_or_warn in get_about in spawn_blocking.
  • Verifier: sendCreate awaits fetchCreateBootId (full /api/about) at SessionWizard.tsx:695 before POST; get_about does sync config read under namespace read lock. One extra RTT is real on remote links. Caveat: boot id is deliberately read fresh before first send, so prefetch at mount risks stale id after a restart.
  • Measure: Browser devtools Network tab on Launch with 200ms throttling; compare time from click to POST /api/sessions start.

#465 Create handler does blocking config and file I/O on the async runtime

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-create-launch-latency, category latency
  • Where: src/server/api/sessions/create.rs:1115-1125, src/server/api/sessions/create.rs:312-336, src/server/api/sessions/create.rs:949, src/server/api/sessions/create.rs:989-994
  • Frequency: Per create with a custom (non-registry) tool; CityHall creates always
  • Problem: validate_session_tool_identity calls resolve_config_with_repo directly in async create_session_with when the tool is not a built-in agent. In CityHall mode, projects::load_merged and agent_is_acp_capable (another resolve) also run inline. These are synchronous TOML reads and git2 opens on a tokio worker thread.
  • Fix: Move validate_session_tool_identity, and the CityHall load_merged plus agent_is_acp_capable, into the existing spawn_blocking at create.rs:1139, returning one struct with all verdicts. That also removes one duplicate resolve.
  • Verifier: Sync resolve_config_with_repo in validate_session_tool_identity (create.rs:312-336) and CityHall load_merged/agent_is_acp_capable do run inline on the async handler. But built-in tools short-circuit via get_agent, and the later ACP check is already in spawn_blocking. Only custom-tool and CityHall paths affected; ms-scale blocking.
  • Measure: Run tokio-console or log elapsed time around validate_session_tool_identity for a custom tool create with a large repo config.

#466 Redundant git2 repo opens and per-project find_main_repo in plan_instance

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-create-launch-latency, category latency
  • Where: src/session/builder.rs:946-962, src/session/builder.rs:1063-1072, src/session/builder.rs:249-260, src/session/builder.rs:320-372, src/git/worktree/mod.rs:120-151
  • Frequency: Per worktree create, under the identity lock; project_base_branches scales with registered projects that set a base branch
  • Problem: The worktree branch path opens the same repo with git2 several times: is_git_repo, find_main_repo, GitWorktree::new, is_bare_repo, list_worktrees, then resolve_repo_base_branch calls find_main_repo again. project_base_branches calls project_root_key, which calls find_main_repo, for every registered project with a default base, opening each project's repo. The comment at mod.rs:130 says opens are costly in repos with many worktrees.
  • Fix: Open the repo once in plan_instance and derive is_bare and main_repo from that handle. Pass main_repo_path into resolve_repo_base_branch instead of rediscovering it. In project_base_branches, look up only the key for the repos being built instead of resolving every registered project's root.
  • Verifier: Repeated find_main_repo calls exist (builder.rs:956, resolve_repo_base_branch:255, project_root_key per project with base). But find_main_repo reads the linked-worktree gitfile before opening git2, so the cost is mostly cheap file reads. Scales only with projects that set a default base. Worktree creation itself dominates.
  • Measure: Time plan_instance phases with tracing spans on a worktree create with 20 registered projects setting default_base_branch.

#467 TUI new-session dialog forks the container runtime on the UI thread when it opens

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-create-launch-latency, category latency
  • Where: src/tui/dialogs/new_session/mod.rs:503-519, src/containers/mod.rs:49-53, src/containers/runtime_base.rs:287-296
  • Frequency: Every time the TUI new-session dialog opens
  • Problem: NewSessionDialog::new calls get_container_runtime().is_available(). That does Config::load and then synchronously forks docker --version (bounded by RUNTIME_CMD_TIMEOUT) on the TUI event thread, before the dialog renders. It then resolves config with the repo as well. A slow or hung Docker CLI stalls the open.
  • Fix: Compute docker_available once per TUI run, cached in the App, or on a background thread that updates the dialog via a channel. Pass it into NewSessionDialog::new as a parameter instead of probing inside the constructor.
  • Verifier: Claim holds: new() runs Config::load plus a sync docker --version on the TUI thread (RUNTIME_CMD_TIMEOUT is 60s). But it fires only on a user keypress, and --version is client-only and fast. Hang risk is real but rare. A cached or async probe is a feasible fix.
  • Measure: Time NewSessionDialog::new with Instant around the is_available call, using a real docker, then a PATH shim docker that sleeps.

4.gap-stop-delete-shutdown-latency

#468 Sandboxed or workspace purge runs in-container find -delete, docker rm, and git removals while holding every profile's storage lock

  • Impact low, effort L, verdict partly, evidence plausible-needs-measurement, area gap-stop-delete-shutdown-latency, category concurrency
  • Where: src/session/deletion.rs:1347-1378, src/session/deletion.rs:1544-1553, src/session/deletion.rs:1656-1716, src/git/cleanup.rs:422-476, src/session/storage.rs:3678-3708, src/containers/mod.rs:361-367
  • Frequency: Each purge (delete, empty trash, retention sweep, group delete) of a sandboxed or multi-repo workspace session that has delete_worktree set. Duration scales with worktree size (node_modules, target/) and the number of workspace repos.
  • Problem: with_paths_in_use_locked takes the transition flocks and save mutexes of every profile, then runs stage_teardown_worktrees. That calls cleanup_sandbox_worktree (docker inspect plus exec find . -mindepth 1 -delete), teardown (rm -f plus volume removal), and stage_remove_worktrees_and_branches for workspaces. All sessions.json writes daemon-wide block for seconds or minutes. Only plain worktrees use the move-aside path.
  • Fix: Extend the move-aside pattern. Under the lock, decide and record a PurgeClaim (mark_for_purge) for the sandbox root and each workspace repo. Then return and run the preclean, container teardown, and git removals after with_paths_in_use_locked returns, as remove_moved_worktree already does.
  • Verifier: Confirmed preclean (container find -delete), teardown, and workspace git removals run inside with_storages_locked. But preclean only runs on a running container; a stopped sandbox returns Blocked at once. The lock guards the adoption race; moving aside a bind-mounted root is not proven safe on Docker Desktop, so the fix needs design.
  • Measure: Log elapsed time inside with_paths_in_use_locked while purging a running sandbox with a large node_modules worktree

#469 Group delete and empty trash purge members one at a time, each with full ACP retirement, under all locks

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-stop-delete-shutdown-latency, category latency
  • Where: src/server/api/groups.rs:528-541, src/server/api/groups.rs:589-660, src/server/api/sessions/delete.rs:933-1013, src/server/api/sessions/delete.rs:292-301, src/acp/supervisor/teardown.rs:142-175, src/acp/supervisor/teardown.rs:1319-1350
  • Frequency: Per group delete with DeleteSessions, and per empty-trash request. Time grows linearly with member count.
  • Problem: Each structured member awaits finish_structured_purge. That makes the session/delete RPC (up to 2.5s), the session/close RPC (up to 2.5s), the connection shutdown (up to 2s), SIGTERM plus 50ms polls (up to 2s), and SIGKILL (0.5s), followed by worktree and branch removal. Members run strictly one after another. Every member's instance lock and the purge namespace lease stay held until the last one finishes, which blocks all other deletes.
  • Fix: In delete_group_owned and empty_trash_owned, drive purge_session_artifacts over members with futures::stream::iter(..).buffer_unordered(4). The per-row locks are already held, and the storage flocks still serialize the store commits. Another option: first retire every structured worker concurrently with join_all over shutdown_captured_and_delete_and_wait, then purge serially.
  • Verifier: Serial loop confirmed (groups.rs ~589-660, delete.rs ~947-1013), and the namespace lease plus all instance guards stay held. The cited 2.5s/2s values are timeout ceilings; a healthy runner exits in milliseconds. Git worktree/branch removal likely dominates, and running buffer_unordered on one repo causes index.lock contention. Retiring workers with join_all, then purging serially, is the safer fix.
  • Measure: Add tracing spans around finish_structured_purge and worktree removal in purge_session_artifacts, then delete a group of 10 structured sessions and compare the elapsed_ms values.

#470 Daemon shutdown runs plugin reap, work drain, and serial detach_all one after another under a 5s force-exit

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-stop-delete-shutdown-latency, category latency
  • Where: src/server/startup.rs:200-241, src/server/startup.rs:1511-1533, src/acp/supervisor/teardown.rs:896-930, src/acp/acp_client/mod.rs:1137-1175
  • Frequency: Every daemon SIGTERM, serve --stop, or restart. detach_all scales with the number of live structured sessions.
  • Problem: The shutdown sequence awaits the plugin reap (up to 4s), then work.drain(), then detach_all, which awaits client.shutdown() for one worker at a time. Each call can take up to 2s for the connection grace, and prime-native clients add a session/close of up to 2.5s. With several prime sessions or a slow drain, the 5s force-exit fires and skips detach, tunnel SIGTERM, and passphrase removal.
  • Fix: In detach_all, take ownership under the lock as today, then run the per-client shutdown plus quiesce_retained_drain with futures::future::join_all. In start_server, start detach_all concurrently with the plugin reap, for example tokio::join!(signal_task, async { drain; detach_all }), because ACP runners do not depend on plugins.
  • Verifier: Confirmed: detach_all (teardown.rs ~895-929) awaits client.shutdown serially, and it runs after the signal_task reap (up to 4s) and work.drain (startup.rs ~1511-1520). shutdown() cancels the connection first, so the 2s grace only applies to a hung task. Only prime-native clients add a close RPC. Each lease has its own gate, so join_all is safe and cheap.
  • Measure: Run aoe serve --stop with 10 live structured sessions and read the 'daemon shutdown complete' elapsed_ms log, plus a timing of each detach call.

#471 Session::kill makes about 6 tmux spawns, including a full list-sessions rescan for every killed session

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-stop-delete-shutdown-latency, category subprocess
  • Where: src/tmux/session.rs:643-666, src/process/mod.rs:897-912, src/tmux/utils.rs:284-286, src/tmux/utils.rs:587-610, src/tmux/mod.rs:744-748, src/tmux/tool_session.rs:597-688, src/tmux/tool_session.rs:752-850
  • Frequency: Per terminal-session stop or delete, and per auxiliary tool session. Bulk delete of N sessions costs N full scans, so O(N^2) parsing.
  • Problem: kill calls first_pane_id, then set-option, then get_pane_pid (which calls first_pane_id again plus display-message), then kill-session, then refresh_session_cache(). That last call re-lists every tmux session. ToolSession::kill_verified adds about 4 more tmux spawns, a server-birth probe, 3 journal fsyncs, and another full refresh for each tool.
  • Fix: Resolve the pane once with display-message -p -t =name: '#{pane_id}\t#{pane_dead}\t#{pane_pid}' and reuse it for set-option. Chain set-option and kill-session in one tmux invocation where ordering allows. Replace the trailing refresh_session_cache() with an in-place removal of the killed name from the session cache, or mark the cache stale.
  • Verifier: About 6 tmux spawns confirmed (session.rs ~643-666: first_pane_id twice, set-option, display-message, kill-session, list-sessions), roughly 3-5ms each. kill_with_fallback (process/mod.rs ~2092) does an unconditional thread::sleep(100ms), which costs more than all the spawns together. The O(N^2) parsing is negligible at realistic N. utils.rs documents that callers refresh the cache after a kill.
  • Measure: Time Session::kill with Instant around each step on a test tmux socket. Compare the spawn total with the fixed 100ms sleep in kill_with_fallback.

#472 VtChannel/Osc52Channel drop runs blocking tmux and thread joins on tokio workers when terminal sockets close

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-stop-delete-shutdown-latency, category concurrency
  • Where: src/tmux/vt.rs:3361-3392, src/tmux/vt.rs:3593-3608, src/tmux/vt.rs:3657-3672, src/tmux/session.rs:2062-2093, src/server/live_ws.rs:1056-1090, src/server/live_ws.rs:1944-1960
  • Frequency: Per live terminal WebSocket close. On daemon shutdown, every open viewer closes at once, so cost scales with open terminal views.
  • Problem: The capture task owns the last Arc<VtChannel> or Osc52Channel. When it ends, Drop runs shutdown_with_deadline on a tokio worker: a tmux if-shell subprocess, socket connects, reader.join() (the OSC52 reader wakes every 200ms), and remove_dir_all. Many simultaneous closes stall the worker pool during graceful drain. Osc52Channel::acquire also runs blocking tmux calls and a 2ms sleep loop of up to 500ms on the async thread.
  • Fix: Have capture_task return its capture_vt and capture_osc52, then drop them together with vt and vt_slot inside the existing spawn_blocking that calls release_size_owner at the end of the handler. Wrap Osc52Channel::acquire in spawn_blocking like VtChannel::acquire_with_deadline.
  • Verifier: Drop does tmux subprocess plus reader.join() on a tokio worker, and Osc52Channel::acquire (live_ws.rs:1059) is sync on the async thread; both real. But the handler still holds vt/vt_slot clones, so moving only capture_* drops is incomplete. Only the last viewer per pane pays.
  • Measure: Open N viewers on distinct panes, SIGTERM the daemon, and log tokio worker block time (tokio-console or tracing around Drop).

#473 Prime-native stop sends session/close twice

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-stop-delete-shutdown-latency, category latency
  • Where: src/acp/supervisor/teardown.rs:149-170, src/acp/acp_client/mod.rs:1112-1146, src/acp/acp_client/close.rs:11
  • Frequency: Per stop or delete of a structured session backed by a native prime runtime.
  • Problem: retire_registered_clients_locked calls client.close_session() and records close_done. It then calls client.shutdown(), which calls close_session() again for native runtimes. That is an extra RPC round trip on every stop, and when the adapter is wedged it doubles the wait (two 2.5s timeouts) before SIGTERM.
  • Fix: Add an AtomicBool closed to AcpClient, set it when close_session returns. In shutdown, skip close_session when it is already set.
  • Verifier: teardown.rs:150 calls close_session, then client.shutdown() (mod.rs:1140) calls it again for native runtimes; no dedupe, so a wedged adapter costs two 2.5s timeouts. Fix is trivial: an AtomicBool on the client.
  • Measure: Stop a native structured session with a stub adapter that ignores session/close; time stop and count close requests received.

#474 Trash retention sweep ignores shutdown between candidates, so drain can hit the force-exit

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-stop-delete-shutdown-latency, category latency
  • Where: src/server/api/sessions/delete.rs:622-700, src/server/startup.rs:1229-1260, src/server/runtime.rs:117-133, src/session/deletion.rs:2461-2464
  • Frequency: When a daemon stop overlaps the startup or hourly trash sweep. The sweep length scales with the number of expired trashed sessions.
  • Problem: purge_expired_trash loops over every expired candidate without checking state.shutdown. Each purge can run before-destroy hooks (up to 120s) and git removals. RuntimeWork::drain waits for this task, so shutdown runs into the 5s force-exit and skips detach_all and the remaining cleanup.
  • Fix: At the top of the for id in candidates loop in purge_expired_trash, add if state.shutdown.is_cancelled() { break; }. The sweep is idempotent and resumes on the next start.
  • Verifier: purge_expired_trash loops candidates with no shutdown check. startup.rs:1516 awaits work.drain(), and the 5s force exit skips detach_all and cleanup. A top-of-loop is_cancelled check is safe. An in-flight purge is still uncancellable. Overlap is rare.
  • Measure: Trash several sessions with a slow before-destroy hook, backdate retention, start the daemon, SIGTERM during the sweep, and check for the forced-exit log.

4.gap-daemon-client-reconnect

#475 Every status WebSocket runs its own full runtime publish for every status change

  • Impact low, effort M, verdict partly, evidence proven-by-code, area gap-daemon-client-reconnect, category cpu
  • Where: src/server/session_status_ws.rs:214, src/server/session_status_ws.rs:105, src/server/runtime.rs:278-300, src/server/api/sessions/list.rs:40-130
  • Frequency: Per StatusChange, per connected /api/sessions/status/ws client (one per open web tab). A bulk start, or daemon startup recovery, emits one change per session.
  • Problem: serve() calls state.runtime.publish() for each change it receives. With T tabs, one change costs T serialized publishes through publish_lane. Each publish runs project_sessions: about 4 SQLite lookups per session, a disk read for claude settings, and resume config reads, then a full contents comparison. A 50-session recovery cascade with 4 tabs costs 200 full projections. frame_for also scans every session linearly for each change.
  • Fix: Make the publish single-flight. Give Runtime a publish generation counter. A status socket stamps the change with the current generation, calls request_publish(), and waits on runtime.snapshots until a publication that started after that stamp lands. publish_loop then runs one projection for all sockets, and the invariant 'publication began after the move' still holds.
  • Verifier: Confirmed: serve() calls runtime.publish per Next::Change per socket, serialized on publish_lane, each running project_sessions (per-session SQLite lookups, read_tui_fullscreen disk read). But T is the open tab count (usually 1 to 3) and changes are status moves, not a tick. frame_for scan is negligible. Single-flight is sound but the win is small.
  • Measure: Add a tracing span around project_sessions in publish(); start 50 sessions with 3 tabs open and count publishes and total ms.

#476 Runtime WS connect and GET runtime info/snapshot each force an inline publish, plus a redundant wake

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-daemon-client-reconnect, category latency
  • Where: src/server/runtime.rs:684-688, src/server/runtime.rs:615, src/server/runtime.rs:627, src/server/runtime.rs:787-802
  • Frequency: Per /api/runtime/ws connect (TUI session feed, CLI), per GET runtime info/snapshot. On a daemon restart, every TUI and CLI client reconnects at once.
  • Problem: follow_runtime calls request_publish(), which wakes publish_loop for a second projection, and then awaits publish() inline. K clients that reconnect together queue 2K full project_sessions runs behind one publish_lane mutex. The last client waits through all of them before it gets Hello. This happens while startup recovery is also publishing.
  • Fix: Remove the request_publish() call in follow_runtime because the inline publish already covers it. Route follow_runtime, get_runtime_info and get_runtime_snapshot through the same single-flight publish: if a publish is in flight, await its result through runtime.snapshots instead of taking a new turn on publish_lane.
  • Verifier: follow_runtime does request_publish() then an inline publish(), so the loop runs one redundant projection per connect. Removing the wake is safe. But publish_loop already runs every 500 ms with subscribers, and reconnecting clients are a TUI plus a CLI or two, so the queue is short.
  • Measure: Time from WS upgrade to Hello send in follow_runtime with tracing, reconnecting 5 clients at once after daemon restart.

#477 Web WebSocket reconnect backoff has no jitter, so all tabs redial in lockstep after a daemon restart

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-daemon-client-reconnect, category network
  • Where: web/src/hooks/acpSession/useAcpConnection.ts:22-28, web/src/hooks/acpSession/useAcpConnection.ts:231-257, web/src/lib/wsBackoff.ts:8-15, web/src/hooks/useSessionStatusStream.ts:61-64, web/src/hooks/useLiveTerminal.ts:351-371
  • Frequency: Per disconnect of every web socket: each tab has one status WS, one ACP WS per open structured view, and live terminals. This happens on every daemon restart or network blip.
  • Problem: The delays are deterministic: ACP uses 1, 2, 4, 8, 16, 30 s; status and terminal use 200, 400, 800 ms up to 10 s. With T tabs and V views per tab, T status sockets redial at exactly +200 ms, and each resyncs GET /api/sessions. T x V ACP dials then land at +1 s. Each dial makes 2 or more replay GETs, then a WS that does replay_from(0), a full fold, and a full transcript_snapshot. Failed waves repeat in sync.
  • Fix: Add full jitter to acpRetryDelayMs and retryDelayMs, for example base * (0.5 + Math.random() * 0.5). The status socket can also jitter its first retry by 0 to 500 ms. One shared helper in wsBackoff.ts covers all three transports.
  • Verifier: No jitter: retryDelayMs (wsBackoff.ts) and acpRetryDelayMs are deterministic; no Math.random in backoff code. But this is a local single-user daemon with a few tabs; early redials fail fast while the daemon is down, so the herd is a handful of requests. Jitter is a cheap hygiene fix, not a measurable win.
  • Measure: Restart the daemon with 4 tabs open on structured views; log request arrival timestamps and handler latency for the first 2 seconds.

#478 One global ACP broadcast channel: every ACP socket wakes for every session's events, and lag hits all slow sockets together

  • Impact low, effort L, verdict partly, evidence plausible-needs-measurement, area gap-daemon-client-reconnect, category concurrency
  • Where: src/server/state.rs:19, src/server/acp_ws.rs:118, src/server/acp_ws.rs:219-224, src/server/acp_ws.rs:262-320, web/src/hooks/acpSession/useAcpConnection.ts:287-293
  • Frequency: Per ACP event, multiplied by every open ACP WS connection across tabs, the TUI and remote clients. Streaming agents emit many events per second.
  • Problem: acp_events_tx has capacity 256 and is shared by all sessions. Each connection receives every frame and drops the ones for other sessions, so wakeups scale as connections x total events. A burst from one session lags slow tunnel clients on unrelated sessions. Each of those then runs replay_from(0) plus a full transcript rebuild, and the web client also starts an HTTP replay.
  • Fix: Replace the single sender with per-session senders: Mutex<HashMap<String, broadcast::Sender<AcpBroadcastFrame>>> in AppState, created on the first subscribe and removed when receiver_count reaches 0. acp_ws subscribes only to its session. Publishers look up the session's sender. Lag then stays within one session.
  • Verifier: Single global acp_events_tx (cap 256, startup.rs:700) confirmed; acp_ws filters by session_id. Skipped frames cost an Arc clone plus string compare, cheap. Cross-session lag happens only while a socket blocks on its own sends. Other subscribers (resume.rs, view.rs, plugin session_api, api/acp) use the global channel, so per-session senders are a broad refactor.
  • Measure: Count RecvError::Lagged in acp_ws (log target acp.ws) while 5 sessions stream concurrently over a throttled tunnel client.

#479 Each remote wss connect reloads the OS root certificate store synchronously

  • Impact low, effort S, verdict confirmed, evidence plausible-needs-measurement, area gap-daemon-client-reconnect, category latency
  • Where: src/daemon/websocket.rs:120-124, ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-tungstenite-0.30.0/src/tls.rs:91-100
  • Frequency: Per remote WebSocket connect: structured view open, each of the 3 reconnect attempts, RuntimeConnection connect, and acp tail. Only through tunnel or HTTPS endpoints.
  • Problem: connect_async_with_config passes no connector, so tokio-tungstenite runs rustls_native_certs::load_native_certs() and builds a new ClientConfig on every TLS connect. On macOS this enumerates the Keychain, which takes tens to hundreds of ms. It is blocking work on an async worker thread, and the cost repeats on every reconnect attempt.
  • Fix: Build the rustls ClientConfig with native roots once in a static OnceLock<Arc<rustls::ClientConfig>>. Call tokio_tungstenite::connect_async_tls_with_config(request, Some(config), true, Some(Connector::Rustls(cfg.clone()))) in connect_with_headers. The localhost branch keeps its current path.
  • Verifier: websocket.rs:120-122: non-localhost branch calls connect_async_with_config with no connector; tokio-tungstenite tls.rs:91-100 then calls rustls_native_certs::load_native_certs() per connect on the async worker. Feature rustls-tls-native-roots is set in Cargo.toml:191. Affects remote/tunnel wss only, a rare per-connect path, so the cost is likely low.
  • Measure: Time load_native_certs() in a scratch bin on macOS, or wrap connect_with_headers in tracing span and compare first vs cached-config connects over a tunnel.

#480 Web ACP client re-fetches replay over HTTP after a lag that the server already rebuilt and resent

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-daemon-client-reconnect, category network
  • Where: web/src/hooks/acpSession/useAcpConnection.ts:287-293, web/src/hooks/acpSession/replay.ts:149-189, src/server/acp_ws.rs:262-320
  • Frequency: Per 'lagged' notice on each ACP socket. With the shared 256-slot channel, this hits all slow sockets at once.
  • Problem: On lag, the server sends 'lagged', runs replay_from(0), and resends reduced_state plus a full transcript_snapshot. The client also calls startReplay(), which runs fetchForward with both legs, frames and rows, for every page since lastSeq-50. The rows leg duplicates the transcript_snapshot that arrives on the same socket.
  • Fix: On 'lagged', call fetchForward with legs="frames" only, because the frames leg feeds control state that the daemon does not model. The socket's transcript_snapshot then covers rows. A small option on startReplay can pass the leg through.
  • Verifier: Duplicate rows leg is real: startReplay fetches both legs while the socket also sends transcript_snapshot. But lag is rare and replay pages are cheap. The fix needs care so the snapshot and rows reducers do not race with the frames leg.
  • Measure: Force a Lagged in acp_ws via a tiny channel in a test and count /replay requests and bytes in devtools.

#481 Unix-socket daemon transport opens a new connection and HTTP/1 handshake on every request

  • Impact low, effort M, verdict partly, evidence proven-by-code, area gap-daemon-client-reconnect, category latency
  • Where: src/daemon/transport.rs:328-371, src/daemon/transport.rs:287-297
  • Frequency: Per DaemonClient request over the local Unix socket from the TUI or CLI: mutations, plugin UI polls, queue refreshes.
  • Problem: execute_with_peer runs UnixStream::connect, a getsockopt peer-uid check, a hyper handshake and a tokio::spawn for each request. The daemon side accepts the connection and runs SO_PEERCRED again. The cost per call is small, but it adds up for periodic pollers.
  • Fix: Keep a cached hyper::client::conn::http1::SendRequest in DaemonClient behind a tokio Mutex. Reuse it while sender.is_ready() and the peer matches, and reconnect only when it closes. The expected_peer path can keep a fresh connection.
  • Verifier: Code does connect, handshake and spawn per request, as claimed. But a local Unix connect costs about tens of microseconds, and callers are low-rate. Reuse adds closed-connection and peer-check complexity, and a stale connection can fail requests.
  • Measure: Microbench 1000 sequential DaemonClient GETs over the Unix socket versus a reused SendRequest.

#482 Cloudflared health monitor polls try_wait every 10 s, so a dead tunnel is detected up to 10 s late

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-daemon-client-reconnect, category latency
  • Where: src/server/tunnel.rs:498-521
  • Frequency: Every 10 s for the life of a Cloudflare tunnel daemon.
  • Problem: The monitor sleeps 10 s, locks the child and calls try_wait. A cloudflared crash leaves remote clients failing reconnects for up to 10 s before the restart. The loop also wakes 0.1 times per second while idle.
  • Fix: In spawn_health_monitor, select! on child.lock().await.wait() and cancel.cancelled(), with shutdown() signalling through cancel before it kills the child. This removes the 10 s sleep and lets the restart run on the exit event.
  • Verifier: 10s poll is real but cloudflared crashes are rare and restart takes seconds anyway. Proposed fix deadlocks: wait() under the child mutex blocks shutdown(), which locks the same mutex before killing. Needs a pid or restructure.
  • Measure: Kill cloudflared with SIGKILL during aoe serve --remote and time from kill to the 'restarting' log line.

#483 Remote home refresh makes two sequential round trips through the tunnel and blocks input

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-daemon-client-reconnect, category latency
  • Where: src/tui/remote_home/mod.rs:262-283, src/tui/remote_home/mod.rs:198-203
  • Frequency: At startup and per 'r' keypress in the remote TUI picker.
  • Problem: refresh awaits list_sessions and then plugin_ui_state in sequence, so it costs 2 tunnel round trips, each with its own TLS setup per call. Key handling waits during both.
  • Fix: In refresh, run the two calls with tokio::join!(state.client.list_sessions(None), state.client.plugin_ui_state()) and apply both results after the join.
  • Verifier: Calls are sequential (mod.rs:262-283), so join! saves one RTT on 'r' and startup. But the daemon client holds a shared reqwest::Client (daemon/mod.rs:72), so connections are pooled and there is no TLS setup per call. Win is one RTT only.
  • Measure: Time refresh() against a remote tunnel endpoint with tracing timestamps around each await.

4.gap-session-store-service

#484 Lifecycle commit observer builds JSON summaries for every row twice per commit

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-session-store-service, category cpu
  • Where: src/session/storage.rs:2579-2583, src/session/storage.rs:2629-2632, src/session/lifecycle.rs:32-56, src/session/lifecycle.rs:231-297, src/plugin/host_api.rs:543-574, src/server/startup.rs:1380-1383
  • Frequency: Every Storage::update in the daemon (per prompt touch, queue mutation, status commit), always on when plugin_host exists (default non-read-only)
  • Problem: rows_of runs over the whole profile before and after the mutation, building LifecycleRow with a sorted checkouts Vec and a serde_json session_summary Value per session. tracker.commit then clones each after-row into self.rows. This runs under the storage flock, lengthening every write. Cost O(sessions in profile) allocations per commit, though summaries are only needed for the few rows that change.
  • Fix: Split LifecycleRow into a cheap key (id, profile, title, archived, trashed, checkouts) and build session_summary lazily in lifecycle::change() only when a LifecycleChange is emitted. In LifecycleTracker::apply_row skip the *tracked = row.clone() when nothing differs.
  • Verifier: Claim is accurate: rows_of runs twice under flock and builds a small session_summary JSON per row, only when a plugin host exists. But the same commit does serde to_vec_pretty of the whole file plus atomic write and fsync, which dwarfs these allocations. Lazy summary also requires an Instance at change() time.
  • Measure: Add a tracing span around both rows_of calls in update_under_lock and compare with the write plus sync_parent duration for 200 sessions.

#485 observe_disk rebuilds lifecycle rows for all sessions on every disk wake

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-session-store-service, category cpu
  • Where: src/server/lifecycle_feed.rs:122-153, src/server/disk_watch.rs:314, src/session/lifecycle.rs:181-228
  • Frequency: Every disk_watcher_consumer iteration, plus AGAIN_DELAY 250 ms retries while suspects exist
  • Problem: observe_disk maps every loaded instance across all profiles to LifecycleRow (session_summary JSON + checkouts Vec) and tracker.observe builds a HashSet of all keys and clones every row into the tracker. Combined with the self-write echo this runs after almost every daemon commit even though the commit observer already applied the same rows.
  • Fix: Same lazy-summary LifecycleRow as the commit-observer fix; additionally, in LifecycleFeed::observe_disk compare per-profile DataFileStamp against those last seen via on_commit and skip rows of profiles whose file is unchanged since the last commit.
  • Verifier: observe_disk maps every loaded instance to LifecycleRow on each wake and 250 ms retry, even without a plugin host. The cost is small next to the full JSON parse that precedes it. Skipping unchanged profiles conflicts with the suspect and missing-row logic in tracker.observe, so the fix needs care.
  • Measure: Instrument observe_disk duration versus load_profiles_for_reload duration in disk_watcher_consumer with 300 sessions.

#486 Identity drain deep-clones the full instances Vec every status tick

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-session-store-service, category memory
  • Where: src/server/session_identity.rs:82-143, src/server/status_poll.rs:403, src/server/status_poll.rs:461-465
  • Frequency: Every status poll tick: 500 ms with dashboard subscribers, 2 s otherwise
  • Problem: drain_session_id_updates_in_state clones every Instance (including queued_prompts up to 100 x 256 KiB text each, worktree info, conversation bindings) and builds a baseline HashMap and repair_backoffs map for all rows, even when no poller has an update and no repair is due. Write-back does guard.iter_mut().find per mutated row, O(N^2), and mutated is the whole snapshot.
  • Fix: Under the read lock, first select only rows with a pending poller observation or capture_poller.repair_due(now) and not structured; clone only those into the blocking task (return early if none). In the write-back, build a HashMap<&str, usize> index of guard once instead of find per row.
  • Verifier: The full clone runs every tick (session_identity.rs:85). The proposed fix breaks things: drain_and_persist_session_ids_inner builds sid_owners from ALL rows for cross-claim collision checks (sync.rs:175-189), and the repair walk needs contended_capture_cwds over all rows. Write-back O(N^2) only runs on ticks with changes. The same tick already reloads and walks every row.
  • Measure: Wrap drain_session_id_updates_in_state in a tracing span with elapsed_us and row count; check p99 at 50 sessions with 500 ms ticks.

#487 Worker registry read and liveness-probed on every tick and disk wake

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-session-store-service, category subprocess
  • Where: src/server/structured_repair.rs:20-45, src/server/structured_repair.rs:50-62, src/server/status_poll.rs:572, src/server/disk_watch.rs:290, src/process/worker_registry.rs:458-486, src/process/worker_registry.rs:598-608
  • Frequency: Every status poll tick (500 ms / 2 s) plus every disk_changed wake
  • Problem: live_structured_worker_records reads and parses every worker JSON and runs is_record_live (process_birth_identity, process_executing, socket stat) for each, then repair_structured_rows_from_live_workers only uses records whose session row is NOT structured, which is normally none. Cost scales with live ACP worker count, about 3 syscalls plus a JSON parse per worker per tick.
  • Fix: Pass the set of non-structured row ids into live_structured_worker_records (available from fresh in both call sites) and filter records by session_id membership before calling is_record_live; return early without reading the directory when no non-structured row exists.
  • Verifier: live_structured_worker_records reads, parses and runs is_record_live (birth identity, executing, socket stat) for every worker. repair_structured_rows_from_live_workers then skips structured rows, which is normally all of them. The work runs in spawn_blocking, so the cost is a few syscalls per worker per tick. The waste is real but small.
  • Measure: Count is_record_live calls per tick with a tracing counter. Time live_structured_worker_records with 20 live ACP workers.

#488 Every live prompt rewrites the whole profile file to bump last_accessed_at

  • Impact low, effort M, verdict partly, evidence proven-by-code, area gap-session-store-service, category disk-io
  • Where: src/server/session_service.rs:957-1002, src/server/session_service.rs:2837-2844, src/server/session_store.rs:370-421
  • Frequency: Once per user/plugin prompt on any structured session
  • Problem: touch_and_wake_on_prompt_inner always runs store.update even for a live, unparked session where the only change is last_accessed_at advancing. That takes reload_gate exclusively, the publication write lock, identity/title/lifecycle flocks, pretty-serializes and fsyncs the full profile sessions.json, adopts rows, and triggers the reload echo. Cost scales with sessions per profile and prompt rate.
  • Fix: In touch_and_wake_on_prompt_inner, when needs_resume is false and the in-memory row is neither snoozed nor idle-dormant, update last_accessed_at in memory only and skip the commit if the row's persisted value is within a coalescing window (for example 60 s); park clears still go through the commit path since wake is true there.
  • Verifier: The full store.update commit runs on every live prompt. But the commit also re-validates under flocks against disk (prompt_touch_rejection: generation, title, provider, view), and a comment says live prompts keep a single commit producer. A skip-commit fix loses that check. Prompt rate is human-scale, so one file write per prompt is minor next to an agent turn.
  • Measure: Time touch_and_wake_on_prompt_inner with a tracing span at 100 sessions per profile. Compare with time to first ACP token.

#489 Callback consumer spawns a 500 ms task per transition for sessions with no callback_url

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-session-store-service, category cpu
  • Where: src/server/callback.rs:296-340, src/server/callback.rs:72-99
  • Frequency: Every Idle/Waiting/Error status change of any session
  • Problem: handle_status_change bumps the global debounce map and spawns a sleeper task before checking whether the session has a callback_url, which almost no session does. After 500 ms each task takes the instances read lock and scans O(N). With many sessions flickering this is steady wasted task churn and lock traffic.
  • Fix: In handle_status_change, check callback_url presence first (brief instances read, or carry a has_callback flag on StatusChange) and return before bump_debounce and work.spawn when absent; keep the post-sleep re-read for the current status.
  • Verifier: handle_status_change (callback.rs:296) bumps debounce and spawns a 500ms task before any callback_url check; the check happens only after the sleep. Status changes are human-scale, so the cost is a tiny task plus one read per transition. Pre-check is safe and trivial.
  • Measure: Count server.callback_send spawns per hour on a daemon with 50 sessions and no callback_url, using tokio-console or a counter.

4.gap-acp-reconciler-supervisor-unread

#490 Redundant (session_id, seq) index on acp_events doubles primary-key index maintenance on every event insert

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-acp-reconciler-supervisor-unread, category disk-io
  • Where: src/events/mod.rs:100-110, src/events/mod.rs:178-181
  • Frequency: Every persisted ACP event, for every session. Streaming emits many chunk events per second per active session.
  • Problem: acp_events declares PRIMARY KEY (session_id, seq) on a rowid table, so SQLite already builds a unique autoindex on (session_id, seq). idx_{events}_session_seq is an identical second B-tree. Each insert and retention delete updates both, which adds write amplification and WAL volume. The extra index also takes disk space proportional to total event count.
  • Fix: Add a migration in src/migrations/ that runs DROP INDEX IF EXISTS idx_acp_events_session_seq, and remove the CREATE INDEX for idx_{events}session_seq from the schema setup in src/events/mod.rs. The PK autoindex and idx{events}_session_discriminant_seq already serve every query that uses (session_id, seq).
  • Verifier: src/events/mod.rs:101-110: composite PRIMARY KEY on a rowid table creates sqlite_autoindex on (session_id, seq), so idx_{events}_session_seq duplicates it. Real but small win: one extra B-tree insert/delete per event inside a per-event transaction. Fix must drop the index for every Schema prefix (ACP and plugin topics), not only acp.
  • Measure: sqlite3 acp_events.db "SELECT name,SUM(pgsize) FROM dbstat GROUP BY name"; time 100k record() calls with and without the index.

#491 Attachment GET reads the whole BLOB synchronously on the async runtime while holding the writer connection

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-acp-reconciler-supervisor-unread, category latency
  • Where: src/server/api/acp/prompt.rs:629-651, src/acp/event_store/attachments.rs:41-47, src/events/mod.rs:549-573
  • Frequency: Per GET /attachment request. Every image or file chip in a transcript costs one request on first view or cache miss. Cost scales with blob size, which can be several MB.
  • Problem: acp_attachment calls EventStore::load_attachment directly inside the axum handler. load_attachment takes self.conn(), which is the writer Mutex, and reads the full BLOB. That blocks a tokio worker thread on disk I/O. It also stalls the event writer, and so live persistence for every session, until the read finishes.
  • Fix: In acp_attachment, wrap the call in tokio::task::spawn_blocking. Change EventStore::load_attachment, and the other read-only loaders load_pending_attachments_for_ref and pending_attachment_bytes, to use self.reader() instead of self.conn().
  • Verifier: prompt.rs:638 calls load_attachment synchronously; attachments.rs:41-47 uses self.conn() (writer mutex) though a reader() pool exists at event_store/mod.rs:208. Claim holds, but blobs cap at 10 MB, responses are immutable-cached, so it fires once per chip; stall is milliseconds. Switching to reader() plus spawn_blocking is safe and trivial.
  • Measure: Add a tracing span around load_attachment in acp_attachment and log elapsed ms and writer-lock wait for a 10 MB image.

#492 Rate-limit park and live-work probes run on the writer connection instead of the read pool

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-acp-reconciler-supervisor-unread, category concurrency
  • Where: src/acp/event_store/rate_limit.rs:26-44, src/acp/event_store/rate_limit.rs:76-158, src/acp/event_store/rate_limit.rs:163-218, src/acp/event_store/rate_limit.rs:268-297, src/acp/event_store/account_limits.rs:143-175, src/acp/event_store/turns.rs:488-537
  • Frequency: rate_limit_park, rate_limit_redelivery_streak and account_state: every 15s per workerless, rate-limit-parked session. Parks last minutes to hours. holds_live_work and has_open_agent_turn: every 2s tick per respawn-pending session, plus once per resume target.
  • Problem: Each of these read-only probes takes self.conn(), the single writer mutex. rate_limit_park alone runs 4 to 5 queries under it, holds_live_work about 8. They run in spawn_blocking, but they still serialize with the event writer thread that persists streaming events for all sessions, so persistence latency spikes during reconciler passes.
  • Fix: Switch these functions to self.reader(): latest_rate_limit_event, rate_limit_park, rate_limited_turn_prompt, rate_limit_interrupted_agent_turn, rate_limit_redelivery_streak, account_state_checked, has_open_agent_turn, has_unhandled_finish and latest_prompt_state. reader() already exists for this purpose. Callers that need prior writes already call query_flushed first.
  • Verifier: Claim holds: these use self.conn() while reader() exists, and park/api list paths take the writer lock. But each query is indexed LIMIT 1 on a few rows, so hold time is microseconds at 15s/2s cadence. Caller flush ordering needs auditing (api/list.rs, session_service lack it).
  • Measure: Time the writer mutex wait in EventStore::conn() under a reconciler pass with 20 parked sessions; compare event persist latency before and after.

#493 respawn_drained_stale_workers forces a writer flush plus about 8 queries per stale session every 2s tick

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-acp-reconciler-supervisor-unread, category cpu
  • Where: src/server/acp_reconciler/resume.rs:655-701, src/server/acp_reconciler/mod.rs:144-159, src/acp/supervisor/sink.rs:210-217, src/acp/event_store/turns.rs:519-526
  • Frequency: Every reconciler tick (about 2s) for each session adopted as build-stale mid-turn. After a binary upgrade this can be every busy session, and it lasts as long as their turns (minutes).
  • Problem: Each tick calls query_flushed(holds_live_work) for every respawn_pending id. The call submits a Job::Flush and blocks until the writer drains. It then runs has_open_turn, has_open_subagent and has_unhandled_finish, about 8 SQLite queries, all on the writer conn. This repeats for every adopted stale session until its turn ends, so the cost grows with N sessions times turn length.
  • Fix: Re-probe only after the turn can have ended. When Drain::pump sees Event::Stopped (or BackgroundTaskFinished) for a session in Supervisor::respawn_pending, set a per-session dirty flag. In respawn_drained_stale_workers, call holds_live_work only for flagged ids, plus a slow fallback such as the 15s rate_limit cadence.
  • Verifier: Per-tick flush plus ~8 indexed queries per respawn-pending id is real, but the set is only stale mid-turn adopted sessions, and flush is cheap when the writer is drained. A dirty flag risks missing wake-ups and never respawning; a probe cadence change is safer.
  • Measure: Add tracing timing around query_flushed in respawn_drained_stale_workers with 20 stale sessions after a simulated binary upgrade.

#494 reap_rate_limit_resumes clones every attempted Instance, including live-worker ones, before filtering

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-acp-reconciler-supervisor-unread, category memory
  • Where: src/server/acp_reconciler/rate_limit.rs:227-243, src/server/acp_reconciler/mod.rs:332-337
  • Frequency: Every 15s (RATE_LIMIT_RESUME_INTERVAL), and every tick after a rate_limit_wake. Cost scales with the number of sessions that have a live worker, because the main loop inserts every Running session into attempted.
  • Problem: The candidates Vec clones the full Instance under the instances read lock for every resumable session in attempted. That includes queued_prompts with their full text and many String fields. Most candidates are then dropped because acp_supervisor.is_running is true. The comment at lines 171-174 shows the authors try to avoid copying queued prompt text under this lock.
  • Fix: Under the read lock, collect only the ids of resumable, attempted rows that are not in parked and not running (is_running is a cheap std mutex check). Clone the Instance only for those workerless ids, or clone just the fields the loop uses: id, source_profile, queued_prompts.is_empty(), and the failover inputs.
  • Verifier: candidates clones full Instance for every resumable attempted row before dropping parked and is_running ones, under the read lock. Runs every 15s. Fix is trivial: filter ids first, clone only workerless. Real but small cost; unchanged correctness.
  • Measure: Microbench Instance::clone with large queued_prompts across 50 sessions, or count allocations per reap pass via dhat.

#495 Failover account key does std::fs::canonicalize on the async runtime, twice per call

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-acp-reconciler-supervisor-unread, category latency
  • Where: src/server/acp_reconciler/rate_limit/failover.rs:86-109, src/server/acp_reconciler/rate_limit/failover.rs:198-208, src/server/acp_reconciler/rate_limit/failover.rs:264-271, src/server/acp_reconciler/rate_limit.rs:264-266
  • Frequency: When failover is enabled: every 15s per workerless, attempted session (note_auth_failure runs before the park check). observed_account_key also runs on record_limit and reported_deadline.
  • Problem: account_key calls path_key, which loops std::fs::canonicalize up the ancestor chain. It also resolves host_account_root. This runs inline on a tokio worker. observed_account_key calls account_key twice, once on the snapshot row and once on the live row. On slow or network home directories this blocks the runtime once per session per pass.
  • Fix: Compute account_key inside the existing spawn_blocking closures in note_auth_failure, record_limit and reported_deadline. Or memoize path_key results in a small Mutex<HashMap<PathBuf, String>> keyed by the config root, which only changes when profiles change.
  • Verifier: canonicalize runs inline on the tokio worker in account_key, only when failover is enabled (opt-in). Each call is a few cached stat syscalls on local home. Moving into spawn_blocking is easy; observed_account_key's live-row compare needs the lock held, so restructure.
  • Measure: Log elapsed time of account_key on a test host with failover enabled and a network-mounted home; check against 1ms.

#496 Rate-limit pass re-reads and re-parses profile config from disk every 15s

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-acp-reconciler-supervisor-unread, category disk-io
  • Where: src/server/acp_reconciler/rate_limit.rs:247-251, src/server/acp_reconciler/mod.rs:179-197
  • Frequency: Every 15s whenever at least one workerless attempted session exists, for example while any session is rate-limit parked. Cost scales with the number of distinct profiles.
  • Problem: resolve_per_profile calls profile_config::resolve_config_or_warn for each distinct profile on every pass. That reads and parses the global and profile TOML files just to get rate_limit_auto_resume and the failover settings, even though config rarely changes.
  • Fix: Read these two values from the server's cached config if AppState has one. Otherwise memoize them in a per-profile cache keyed by the config files' mtime, and invalidate it from the existing settings-save path.
  • Verifier: resolve_per_profile reads TOML per distinct profile every 15s, but it already runs in spawn_blocking and is gated on workerless sessions existing. Two small files per profile per 15s is negligible; a mtime cache adds invalidation risk for little gain.
  • Measure: strace -c the daemon (fs open count) over 60s with one parked session and 5 profiles, counting config TOML opens.

#497 Per-request sync worker-registry file I/O on the async runtime in prompt and request paths

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-acp-reconciler-supervisor-unread, category latency
  • Where: src/acp/supervisor/publish.rs:208-218, src/acp/supervisor/requests.rs:77-90, src/server/acp_reconciler/resume.rs:164-167, src/server/acp_reconciler/resume.rs:125-138
  • Frequency: ready_client: every send_prompt, cancel, set_mode, set_config_option and reset. agent_key_for_session: every user prompt to an Attached (adopted) worker. resume_one and requeue_interrupted_monitor: every resume.
  • Problem: ready_client calls worker_registry::stop_requested, a file read, inline. agent_key_for_session falls back to worker_registry::load, a file read plus JSON parse, for Attached workers on every prompt. resume_one loads the record inline. requeue_interrupted_monitor runs latest_active_monitor, up to 4 SQLite queries on the writer conn, directly on the runtime.
  • Fix: Cache agent_key on the WorkerHandle when attaching (WorkerKind::Attached) so agent_key_for_session never reads the file. Run resume_one's worker_registry::load and requeue_interrupted_monitor's latest_active_monitor inside spawn_blocking, and make latest_active_monitor use self.reader().
  • Verifier: Claims are true (stop_requested file read in ready_client, worker_registry::load for Attached, latest_active_monitor on writer conn). But each is a tiny local file or indexed query, once per user action or resume, not per tick. The sink already does sync SQLite inline. Sub-millisecond; the only cheap win is passing latest_active_monitor to reader().
  • Measure: Wrap ready_client and requeue_interrupted_monitor in tracing timers; check p99 under a 50-session resume storm on a populated DB.

#498 Queue enqueue loads full pending attachment blobs only to sum their sizes

  • Impact low, effort S, verdict confirmed, evidence proven-by-code, area gap-acp-reconciler-supervisor-unread, category memory
  • Where: src/server/api/queue.rs:181-191, src/events/mod.rs:619-650
  • Frequency: Per queued-prompt enqueue or re-enqueue that carries attachments. Cost scales with the bytes already buffered for that prompt (up to the per-session cap).
  • Problem: existing_for_prompt calls load_pending_attachments_for_ref, which copies every BLOB for the prompt into memory, and then just sums data.len(). This runs synchronously on the writer connection inside the HTTP handler.
  • Fix: Add events::pending_attachment_bytes_for_ref, which runs SELECT COALESCE(SUM(LENGTH(data)),0) ... WHERE session_id=?1 AND ref_id=?2 (LENGTH on a BLOB does not load overflow pages). Use it in queue.rs, through spawn_blocking and the reader connection.
  • Verifier: existing_for_prompt copies all BLOBs via load_pending_attachments_for_ref just to sum len; pending_attachment_bytes_for_session already uses SUM(LENGTH(data)) next line. Only nonzero on re-enqueue of the same prompt id, up to 64 MiB cap. Trivial sibling helper fixes it; spawn_blocking is optional.
  • Measure: Re-enqueue the same prompt_id with a 30 MiB attachment; time the handler and RSS before and after the SUM(LENGTH) helper.

#499 Orphaned approval and elicitation sweeps json_extract every request and resolution in session history

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-acp-reconciler-supervisor-unread, category cpu
  • Where: src/acp/supervisor/publish.rs:348-390, src/acp/event_store/turns.rs:248-268, src/acp/event_store/turns.rs:462-481
  • Frequency: Per spawn, respawn and control-channel reattach (cancel_orphaned_requests_on). Cost scales with lifetime ApprovalRequested plus ApprovalResolved count, which is high in non-yolo sessions running for hours.
  • Problem: unresolved_approval_nonces and unresolved_elicitation_nonces parse event_json with json_extract for every ApprovalResolved row to build the NOT IN set, and again for every ApprovalRequested row, with no seq bound. Requests are almost always resolved, so the sweep does O(total approvals) JSON parsing to find usually nothing. It holds the writer mutex while doing so.
  • Fix: Bound both queries to rows after the previous worker's assignment: add AND seq > (SELECT IFNULL(MAX(seq),0) FROM acp_events WHERE session_id=?1 AND discriminant='AcpSessionAssigned' AND seq < <current assignment>). Or rewrite as NOT EXISTS against a partial expression index on json_extract(event_json,'$.ApprovalResolved.nonce') WHERE discriminant='ApprovalResolved'.
  • Verifier: Queries confirmed: unbounded json_extract over all ApprovalResolved and ApprovalRequested rows, run only on spawn, respawn or reattach (launch.rs:668), not per tick. NOT IN subquery is non-correlated so built once. Even thousands of approvals cost milliseconds; seq bound adds correctness risk for little gain.
  • Measure: Seed 20k ApprovalRequested and ApprovalResolved rows in a test DB, time unresolved_approval_nonces with EXPLAIN QUERY PLAN and Instant.

#500 rate_limit_interrupted_agent_turn sums over every row of the interrupted turn

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-acp-reconciler-supervisor-unread, category cpu
  • Where: src/acp/event_store/rate_limit.rs:223-263
  • Frequency: Once per auto-resume continuation install when no user prompt was interrupted. Cost scales with the length of the interrupted turn, often thousands of chunk events.
  • Problem: The window query computes SUM(discriminant IN ...) across every row between the previous terminal and the rate_limited stop. The (session_id, discriminant, seq) index cannot serve a seq range without a discriminant equality, so this is a table range scan over the whole turn just to learn two booleans.
  • Fix: Replace the SUMs with two EXISTS probes bounded by the window: EXISTS(... discriminant IN ('UserPromptSent','UserDiffCommentsPrompt') AND seq > lo AND seq < stop) and the same for ('AgentMessageChunk','ToolCallStarted'). Each becomes an indexed seek on idx_session_discriminant_seq.
  • Verifier: Query is real: seq-range scan with a per-row table lookup to read discriminant, and EXISTS probes on idx_session_discriminant_seq would be cheaper. But it runs once per rate-limit auto-resume, a rare event, over one turn of at most thousands of rows. Milliseconds at worst, so the win is marginal.
  • Measure: Seed a 20k-chunk turn ending in Stopped rate_limited; time rate_limit_interrupted_agent_turn before and after the EXISTS rewrite.

4.gap-large-repo-git-scaling

#501 Changed-file stats pass formats a full patch and reads whole untracked/large files

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-large-repo-git-scaling, category memory
  • Where: src/git/diff.rs:89-123
  • Frequency: Per diff-files cache miss per session; scales with changed bytes and size of non-ignored untracked files.
  • Problem: The first pass calls diff.print(DiffFormat::Patch) only to count +/- lines. That loads every changed and untracked file fully, formats every line into libgit2 buffers, and DiffOptions sets no max_size. A multi-GB untracked log or build artifact is read on every cache miss.
  • Fix: Set opts.max_size(1 << 20) in compute_changed_files so large files are treated as binary, and replace print() with diff.foreach(..) using only the line callback. Or use Diff::stats() per delta via Patch::from_diff(idx).line_stats().
  • Verifier: print(Patch) only counts lines and loads the full content of every delta. The multi-GB claim is false: libgit2 already treats blobs over 512MB as binary by default, and ignored files are excluded. foreach or line_stats would still generate patches, so they do not help. Only a lower opts.max_size gives a win, and it changes counts for large files to 0/0.
  • Measure: Add a 100MB untracked text file to a worktree, then time GET /api/sessions/{id}/diff/files before and after setting opts.max_size(1<<20).

#502 Merge-base and default-base resolution run uncached on every diff request, outside the 1.5s cache

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-large-repo-git-scaling, category latency
  • Where: src/server/api/sessions/diff.rs:248, src/server/api/sessions/diff.rs:281-297, src/git/diff.rs:218-232, src/git/diff.rs:238-304, src/git/worktree/branch.rs:188-200
  • Frequency: Per /diff/files poll per repo, per /diff/file click, per cache miss in compute_changed_files, per TUI diff open. Scales with commit distance between HEAD and base, and with remote count.
  • Problem: Each request re-opens the repo several times: is_outside_repository, get_default_base_ref (merge_base per candidate, up to 2 per remote plus local), check_merge_base_status (merge_base), then compute_changed_files (merge_base again). In a monorepo where main advances thousands of commits per day, each libgit2 merge_base walks the commit graph without a commit-graph file.
  • Fix: Add a small cache in AppState keyed by (repo, head_oid, base_oid) for merge_base and by (repo, refs mtime) for detect_default_branch_info. Make check_merge_base_status reuse the computed merge-base, and resolve the base once per request before the changed_files_cached check.
  • Verifier: Duplication is real: check_merge_base_status and get_merge_base_tree each open the repo, resolve the base and run merge_base on every 10s poll. get_default_base_ref runs only when no override, recorded base or config default exists, and worktree sessions record a base. Each merge_base walk only covers commits since the fork. The cheap fix is to fold the status check into compute_changed_files, not to add an AppState cache.
  • Measure: Wrap check_merge_base_status and get_merge_base_tree in tracing spans and log their durations in a repo where main is about 5k commits ahead of the fork.

#503 changed_files_cached has no single-flight, so concurrent misses each run a full scan

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-large-repo-git-scaling, category concurrency
  • Where: src/server/state.rs:432-462
  • Frequency: Per cache expiry when several clients or tabs, or the diff-file endpoint plus the poll, hit the same repo at once. Scales with viewers and scan cost.
  • Problem: On miss the code releases the read lock and calls compute_changed_files with no in-flight marker. N concurrent requests for the same (repo, base) each run the full status/diff scan on the blocking pool, and the last writer wins. On a monorepo that multiplies multi-second scans.
  • Fix: Store an Arc/Mutex per (repo, base) key in changed_files_cache and have followers await the leader's result. Alternatively hold a per-key std Mutex across compute_changed_files.
  • Verifier: Claim holds: state.rs:432-462 has no in-flight marker. But TTL is 1.5s, callers are only diff.rs:295 (file list) and diff.rs:412 (single file), and keys are per (repo, base). Overlap needs two viewers or a poll and a click inside the same miss window, so a duplicate scan is rare on the blocking pool.
  • Measure: Add a debug counter for compute_changed_files calls per key per second. Open 3 dashboard tabs on one monorepo session and count duplicates per TTL window.

#504 Deletion dirty pre-check does a second full untracked scan before git worktree remove does its own

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-large-repo-git-scaling, category cpu
  • Where: src/session/deletion.rs:2054-2090, src/git/cleanup.rs:198-218, src/git/worktree/mod.rs:411-427, src/session/attach_project.rs:366
  • Frequency: Per non-force session delete per managed worktree (every repo of a workspace, sequentially), and per attach_project. Scales with file count and non-ignored untracked files.
  • Problem: The doc says dirty_worktree_message gates the sandbox preclean, but stage_collect_preserved_worktrees calls it for every non-force delete. It runs libgit2 status with recurse_untracked_dirs(true) and materializes every entry. Then git worktree remove runs its own status. It only needs a bool plus the first 30 entries.
  • Fix: Gate the call on instance.is_sandboxed(). For the rest, rely on git worktree remove. In list_dirty_files set recurse_untracked_dirs(false) and break after MAX_DIRTY_FILES_LISTED + 1 entries via StatusOptions plus an early-exit loop.
  • Verifier: The double status is real, but it runs once per user delete, which is rare. Gating on is_sandboxed changes behavior: the pre-check also fills preserved_worktree_paths, which gates branch deletion and the error format. Early exit would break the 'N total' count in dirty_worktree_message. The safe part is a capped early-exit count.
  • Measure: Time dirty_worktree_message plus git worktree remove on a 100k-file worktree with tracing spans in stage_collect_preserved_worktrees.

#505 ACP @-mention file list walks without .gitignore, so the 5000 cap fills with ignored junk

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-large-repo-git-scaling, category latency
  • Where: src/server/api/acp/history.rs:24, src/server/api/acp/history.rs:49-100
  • Frequency: Per ACP session view mount (useFilesIndex fetches once per session), blocking thread. Scales with directories visited before 5000 files are found.
  • Problem: list_files stops at 5000 files (good) but skips only a hardcoded SKIP_DIRS list, so vendor/, out/, bazel-*, venv, coverage and generated trees consume the cap. read_dir plus sort run per directory, and file-less directory chains are unbounded. The stack is LIFO, so the 'name order' doc is wrong, and real source files get truncated.
  • Fix: Replace the walk with the index: git2 repo.index() paths (in-memory, no stat) plus untracked from git ls-files -z --others --exclude-standard, capped. Falls back to the current walk for non-git dirs.
  • Verifier: Confirmed: there is no gitignore handling, only SKIP_DIRS. The LIFO pop walks directories in reverse name order, so the 'name order' doc is wrong and the capped subset is biased. Cost stays bounded by the 5000 cap, one request per useFilesIndex mount (FilesPane, composer). This is mainly a relevance bug, not a big perf one. git ls-files is a sound fix.
  • Measure: Time GET /api/sessions/{id}/acp/files on a repo with a large vendor/ or bazel-out tree. Compare against git ls-files -co --exclude-standard | head -5000.

#506 Branch listing iterates every ref, sorts everything, then truncates to 400/200

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-large-repo-git-scaling, category latency
  • Where: src/server/api/git.rs:253-275, src/git/diff.rs:636-720
  • Frequency: Per wizard base-branch picker load (/api/git/branches). Scales with local plus remote branch count (tens of thousands in monorepos).
  • Problem: list_branches_with_remotes builds a BTreeSet of locals, creates an entry for every remote ref, sorts all, then the handler take(400)s alphabetically. Cost is O(refs log refs) per request, and the user sees only the first 400 alphabetically, hiding most branches.
  • Fix: Add a q prefix/substring query param to BranchesQuery and filter inside list_branches_with_remotes while iterating. Stop at the cap after main/master and current. Order by committer time via for-each-ref --sort=-committerdate --count=400 on refs/heads and refs/remotes.
  • Verifier: Code matches: diff.rs:675-720 builds and sorts every ref, then git.rs truncates to 400/200. It runs only on wizard picker load, and libgit2 ref iteration plus sorting tens of thousands of strings costs tens of ms. The real problem is UX: alphabetical truncation hides branches. A server-side q filter is a feature change.
  • Measure: Time GET /api/git/branches?include_remote=true on a repo with 20k remote refs, e.g. a linux or chromium mirror.

#507 Worktree create: sequential submodule update and recursing fetch

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-large-repo-git-scaling, category latency
  • Where: src/git/worktree/create.rs:49-52, src/git/worktree/create.rs:374-380
  • Frequency: Per worktree creation (per new session, per repo of a workspace). Scales with submodule count and size.
  • Problem: git submodule update --init --recursive clones submodules one by one with no --jobs, depth or reference. git fetch <remote> <branch> lacks --no-recurse-submodules, so with submodules git also fetches changed submodules synchronously before worktree add, inside the 10s fetch bound.
  • Fix: Add --jobs 8 to the submodule args in initialize_submodules, and --no-recurse-submodules --no-tags to fetch_branch. Consider --reference-if-able pointing at the main repo's modules dir.
  • Verifier: Confirmed: create.rs:374 runs submodule update --init --recursive with no --jobs and init_submodules defaults true (config/mod.rs:3199). A linked worktree keeps its submodule gitdirs in .git/worktrees//modules, so every session reclones from the network. --reference to the main repo modules is the big win and --jobs is secondary. Fetch recursion is on-demand only and stays inside the 10s bound. Only repos with submodules benefit.
  • Measure: Create a worktree session on a repo with 10+ submodules, compare the 'worktree create:' tracing timings with and without --jobs 8 and --reference.

#508 Startup worktree reconcile loads the whole store per session and uses a fresh list cache each time

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-large-repo-git-scaling, category startup
  • Where: src/server/api/sessions/delete.rs:468-545, src/session/worktree_reconcile.rs:84-97
  • Frequency: Once at daemon startup (and publish tests), per managed session, sequentially under the instance lock. Scales with N sessions squared on load, plus M worktrees per broken session.
  • Problem: For each managed session it takes the identity lock, spawns a blocking task, NativeSessionStore::open + store.load() of the full profile, and passes &mut Default::default() as ReconcileCache. N sessions cost N full loads. Each session with a missing path then pays list_worktrees = M+1 opens. reconcile_profile (TUI) already shares one cache.
  • Fix: In reconcile_worktree_paths, filter candidates to rows whose project_path is missing (stat) before spawn_blocking, and hold one ReconcileCache across the loop (move it into the closure behind a Mutex).
  • Verifier: Confirmed: startup.rs:1178 awaits this before publish, and each managed session does NativeSessionStore::open, a flock and a full load_complete_with_groups parse, so N sessions cost N parses. Sharing ReconcileCache barely helps because list_worktrees runs only when the path is missing (worktree_reconcile.rs:147). The real fix is an in-memory stat prefilter on project_path. That is safe because the locked path rechecks.
  • Measure: Time reconcile_worktree_paths at daemon startup with 200 managed sessions, using a tracing span around the loop.

#509 delete_branch runs git branch -d whose merge check is wasted when force-delete follows

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-large-repo-git-scaling, category subprocess
  • Where: src/git/worktree/branch.rs:233-298
  • Frequency: Per session branch deletion (delete, rollback, rename cleanup): up to 4-5 git forks. Scales with history distance between the branch and HEAD/upstream.
  • Problem: Order is show-ref, branch -d (computes reachability against HEAD/upstream, expensive in large histories without commit-graph), worktree list, then branch -D for any unmerged branch with no worktree. Session branches are usually unmerged, so -d is a wasted fork plus walk before the guaranteed -D.
  • Fix: Call git branch -D after the worktree_path_for_branch check, dropping the -d attempt. Keep the existing 'held by worktree' retry. Or delete via git2 Branch::delete.
  • Verifier: Order is as claimed, but delete is rare and user-initiated; -d merge check is a cheap ancestry test, about one fork (5-20ms). Reordering to -D after the worktree check is safe, since -D on a held branch still fails. Saves one fork only.
  • Measure: Time git branch -d on an unmerged branch in a large repo without commit-graph: time git branch -d x.

#510 Per-file diff reads and copies the entire file several times with no size cap

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-large-repo-git-scaling, category memory
  • Where: src/git/diff.rs:512-556, src/git/diff.rs:581-586, src/git/diff.rs:600-607
  • Frequency: Per diff file click (web and TUI). Scales with file size, e.g. a 200 MB lockfile or fixture.
  • Problem: read_file_state does fs::read of the working copy, blob.content().to_vec() of the base blob, then String conversion, and compute_file_contents clones both into FileContents and the patch buffer. Only the first 8000 bytes are checked for binary. There is no size ceiling before diffing and serializing.
  • Fix: In read_file_state, check blob.size() and fs::metadata().len() against a cap (e.g. 2 MB), returning is_binary-style 'too large' status. Use blob.content() borrowed instead of to_vec(). Skip cloning by moving contents into the response.
  • Verifier: Serialization is already capped: sessions/diff.rs:487 checks MAX_CONTENTS_BYTES and MAX_CONTENTS_LINES and sends truncated:true, and the contents are moved, not cloned. The waste is that read_file_state reads both full files, to_vec()s the blob and runs xdiff on them before that cap is checked. Comparing blob.size() and metadata len against the cap first would skip the read and diff.
  • Measure: Click a 100 MB changed file in the web diff and time the per-file endpoint plus peak RSS, before and after a pre-read size check.

#511 Clone paths have a hard 5 minute kill, no partial clone, and an unbounded post-clone fetch

  • Impact low, effort M, verdict partly, evidence proven-by-code, area gap-large-repo-git-scaling, category network
  • Where: src/git/remote.rs:34-50, src/git/remote.rs:91, src/git/remote.rs:226-240, src/server/api/git.rs:164-175
  • Frequency: Per web 'Clone URL' action. Scales with repository size and history.
  • Problem: A monorepo full clone commonly exceeds 300s and is killed and deleted. Only --depth 1 is offered, no --filter=blob:none or sparse option. In the bare path, git fetch origin after clone --bare runs through run_in_bare with .output() and no timeout, so it can hang the blocking thread indefinitely.
  • Fix: Add a filter option to CloneRepoBody mapped to --filter=blob:none in clone_repo and clone_bare_repo. Scale the timeout with progress (kill only on no output for N seconds). Wrap run_in_bare fetch in run_git_with_timeout.
  • Verifier: Confirmed: there is a fixed 300s kill in both clone paths, only --depth 1 is offered, and the bare path ignores shallow. The fetch origin after clone --bare (remote.rs:91) has no timeout, but stdin is null and the objects are already local, so it moves almost no data. A hang there needs a stalled network. This is a rare, user-initiated action, so it is a robustness gap more than a perf win.
  • Measure: Clone a large monorepo such as chromium or linux through the web Clone URL with the default and with --filter=blob:none, and record wall time against the 300s limit.

#512 Rename/copy detection enabled on every changed-files scan

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-large-repo-git-scaling, category cpu
  • Where: src/git/diff.rs:98-104
  • Frequency: Per diff-files cache miss when the branch has many added and deleted files (vendoring, code moves). Scales with adds times deletes, bounded by libgit2 rename_limit.
  • Problem: find_similar with renames(true) and copies(true) hashes every added and deleted blob to build similarity signatures, and copies add modified files as sources. In a large refactor branch this is heavy compute at each poll miss for a marginal UI label.
  • Fix: Drop copies(true) in compute_changed_files and set find_opts.rename_limit(200). Cache the result keyed by (head_oid, index mtime) so unchanged trees skip it.
  • Verifier: Server already caches compute_changed_files (1.5s TTL, state.rs:428), TUI calls it on open/refresh only. libgit2 rename_limit already defaults to 1000, bounding cost. Dropping copies would remove the Copied status UI; the proposed (head_oid, mtime) cache is mostly redundant.
  • Measure: Time compute_changed_files with and without copies(true) on a branch with 2000 added and deleted files, using a criterion bench or Instant log.

4.gap-fleet-footprint-and-log-volume

#513 Every ACP runner process builds a full multi-thread tokio runtime (one worker per core)

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-fleet-footprint-and-log-volume, category memory
  • Where: src/main.rs:124, src/main.rs:468, src/process/runner/mod.rs:149
  • Frequency: Once per runner process; one runner per structured session, alive for the whole session (hours). Scales with session count x CPU cores.
  • Problem: aoe acp-runner goes through tokio::runtime::Runtime::new() (main.rs:124), which starts num_cpus worker threads. The runner is a thin relay with one agent child, a watchdog and a control socket. On 10 cores with 300 runners that is about 3000 idle worker threads, plus 3 file-watch threads each.
  • Fix: In main.rs, build the runtime for Commands::AcpRunner with Builder::new_current_thread() (or new_multi_thread().worker_threads(2)) before run_cli. Keep Runtime::new() for the daemon and TUI.
  • Verifier: Confirmed: AcpRunner reaches run_cli via Runtime::new() (main.rs:124, dispatched at main.rs:468), so it gets num_cpus workers. Idle parked tokio workers cost mostly virtual stack and a few tens of KB RSS each, so the 'high' rating overstates it. Use worker_threads(2), not current_thread: shared code (supervisor/sink.rs:360) branches on runtime flavor and some paths assume multi-thread.
  • Measure: With 20 runners live, compare ps -M <runner pid> | wc -l and RSS from ps -o rss before and after building with worker_threads(2).

#514 Background sub-agent tailer polls every 500 ms for up to 5 minutes, and runs docker exec each poll in sandboxed sessions

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-fleet-footprint-and-log-volume, category subprocess
  • Where: src/acp/background_agent.rs:15, src/acp/background_agent.rs:281, src/acp/background_agent.rs:353, src/acp/background_agent.rs:433, src/acp/background_agent.rs:82, src/acp/acp_client/connection/notifications.rs:122
  • Frequency: 2 polls/s per running background sub-agent (up to ABORT_AFTER=300 s of no growth). Host: open+seek+read. Container: one <runtime> exec tail fork per poll. Scales with concurrent background agents x sandboxed sessions.
  • Problem: The comment says 'no inotify'. For TranscriptSource::Container, read_from forks docker exec ... tail -c +N every 500 ms even when the transcript is idle (about 600 execs per idle agent before abort). Host mode reopens the file twice a second. The sibling task_transcript already uses file_watch with a 30 s safety reread.
  • Fix: Host: subscribe via FileWatchService like task_transcript::follow, with SAFETY_REREAD as a fallback. Container: back off the sleep (500 ms up to 5 s while idle), or hold one exec tail -F -c +N stream per agent instead of forking per poll.
  • Verifier: Host mode costs one open+seek+read every 500 ms per active sub-agent, which is negligible. Container mode does fork <runtime> exec tail every 500 ms even when idle, up to 600 execs before ABORT_AFTER. Background agents are few and short-lived. Idle backoff in the container path alone is enough; a FileWatch refactor is not worth it.
  • Measure: Run one sandboxed session with an idle background agent and count docker exec calls per minute with docker events --filter event=exec_create.

#515 Session-id pollers: one OS thread per tmux session, capped at 50, never retire after the sid is known

  • Impact low, effort M, verdict partly, evidence proven-by-code, area gap-fleet-footprint-and-log-volume, category concurrency
  • Where: src/session/poller.rs:11, src/session/poller.rs:610, src/session/poller.rs:645, src/session/poller.rs:481, src/tmux/utils.rs:253, src/session/instance/polling.rs:395, src/session/capture/codex.rs:268
  • Frequency: One thread per eligible session while its pane lives. After warm-up, one tick every 60 s (2 s start, x1.5 every 3 stable polls). Each tick forks 2 tmux processes (list-panes, display-message), plus per-backend work such as a codex sessions-tree scan of up to 8192 entries or an OMP docker exec.
  • Problem: At N>50 the default 50-thread budget leaves sessions 51+ without sid capture. Each deferred session retries on a 5-60 s backoff with a warn every ~10 min. Threads that do run keep probing after the sid is stable.
  • Fix: Replace SessionPoller threads with one scheduler task (or a small pool) over a deadline heap so the cap goes away. Back off to 5 min once last_known is stable and no new launch marker exists. Make probe_pane share the batch_pane_metadata snapshot instead of forking per tick.
  • Verifier: One thread per session with a cap of 50 is confirmed, and session_id_poller_max_threads is configurable. At the 60 s max interval that is about 2 tmux forks per session per minute, which is cheap. Probing must continue after the sid is known because sids change (/clear, resume) and pane liveness is checked each tick. A scheduler rewrite only matters above 50 tmux sessions.
  • Measure: With 50 tmux sessions running, count tmux forks over 5 minutes using sudo execsnoop -n tmux (Linux) or dtrace proc:::exec on macOS.

#516 status_rules shadow warning fires on every config resolve, and resolves run on timers and per-session paths

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-fleet-footprint-and-log-volume, category disk-io
  • Where: src/tmux/status_rules.rs:112, src/session/config/profile_config.rs:182, src/server/acp_reconciler/idle.rs:170, src/server/idle_reap.rs:48, src/server/acp_reconciler/rate_limit.rs:247
  • Frequency: Steady state in the daemon: acp idle reap 1/min per distinct profile, plain-session idle reap 1/min per profile, rate-limit resume every 15 s while workerless sessions exist. Plus per-session accessors (declared_agent_config_dir_for, sandbox_capture_store_path, legacy_default_selector_agent). One warn (about 250 B) per shadowing agent per resolve.
  • Problem: install_from_config rebuilds the registry and re-logs the warn on every resolve_config. A user with [[agents.claude.status_rules]] gets about 2-6 identical lines per minute per profile from timers alone (roughly 0.5-1.5 KB/min, 1-2 MB/day), more with per-session resolves. Each resolve also re-reads and re-parses config.toml.
  • Fix: In install_from_config, log only when the compiled rule set for (profile, agent) differs from the registry entry being replaced, or keep a OnceLock<HashSet<(profile, agent)>> of already-warned pairs. Optionally cache resolve_config by config mtime.
  • Verifier: install_from_config warns on every resolve_config and resolve_config reloads config each call. Callers dedupe per profile and only fire with candidates present. Only users shadowing a built-in agent pay. Real but a few lines/min; the log spam is the only cost.
  • Measure: Set a [[agents.claude.status_rules]] with idle ACP sessions; run daemon 10 min; grep -c 'shadow the built-in' in debug.log.

#517 TUI re-arms the VT channel every 3 s while another process owns the pipe, logging at info each time

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-fleet-footprint-and-log-volume, category subprocess
  • Where: src/tui/home/live_send.rs:760, src/tui/home/live_send.rs:772, src/tui/home/live_send.rs:1517, src/tmux/vt.rs:2597, src/tmux/vt.rs:2566
  • Frequency: Every 3 s (VT_REARM_INTERVAL) for the previewed session while a web live viewer in the daemon holds the pipe. Per attempt: a PendingArm thread, about 4-5 tmux forks (first_pane_id, pane_size_cursor, owner claim), and one info line of about 170 B.
  • Problem: VtUnavailable::PipeOwned is not remembered, so channel_arm_due keeps retrying at the same interval forever. That is about 1.5 forks/s plus about 3.4 KB/min (about 5 MB/day) of identical info lines for one previewed session.
  • Fix: On PipeOwned, back off the next arm exponentially (3 s to 30 s) and reset on selection change. Demote the 'pipe owned by another process' line in arm to debug. Skip the retry until the owner heartbeat (VT_OWNER_TTL=4 s) lapses.
  • Verifier: PipeOwned is discarded by acquire(...).ok() in live_send.rs, so channel_arm_due retries every 3 s with an info log. Cost is real only when TUI previews a session a web viewer holds; the interval throttle is deliberate for healing.
  • Measure: Open the same session in web live view and TUI preview for 1 min; count 'pipe owned by another process' lines and tmux forks via strace/ps.

#518 Capture-deferred warn has no throttle on its 30 s retry

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-fleet-footprint-and-log-volume, category disk-io
  • Where: src/session/instance/polling.rs:436, src/session/instance/polling.rs:440, src/session/instance/polling.rs:445, src/session/poller.rs:121
  • Frequency: Once per MANAGED_CAPTURE_RETRY_BACKOFF (30 s) per session whose managed store lease is held by another process (for example TUI plus daemon both polling). About 250-300 B per line.
  • Problem: The budget-exhausted path logs only on escalation or every ~10 min, but 'Session capture deferred because another process owns this store' and 'store ownership is ambiguous' warn on every retry. 100 contended sessions give about 200 lines/min (about 55 KB/min, about 3 MB/h), enough to rotate the 50 MiB x 6 debug.log in about a day.
  • Fix: Route these through PollerRepairBackoff::defer-style gating (log on first, on change, then every N retries), or record a per-row last_deferral_logged and warn once per state change.
  • Verifier: Contended and ambiguous warns at polling.rs:436/453 log on each 30 s retry with no gating, unlike PollerRepairBackoff. Only multi-process contention (TUI plus daemon) triggers it; per-line cost is trivial. Log noise, not CPU.
  • Measure: Run TUI and daemon on N managed-store sessions for 5 min; grep -c 'capture deferred' in debug.log.

#519 Single global acp-event-writer thread serializes all sessions, and per-session reads flush the whole queue

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-fleet-footprint-and-log-volume, category latency
  • Where: src/acp/supervisor/sink.rs:109, src/acp/supervisor/sink.rs:139, src/acp/supervisor/sink.rs:218, src/acp/supervisor/sink.rs:236
  • Frequency: Per worker event and per flushed_store read (the unresolved_* queries). One thread for N sessions, queue capacity 4096.
  • Problem: All sessions persist through one thread. flushed_store() submits a Flush barrier behind every queued publication of every session, so a per-session read waits for the whole fleet backlog. At 100-300 busy sessions streaming deltas, probes can stall behind unrelated sessions' SQLite writes.
  • Fix: Shard ChannelSink writers by hash(session_id) into K threads (K=4), each with its own queue and flush barrier. flush() per session then waits only on its shard. Batch SQLite inserts per drained burst if not already done.
  • Verifier: One writer thread and a global Flush barrier are real. But flushed reads run only on attach, reattach, teardown and reconciler probes for dead or idle runners, all in spawn_blocking. Sharding gains nothing: every write goes through EventStore's single Mutex and SQLite allows one writer. Per-event transactions (mod.rs:236) are the real lever: batch each drained burst in one transaction.
  • Measure: Add a histogram on queue depth and on Job::Flush wait time in sink.rs flush(). Run 100 streaming sessions and check p99 flush latency and per-record commit time.

#520 Runner appends every agent stderr line to the per-session log with open/write/close, no rotation, and logs are never removed

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-fleet-footprint-and-log-volume, category disk-io
  • Where: src/process/runner/mod.rs:223, src/process/runner/mod.rs:662, src/process/worker_registry.rs:497, src/acp/session_tee.rs:21
  • Frequency: Per agent stderr line, unconditionally (the debug! is filtered, append_log_line is not): 3 syscalls per line. A non-empty .log is kept after the session ends. Scales with agent stderr volume x sessions.
  • Problem: append_log_line re-opens the file per line and never rotates. The tee's 10 MiB x 2 cap only applies when the daemon happens to write through SizeRotatingWriter. retire_record_files deletes only empty logs, so a chatty adapter in debug mode grows an unbounded file per session that survives deletion.
  • Fix: Keep one BufWriter<File> in the stderr task and stop appending past a cap (about 10 MiB), rotating with SizeRotatingWriter. In retire_record_files or session deletion, remove <id>.log* once the session row is gone.
  • Verifier: append_log_line opens, writes, closes per stderr line with no cap; retire_record_files removes only zero-length logs. Real unbounded growth, but only for chatty adapters; syscall cost per line is small. Disk retention is the real issue.
  • Measure: Run an ACP session with a verbose adapter; compare du of workers/.log after an hour and after deleting the session.

4.gap-plugin-runtime-and-pages

#521 Plugin pane markdown is re-parsed by ReactMarkdown on every poll re-render

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-plugin-runtime-and-pages, category render
  • Where: web/src/components/plugin/BlockMarkdown.tsx:25, web/src/components/plugin/PluginPane.tsx:40, web/src/components/plugin/PluginSlots.tsx:112
  • Frequency: per ui-state poll (3s), per visible pane or home-pane markdown block; scales with block count and text size (pane payload up to 64 KB)
  • Problem: BlockMarkdown is not memoized and DetailBlock uses key={i}. Because entries get new identity each poll, every markdown block re-runs the unified/remark-gfm parse and rebuilds its React tree even when the text is unchanged.
  • Fix: Wrap BlockMarkdown in React.memo comparing text and tone, or useMemo the rendered ReactMarkdown element on [text]. Pair with the entries identity fix in usePluginUiState so unchanged blocks skip rendering entirely.
  • Verifier: BlockMarkdown (lines 24-36) is unmemoized and DetailBlock uses key={i}, so ReactMarkdown re-parses on every poll re-render. This only happens while a plugin pane or home-pane with markdown blocks is visible. Most of the win comes from the finding 0 identity guard; React.memo on text+tone is a small add-on.
  • Measure: Open a plugin pane with a 64KB markdown block, Profiler-record 30s idle: measure BlockMarkdown render ms per commit.

#522 Plugin worker spawn probes Node (config load + node --version subprocess) on every spawn and respawn

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-plugin-runtime-and-pages, category startup
  • Where: src/plugin/host.rs:675, src/plugin/mod.rs:54, src/plugin/mod.rs:86, src/acp/node.rs:106
  • Frequency: once per Node-based plugin worker at daemon start (concurrently), and every respawn (up to 3 per 60s) and restart; scales with number of non-system or build-step plugins
  • Problem: spawn_once calls node_env() in spawn_blocking for each worker. That runs Config::load_or_warn from disk plus resolve(), whose verify_path spawns node --version (up to 5s timeout). N node plugins pay N config parses and N node subprocess spawns on the critical path to first worker start.
  • Fix: Memoize node_env() in a OnceLock/RwLock keyed by (AOE_ACP_NODE, config.acp.node_path), invalidated in reload_registry() and ensure_node(). Resolve once in PluginHost::start before launching workers.
  • Verifier: Confirmed: spawn_once (host.rs:675) runs node_env -> Config::load_or_warn + resolve -> verify_path spawning node --version, with no cache in acp/node.rs. It runs off the async runtime in spawn_blocking, only once per long-lived worker spawn, at about 30-80ms. A cache risks serving a stale path after a Node upgrade.
  • Measure: Add a tracing span around node_env in spawn_once; compare its duration per worker at daemon start with N node plugins.

#523 Daemon startup always reads the full sessions store and runs lifecycle/status forwarders even when no worker consumes them

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-plugin-runtime-and-pages, category startup
  • Where: src/server/startup.rs:1388, src/server/startup.rs:1392, src/server/startup.rs:1403, src/server/lifecycle_feed.rs:162, src/plugin/host.rs:276, src/plugin/host.rs:286
  • Frequency: baseline: once at every daemon start, serial before 'daemon ready'; forwarders: per session status transition and per lifecycle change for the daemon lifetime; scales with session count
  • Problem: plugin_host is Some whenever not read-only, so startup awaits establish_baseline (load_all_instances, with up to BASELINE_ATTEMPTS retries) and installs the commit observer even with zero runtime plugins. push_session_event builds and stringifies the JSON-RPC line before checking whether any worker opted in.
  • Fix: In startup.rs, compute registry().active() runtime plugins with session.read and api_version>=14 first; skip establish_baseline, install_commit_observer and spawn_forwarder when none, and start them lazily from reconcile. In push_session_event, check for an opted-in worker under the table lock before serializing.
  • Verifier: Confirmed: establish_baseline runs a second full uncached load_all_instances before 'daemon ready', duplicating the load at startup.rs:734. A single read is ms-scale, and retries happen only on commit races or enumeration failure. Serializing per event in push_session_event costs microseconds. Lazy baselining risks the observer-before-baseline ordering invariant.
  • Measure: Time the establish_baseline await in startup.rs with tracing::info_span on a store of 200 sessions.

#524 Plugin page HTML is served no-store with no validator, re-downloaded on every open

  • Impact low, effort S, verdict partly, evidence plausible-needs-measurement, area gap-plugin-runtime-and-pages, category network
  • Where: src/server/api/plugins.rs:202, src/server/api/plugins.rs:207, src/server/api/plugins.rs:218, src/server/api/plugins.rs:260
  • Frequency: per page open and per frame reload (iframe remount on Reopen); scales with page bundle size (a self-contained HTML with inline JS/CSS) and link RTT over tunnel/remote
  • Problem: serve_plugin_page sets Cache-Control private, no-store and emits no ETag or Last-Modified, so every open runs canonicalize twice, reads the whole file and ships it. ADR 0005 does not require no-store; auth is re-checked per request regardless.
  • Fix: In plugin_page_response emit an ETag derived from plugin.manifest_hash plus file mtime/len, use private, no-cache, and return 304 via the existing crate::server::runtime::if_none_match helper. CSP and X-Frame-Options stay unchanged.
  • Verifier: Claim holds (private, no-store, plugins.rs:207, no validator), but pages are small local files read once per iframe open, not polled. An ETag with if_none_match is feasible. Win is small except over a slow tunnel with large bundles.
  • Measure: curl -s -o /dev/null -w '%{size_download} %{time_total}' with a session cookie against /api/plugins//pages/ through the tunnel.

#525 acp.capabilities.probe launches agent adapter handshakes serially

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-plugin-runtime-and-pages, category latency
  • Where: src/plugin/session_api.rs:248, src/plugin/session_api.rs:236, src/acp/capability_probe.rs:17
  • Frequency: per acp.capabilities.probe RPC without agent_id; scales with number of undiscovered registry agents (each spawns an adapter process, typically seconds)
  • Problem: The loop for agent in &targets awaits probe_agent one at a time. Each probe spawns an ACP adapter (often Node) with SPAWN_TIMEOUT, so N undiscovered agents cost N times the handshake latency, and the worker's RPC stream is stalled meanwhile.
  • Fix: Run the probes concurrently with futures_util::future::join_all or a bounded buffer_unordered(4) inside capabilities_probe; keep the per-agent error logging.
  • Verifier: Loop at session_api.rs:248 is serial and serve_connection (host.rs:963) awaits each RPC inline, so the worker's stream stalls. But the RPC is rare, plugin-initiated, filtered to uncatalogued agents, and absent adapters are skipped via command_present. Worst case is installed-but-failing adapters at 15s each. option_catalog::record holds CATALOG_LOCK, so join_all is safe.
  • Measure: Install 3 ACP adapters, clear the option catalog, call acp.capabilities.probe with no agent_id, and log wall time around the loop.

#526 config.get reloads and parses config.toml (up to 8 times) on every call

  • Impact low, effort S, verdict partly, evidence proven-by-code, area gap-plugin-runtime-and-pages, category disk-io
  • Where: src/plugin/host_api.rs:592, src/plugin/host_api.rs:594, src/plugin/agent_integration.rs:635
  • Frequency: per config.get RPC; workers call it at start per key and after each plugin.settings.changed, and polling plugins may call it per tick; scales with config size
  • Problem: config_get does Config::load() from disk in the retry loop each call, then discards the result. Another path (agent_integration::effective_config) already caches Config by file stamps, so the pattern exists but is not shared here.
  • Fix: Cache an Arc in HostApiState keyed by (settings_revision, config.toml stamp) and refresh only when either moves; reuse config_stamps from agent_integration.rs.
  • Verifier: Config::load() runs per config.get (host_api.rs:594), but the 8-iteration loop only repeats if a settings write lands mid-load, so normally one load. Calls are infrequent (start and on settings change). Caching is feasible but small win.
  • Measure: Count config.get calls with a tracing counter at host_api.rs:576 over a 10-minute run with 5 plugins; time Config::load().

#527 Status poll re-stats three config files and clones cache keys per plugin-claimed session per tick

  • Impact low, effort M, verdict partly, evidence proven-by-code, area gap-plugin-runtime-and-pages, category disk-io
  • Where: src/plugin/agent_integration.rs:635, src/plugin/agent_integration.rs:687, src/plugin/agent_integration.rs:758, src/plugin/agent_integration.rs:857, src/session/instance/status_update.rs:274
  • Frequency: per status poll tick per session whose tool is claimed by an active session.integration plugin; scales with such sessions
  • Problem: owned_status calls custom_ownership then effective_config, which does 6 stat syscalls (symlink_metadata plus metadata for global, state and profile files), get_profile_dir_path, and clones PathBuf, String and Vec to build the cache key, all per session though stamps are identical across sessions of a profile. read_report then reopens the report dir, reads and JSON-parses the file, and kills pid 0.
  • Fix: Compute config_stamps once per poll tick (or cache them for ~1s) keyed by profile and pass the result into effective_config; skip read_report's parse when the report's mtime and inode are unchanged from the last tick.
  • Verifier: effective_config does 3 stamps plus key clones per plugin-claimed session per tick (agent_integration.rs:635-649), and the parsed Config is already cached. Cost is a few stat syscalls per session, only for plugin-claimed tools. Real but small; bound by status poll interval.
  • Measure: Run strace -c or dtruss on the daemon with 50 plugin-claimed sessions; count stat/open calls per status poll tick.

#528 Install/update runs two full fetches (clone or asset download) for preview then apply

  • Impact low, effort L, verdict partly, evidence proven-by-code, area gap-plugin-runtime-and-pages, category network
  • Where: src/plugin/install.rs:386, src/plugin/install.rs:627, src/plugin/install.rs:660, src/plugin/install.rs:1203, src/plugin/fetch.rs:461
  • Frequency: per web or TUI install and per consented update; scales with repo size and release-binary asset size
  • Problem: preview_install runs prepare_install (git clone and, for release-binary plugins, the asset download), cleans up, then apply_install runs prepare_install again and compares fingerprints. The re-fetch is a deliberate TOCTOU check, but the bytes are fetched twice.
  • Fix: Keep the previewed staging tree under the operation lease keyed by fingerprint for a short TTL and re-verify its tree_hash and asset_sha256 at apply, or at least cache the downloaded asset by its sha256 so only the cheap ls-remote or commit check repeats.
  • Verifier: Two fetches are real (preview_install and apply_install each call prepare_install). But it is a user-interactive, rare action, and the re-fetch is the deliberate TOCTOU guard. Keeping staging across requests adds lease, TTL and cleanup complexity for a rare path. Asset-by-sha cache is the only cheap option.
  • Measure: Time install of a release-binary plugin in web UI; compare preview vs apply durations in plugin.host tracing logs.

#529 Every plugin git command spawns ps -A on macOS (at capture and every second)

  • Impact low, effort M, verdict partly, evidence plausible-needs-measurement, area gap-plugin-runtime-and-pages, category subprocess
  • Where: src/plugin/execution.rs:93, src/plugin/execution.rs:120, src/process/mod.rs:454, src/process/macos.rs:818
  • Frequency: at least once per Budget::run command (git ls-remote, clone, build steps) and once per second while it runs; update checks run one ls-remote per installed plugin
  • Problem: Budget::run_captured calls OwnedProcessTree::capture, which refresh()es via owned_process_tree_samples, which on macOS runs ps -A -o pid=,ppid=,stat= and parses every process. The loop repeats it each second. Short commands like ls-remote pay a full system process listing just for descendant custody.
  • Fix: In run_captured, skip the capture-time census and take the first census only if the leader is still alive after ~250ms (or use proc_listchildpids on macOS for descendants only of the leader). Keep the final settle check.
  • Verifier: Claim holds: capture calls refresh, which runs ps -A on macOS, then once per second. But ps costs ~10-30ms against network-bound git commands, and update checks are infrequent. The capture-time census is custody attestation, so skipping it weakens a safety invariant.
  • Measure: time ps -A -o pid=,ppid=,stat= on macOS; compare to git ls-remote wall time for a plugin repo.

5. Kept by verifier but judged no real impact

  • #530 (session-instance) Stop and sid persistence reread and rewrite the whole sessions.json several times per operation: Extra loads are real in stop(), but stop and kill are user-driven and rare. The post-update reload in sid_persist runs only on promote_one_shot or on Skipped, OwnershipConflict and PinnedForeign, not on every commit. Parsing a few-KB sessions.json takes milliseconds. The O(N^2) claim for stop-all is true but negligible.
  • #531 (session-instance) Retroactive capture loads the whole store twice per attempt: The second exclusion-set load happens only when an observation is found, at most once per row per repair attempt, and repair is backoff-gated at 5s to 30s. The duplicate parse is real and the fix is trivial, but the saving is one small JSON read at a low rate.
  • #532 (session-instance) Hook status and age are read with two separate directory opens per poll: Real duplication: read_hook_status and read_hook_status_age each reopen the instance dir, plus the file open and fstatat. But the hook base fd is cached via with_hook_base, so the saving is one openat+close per session per tick. Microseconds; not user-visible.
  • #533 (session-instance) Status-transition debug logging does file I/O even when debug is off: Hook reads and detection_tool run eagerly before tracing::debug!, so claim holds. But it fires only on committed status transitions (line 88, prev != status), a few per session per minute at most. Negligible I/O. Guard is a harmless cleanup.
  • #534 (session-instance) Shell-stale heuristics strip ANSI and lowercase the pane repeatedly: Redundant strip_ansi/lowercase exists in pane_has_agent_content and pane_looks_like_bare_shell_prompt. But it runs only for Idle/Waiting candidates that are shell-stale or command-override, a rare state, on a few KB of pane text. Microseconds. Raw-vs-clean signature change touches tests for no visible win.
  • #535 (session-instance) Reserved Claude confirmation re-probes the transcript store on every poller tick until confirmed: The probe repeats per tick, but it costs one canonicalize and one is_file stat on a poller background thread, only for unconfirmed Preallocated Claude ids. The sidecar read (published) is not avoided by the proposed backoff. Backoff adds state and delays legitimate confirmation.
  • #536 (session-storage) unpopulated_projects canonicalizes each pinned project path on every sidebar rebuild: Claim is true but only non-populated pinned projects reach canonical_key, a handful of realpaths in microseconds, on rebuild in Project grouping mode only. Rebuilds are event-driven, not timed. Caching adds staleness risk (symlink changes) for no visible win.
  • #537 (session-storage) find_by_canonical_path canonicalizes every registry entry twice per lookup: Double canonicalize is real (load_merged key plus find), 2N realpaths. But callers are rare: per smart-rename resolution, new-session dialog, plugin host lookup. N is small. Fix is easy but the win is unmeasurable.
  • #538 (session-storage) managed_capture_store_is_exclusive loads every profile's registry and resolves config per profile: Lease contention returns before this check (comment says so). It runs only on sandboxed managed-store start, retried every 30s only if ambiguous, a rare state. Cost is a few small JSON parses. The load_instances_readonly swap is cheap and plausible but wins nothing visible.
  • #539 (session-storage) SessionsFileCache deep-clones rows on hit and never caches groups.json: Claims hold: cache hit does rows.clone() and groups.json is reparsed. But reloads are watcher-triggered by file changes, not a timer, and the data is hundreds of small rows. Cache is deliberately settled-stamp guarded; Arc plumbing touches every caller for negligible gain.
  • #540 (session-storage) Settings validators compile a Regex on every call: Regex::new per call is real (profile_config.rs:271-321), but callers are only settings validation on save or form edit, tens of entries at most, microseconds each. LazyLock is a trivial tidy-up, not a user-visible win.
  • #541 (session-storage) Sandbox login status resolves the full profile config three times: Three resolve_config_or_warn calls per sandbox_login_status is true (container_config.rs:2131, 2005, 1972 plus login_target_in). Callers are CLI check and a one-time serve-start log_login_status in spawn_blocking over a few agents. Not a hot path; each resolve is sub-millisecond.
  • #542 (session-misc) Idle reaper clones all rows and spawns tmux every 60 s even when auto-stop is disabled: Pass is gated to once per 60 s (idle_reap.rs:21). The tmux call is already in spawn_blocking. Clone is once a minute, tens of rows. Reordering is correct but saves one tmux spawn and a clone per minute. Not worth a change.
  • #543 (session-misc) Skill propagation recomputes the source package digest per root and per launch: Gated by skills.auto_propagate, default off, and the work is per launch of a user session. Digesting a few small skill packages is milliseconds. A stat-keyed memo adds invalidation risk for little gain; the per-root source digest repeat in sync_all_roots is a cheap local fix at most.
  • #544 (session-misc) Sandbox store purge walks the store twice (size then delete): Double walk is real (directory_bytes then remove_owned_store), but it runs once per sandboxed session purge, off any hot path, and only to print a freed-bytes message. lstat-only walk is cheap beside deletion. Not worth the change.
  • #545 (tui-loop-home) Metrics refresh clones every Instance each second even when hidden: request_metrics_refresh clones all Instances before the gate; the clone is dropped when diagnostics are off. Called once per second (app.rs:1323, not 1288). Cost is n struct clones per second, negligible at tens of sessions. Trivial reorder is safe but a win nobody sees.
  • #546 (tui-loop-home) Search-match highlighting uses linear Vec::contains per visible row: Claim is true (render.rs:1722 and 1803, visible rows only) but cost is negligible: rows ~50, matches ≤ hundreds, ~10k usize compares per frame. Proposed binary_search is wrong: search_matches is sorted by score descending (input.rs:7691), not by index. HashSet would work.
  • #547 (tui-views) Mention picker re-lowercases and re-sorts up to 5000 paths on every redraw: Code matches: lowercases up to 5000 paths per call, called in render plus input handlers. But empty query short-circuits, picker only open briefly, and 5000 short allocations cost well under 1ms per frame. Not user-visible; cache adds invalidation complexity.
  • #548 (tui-views) Row badge lookup scans every plugin entry for each visible session row: Per-row linear filter over snapshot.entries is real (home/render.rs:2237), but entries are few (plugin badges, tens) and rows visible are about 50, so under 2500 cheap comparisons per frame. serde_json::from_value clone only on matching entries. Negligible.
  • #549 (tui-views) OSC 8 hyperlink map sanitizes and scans the URI table once per cell: Claim true: insert() allocates a String and scans uris per cell. But a preview shows maybe 50-500 linked cells and the uris vec is tiny (a few entries). Microseconds per frame against a terminal draw; the fix is correct but unnoticeable.
  • #550 (server-api-sessions) Remote-owner cache takes a write lock on every publish when any repo has no origin: Claim is accurate: None-cached repos still take the write lock and rescan (list.rs:421-461). But the work is a few HashMap ops, with no libgit2 call after the first lookup. Contention is microseconds; the per-row SQLite lookups in project_sessions dwarf it.
  • #551 (server-api-sessions) Per-row artifact_dir_path stats the app dir on every publish: Real: artifact_dir_path calls get_app_dir (path resolution plus one exists() stat) per row, model.rs:69. A cached-metadata stat is about 1-2us. Negligible next to the per-row SQLite calls in the same loop. Hoisting is cheap but not a measurable win.
  • #552 (server-api-sessions) Background task output poll rescans /tmp/claude-uid and rereads 256 KB every 2s: Code matches, and it already runs in spawn_blocking. Poll runs only while a modal is open on a running shell. read_dir of /tmp/claude-uid is a handful of project dirs; a 256 KB local read every 2s is trivial. An offset or 304 saves bandwidth, not CPU.
  • #553 (server-api-sessions) Small sync disk reads on the async runtime in wizard and import handlers: get_recent_projects reads a small capped file and stats a few dirs per wizard open. unknown_profile_response is one readdir of a tiny dir at create time. outside_repository_cached short-circuits when .git exists, so libgit2 opens only for non-repo dirs every 30s. Negligible runtime stall.
  • #554 (server-streaming) Sandbox credential refresh reloads the whole profile store once per sandboxed session: Per-session load() and configuration() are real (status_poll.rs:262-341), but it runs every 30 min on a blocking thread, one session at a time, so no UI path waits on it. The agent config refresh per session costs more than the JSON parse. Grouping by profile adds lock-ordering risk for negligible gain.
  • #555 (server-streaming) Cloudflare tunnel health monitor polls try_wait every 10s: A 10s tokio sleep plus uncontended try_wait is a negligible wakeup, and the task runs only with a remote tunnel. The only real gain is faster exit detection. The restart path swaps the child inside the shared Mutex, and shutdown() locks it, so moving ownership needs a redesign.
  • #556 (server-state) Startup parses each profile's sessions file three times and enumerates profiles repeatedly, synchronously on the runtime: Redundant loads are real (startup_recovery.rs:14 and :36 reload). But it runs once per start before the listener exists, so blocking the runtime delays nothing else. Cost is a few ms of JSON parse for typical sizes. Not worth a change.
  • #557 (server-state) Startup recovery runs tmux subprocesses synchronously inside async tasks, once per candidate: Mark phase (startup.rs:1190) is deliberately awaited inline before status polling and runs once. Cascade's batch_pane_metadata is sync in a task, but only for recovery candidates (3 at a time) after tmux loss. The orphan check already uses spawn_blocking.
  • #558 (server-state) security_headers re-parses the CSP string into a HeaderValue on every response: Claim true, but or_insert(CSP.parse().unwrap()) evaluates eagerly every response; parse of about 500 bytes is sub-microsecond, dwarfed by the request. from_static is a harmless cleanup with no measurable user win.
  • #559 (acp-client) Lifecycle Progress signal sent through an mpsc channel for every streamed chunk: Progress is sent per chunk, but only on the local prompt path, via a 128-slot mpsc. The hop costs far less than map_update_to_events plus event_tx and persistence per chunk. The proposed atomics would break the channel ordering that apply_signal relies on.
  • #560 (acp-client) Post-load history replay fully maps every replayed update, then drops the events: The waste exists but runs once per session/load. The early return would also skip restore_wake_tool_title, tool_context_cache population, and first_event_after_attach, which ToolCallUpdate frames later in the replay may need. Gain is milliseconds per respawn.
  • #561 (acp-client) Direct stdio batch shim parses each agent line three times and reserializes it once: Triple parse is real, but the shim is used only by spawn_subprocess paths (list.rs and the no-socket fallback in mod.rs:620). Production uses the runner socket. Agent lines are small and rare, so the cost is negligible.
  • #562 (acp-client) AgentRegistry::with_defaults rebuilds an 11-entry HashMap with owned Strings on every call: Rebuild is real (agent_registry.rs:44) but costs about 11 small allocations, roughly microseconds. Callers are per-session create or spawn and API calls, not a hot loop. Many call sites use it too (about 25), so a static refactor is wide churn for no visible win.
  • #563 (acp-client) HttpClient::list_sessions builds a new reqwest client and pool on every call: Fresh DaemonClient per call is true (http.rs:844), but list_sessions is only called on a manual 'r' key in remote home, once on open, on structured-view open, and one-shot CLI verbs. No hot loop. Full-list fetch in session_view_info is real but once per open.
  • #564 (acp-client) Per-chunk text clone and six compaction substring scans on every agent message chunk: Clone and marker scans are real per chunk (update_events.rs:321-333, lifecycle.rs:54-66), but substring scans over short token strings cost nanoseconds. Per-chunk JSON decode, event-log append and broadcast dominate. Moving the text instead of cloning is a trivial safe tidy, not a win.
  • #565 (acp-supervisor) Elicitation pattern regex compiled on every validation: Code matches: Regex::new at elicitations.rs:498 per free-text answer. But it runs once per human submit of a rare agent form, microseconds for typical patterns. Fix would add a Regex field to a serialized question type. No user-visible win.
  • #566 (tmux) Status-rule lookups allocate keys per call and may reload config from disk: Per-call String allocs are real but trivial. The Config::load path runs only when source_profile is empty, which is rare for loaded instances. detect lowercases only for tools with custom rules, on a few KB capture. Not measurable against tmux forks per tick.
  • #567 (process-daemon) MetricsSampler clones every eligible Instance and scans instances per worker record: Clone, O(W*N) and logical_cpus are real but trivial for tens of instances. The same sample forks ps and tmux and reads /proc, which dwarfs them. Sampling runs only while the health UI is open. Only the pre-gate clone in pollable_instances is cheap to fix.
  • #568 (process-daemon) systemd scope retirement forks systemctl every 50ms and runs which() on every call: which() per call is real but microseconds. The 50ms drain loop only runs when systemctl stop succeeded and scope is still not empty, normally 0-1 iterations since stop is synchronous. Swapping to cgroup.events changes the proof semantics that scope_stopped deliberately checks.
  • #569 (process-daemon) File-watch debounce adds one timer slot per event and dispatch scans all subscriptions: Stale slots are real (arm_debounce pushes per event, fire_due_at skips stale). Cost is one cheap BTreeMap wake per event inside the debounce window, bounded by event rate. Subscriptions are few and notify_local_change is called only on storage saves, so the canonicalize cost is negligible.
  • #570 (process-daemon) boot_id re-reads /proc on every birth-identity check: Claim holds (uncached /proc read per call, macOS too) but cost is microseconds, and calls are per-worker liveness or launch/teardown, not a hot loop. Process_start_id in the same function costs more. OnceLock is safe but the win is not measurable.
  • #571 (process-daemon) Runner watchdog reads and fully parses its JSON record every 10s per runner: Accurate but trivial: a read of a small file and one JSON parse every 10s per runner, on a task that is otherwise sleeping. Minimal-struct parse is a harmless one-liner; tokio::fs and a file watcher add complexity for no measurable gain.
  • #572 (plugin-git-containers) ui.state.set revalidates by cloning and re-serializing payloads and scans all entries for quota on each new key: Triple pass and per-new-key scan exist (ui_state.rs:439-476). But payloads are capped at 8KB (64KB panes), entries at 1024 per plugin, so worst-case bulk fill is about 500k cheap iterations, tens of ms total, once. Counters add invariant risk for no visible win.
  • #573 (sweep-timers-polling) Push consumer ticks every 500ms and scans the TUI activity dir with nothing pending: Ordering is true (push.rs:705 is_tui_active before due_events at 734), but it is one readdir of a tiny dir (one file per live TUI) every 500ms. Also the suppression reason log depends on that check, so reordering changes logging. Dynamic sleep_until is overkill.
  • #574 (sweep-memory) fold_control_state clones the full AcpState for callers that need one bool: Clone is real, but reconciler candidates are filtered to idle sessions with non-empty queued_prompts, so few calls per 2s. A few Vecs cloned is microseconds. Real cost is spawn_blocking plus a cold SQLite replay, which with_state does not change.
  • #575 (sweep-memory) Per-session map entries survive session deletion: instance_locks is already pruned on delete (prune_unused_session_locks in delete.rs, with a test). Control cache forget() is called on delete. Remaining leaks are smart_rename_attempted and possible slot recreation, about 100 bytes per session, which is negligible.
  • #576 (trace-acp-stream) AgentThoughtChunk resets thinking.started_at on every chunk: Reset is real (state.rs:1220-1224, merged with ThinkingStarted), but started_at is never read: TUI and web only test thinking.is_some(). Nothing skips unchanged state; send_reduced_state fires per event with a new seq anyway. Fix is safe but saves nothing.
  • #577 (trace-acp-stream) Small per-chunk allocations in the ACP client mapping and control framing: Clone at update_events.rs:319 is real but one small memcpy per chunk, avoidable by reordering. Dedup uses amortized push_str, one copy per block, reset per turn. encode_frame capacity is moot: callers do frame.into() Arc<[u8]>, which copies anyway. Proposed prepend adds a memmove.
  • #578 (trace-terminal-stream) Server keeps four copies of the window per publish: Copies exist (cache clone, last_sent Strings, json, deflater input), but publish only runs on changed frames and the cache already keys on grid_gen. Idle hits cost one memcpy per 250ms. Memcpy of a few hundred KB is microseconds, dwarfed by deflate.
  • #579 (trace-terminal-stream) VT reader thread polls with a 200ms timeout: Poll at 200ms is real (vt.rs:2122), but 5 trivial wakeups/s per channel is negligible CPU. Proposed wake is wrong as stated: stop_and_wake_reader connects to the listener, not the accepted conn, so a shutdown(Read) on conn or a self-pipe would be needed. Tests inject the wait closure, adding churn.
  • #580 (rust-tests) #[serial(file_watch)] on two e2e tests that use separate homes: Only these two tests hold the named key file_watch, and named keys do not block default-key #[parallel] tests, so they only serialize against each other. Saves at most one test's runtime (seconds) across 6 threads. Both use per-test HOME and socket, so parallel is likely safe.
  • #581 (web-tests) Fixed waitForTimeout sleeps in mocked and live Playwright specs: Only 3 x 500 ms in focus-mode and 1400 ms in jump-to-bottom exist, spread over 6 parallel workers: under 1 s of CI wall time. They are negative observation windows; observeFor already exists in mockedTest.ts. dragRow's 250 ms is the dnd-kit hold, used by 2 spec files, not ~20. Not worth the churn.
  • #582 (web-data-layer) mergePrependedActivity copies the tail once per matched tool_start: Claim true (tail.slice per matched tool_start, reducer.ts:238, replay.ts:115) but k is only tool calls split across the single page seam, typically 0-2. Cost is negligible; lazy-copy flag is a trivial tidy, not a win.
  • #583 (web-data-layer) Each sidebar row registers its own window storage listener and reads localStorage on every render: Per-row listener is true, but subscribe is memoized on joined ids, so no re-subscribe per poll. The storage handler is a cheap key parse plus Set lookup, and localStorage reads are synchronous in-memory-backed. hasDraftAttachments reads a marker. Rows number in tens.
  • #584 (gap-create-launch-latency) Up to three separate config resolves in pick_agent_for_tool for custom tools: Up to 3 resolves holds (agents.rs:52-82), plus spawn_config. But they run in spawn_blocking, once per create or resume of a non-registry tool, and each is small TOML reads. Wall-time win is milliseconds. Merging into one with_resolved_config is safe but cosmetic.
  • #585 (gap-stop-delete-shutdown-latency) Terminal stop re-reads metadata for every tmux pane on the server to resample one row: batch_pane_metadata is real but runs inside spawn_blocking, once per HTTP stop: one list-panes -a, a few ms. A cached snapshot would still show the stopped session's panes, and an empty map changes sample_panes semantics. Win is negligible.
  • #586 (gap-stop-delete-shutdown-latency) Event-store session delete makes 4 autocommit DELETEs while holding the shared write connection: Four autocommit deletes are real, but the store uses WAL with synchronous=NORMAL, so commits do not fsync. The three small tables are cheap and the big events delete holds the mutex either way. Transaction gives atomicity, not speed. Chunking helps only for huge topics.
  • #587 (gap-session-store-service) Prompt path takes the instances read lock and scans linearly about 6 times: Reads are real (admits_turn x2, touch_and_wake, is_solo_command, send_turn) but each is a microsecond-scale find. Writers (acp_events.rs:527) hold the lock briefly and release before saves. Prompts are human-rate and dominated by tmux/worker work. Passing fields via SendTurnRequest adds stale-state risk.
  • #588 (gap-large-repo-git-scaling) ensure_branch_exists scans all remote branches linearly: Code matches, but scan is in-process libgit2 over packed refs (microseconds to low ms even at 50k refs) on a rare, user-initiated create path that also does a network fetch. Proposed fix changes semantics (ends_with matches nested remote names). Negligible.
  • #589 (gap-fleet-footprint-and-log-volume) VT reader thread wakes 5 times per second per armed channel even when the pane is idle: Claim holds: poll(fd,1,200) loops on timeout only to recheck stop; stop_and_wake_reader connects to the listener only. But 5 wakeups/s of a parked thread is negligible. A conn shutdown on ctx.stream would work but trades for little.
  • #590 (gap-plugin-runtime-and-pages) Per-row plugin slot selectors scan all entries repeatedly (O(rows x entries) per render): Four filter passes per row are real (PluginSlots.tsx:52,60,93), but entries only hold plugin-pushed state, typically a handful. Cost is microseconds per row; quadratic claim needs K per session at scale. Cheap tidy: compute once in PluginRowLine and pass down.
  • #591 (gap-plugin-runtime-and-pages) Every Node-less host RPC pays two thread hops (work.run task plus spawn_blocking): Two hops are real (host.rs:970 work.run, then spawn_blocking), but RuntimeWork is a JoinSet that tracks in-flight work for shutdown, so bypassing it for ui.* breaks drain. Skipping only spawn_blocking saves microseconds per RPC; negligible.
  • #592 (gap-plugin-runtime-and-pages) ui.state.set does an O(all entries) quota scan with String allocations per new key and a double JSON pass: O(E) scan per new key is real, but quotas cap per-plugin at 1024 and scope at 32, and the scan is of a small in-memory map; payloads are at most 8-64KB. Populate burst is microseconds to low milliseconds. Not user-visible.
  • #593 (gap-plugin-runtime-and-pages) Registry load parses each manifest TOML twice and reparses the builtin manifest per external plugin: Double parse and per-call is_builtin_id reparse are real (from_toml_str parses twice; is_builtin_id parses BUILTINS each call; set_enabled reloads twice). But manifests are tiny, there is at most one builtin, and reloads are rare user actions. Cleanup only.

6. Refuted or already handled

  • (session-instance) contended_capture_cwds resolves capture support and canonicalizes paths for every row on each due pass: The caller only runs this when some row is due. Inside, the loop already checks agent_session_id, tmux_alive_cached, then resolved_session_support, and computes contended_capture_key only for id-less live rows, which are few. The proposed gate ordering already exists.
  • (session-storage) resolve_config recompiles status-rule regexes and write-locks the global registry on every call: resolve_config is not on a polling path. Callers are startup, config watcher refresh, dialogs, and per-distinct-profile reconcilers in spawn_blocking. The comment says the status poll never loads config. Regex compile only happens when status_rules are declared; the write lock is held microseconds.
  • (server-streaming) Global ACP broadcast wakes every acp_ws socket for every session's events: Claim is accurate (acp_ws.rs:118 subscribes to shared channel, filters at 229), but web opens one acp_ws per mounted AcpRuntime (useAcpSession), so 1-3 sockets per tab. Filter is a string compare. A quiet session's receiver drains instantly, so cross-session lag is unlikely; the busy session's own socket lag is not fixed by per-session channels.
  • (tmux) Manifest evaluation re-lowercases region text and re-resolves markers per rule: Code does re-lowercase per rule and Marker regions are Cow::Owned, but screens are ~30 lines (few KB). Total is tens of microseconds per detection, dwarfed by the capture-pane fork that feeds it. Memoization adds RefCell state for no visible win.
  • (tmux) Name/shape resolution scans every live pane per instance per lookup: Fallback scan is a starts_with/ends_with check over tens of panes: instances x targets x panes is roughly 10^4 cheap string ops per 2s tick, microseconds. Derived-name fast path already exists in resolve_session_name_from_snapshot. An index adds cache-invalidation complexity for no visible win.
  • (cli-startup) get_agent() on custom or unknown names rebuilds plugin declaration lookups per call: bundled_agents::definitions() yields exactly one entry (once(&DEFINITION)), so available() runs declared_agent once per miss. The registry is a cached Arc after first load, and declared_agent returns early for builtin names. Cost is a few iterations, negligible.
  • (cli-startup) Daemon readiness wait polls every 50ms: await_daemon_ready (serve.rs:2240) sleeps 50ms between probes, but daemon boot takes hundreds of ms to seconds, so the expected overshoot is about 25ms. The ready probe is a local socket check. A pipe-based handshake is a larger change for negligible gain.
  • (plugin-git-containers) list_dirty_files materializes the full status list for a capped message: Runs only on worktree delete or remove-error paths. libgit2 statuses() computes the full walk regardless, so the walk dominates; formatting one String per entry is negligible and cannot be skipped by capping output. Only update_index(false) is a marginal option.
  • (sweep-timers-polling) maintenance_loop reads every worker registry file every 2s on the async thread: Claims hold (list() at worker_registry.rs:458, called from reconcile at acp_reconciler/mod.rs:295/642), but cost is one readdir plus a few small JSON files per 2s. readopt only probes attempted unowned ids, which is rare. The comment requires the sweep before scheduling because capacity counts registry entries, so a 30s cadence would delay legitimate spawns.
  • (sweep-timers-polling) ACP command loop wakes at 1Hz per live worker even when no agent-initiated turn is active: 1Hz tick (command_loop.rs:148,190) does a few uncontended std mutex locks, microseconds per tick; 30 workers cost about 30us/s. Gating needs a Notify at every arming path; a missed signal leaves a turn stuck without its idle fire. Risk exceeds win.
  • (sweep-timers-polling) Separate 60s cleanup timers could share the maintenance loop: Each task wakes once per 60s and does an O(n) retain on a tiny map. maintenance_loop ticks every 2s but also awaits docker, purge recovery and ACP reconcile, so a stall would delay these cleanups. The fix saves almost nothing and couples unrelated work.
  • (sweep-alloc-serde) Elicitation pattern regex compiled on every answer validation: Regex::new at elicitations.rs:498 runs once per user-submitted text answer to a form; human-rate, and compile of a typical pattern is microseconds. A cache adds a global Mutex and unbounded agent-keyed state for no visible win.
  • (sweep-subprocess) Per-session tmux liveness can degrade into a list-sessions fork per session when a tick outlives CACHE_TTL: Mechanism is wrong. status_poll.rs:512 refreshes the cache at tick start. A stale lookup calls refresh_session_cache, which re-publishes and restarts the 2s clock. So at most one extra list-sessions per 2s of serial work, not one per session.
  • (web-bundle) useShikiTheme drags shiki and @pierre/diffs into any importer just for a string constant: App.tsx:183 statically imports DiffFileViewer, and MobileMainPane does too. DiffFileViewer imports @pierre/diffs and @pierre/diffs/react directly, which pulls in shiki. So the shiki/pierre core sits in the entry chunk whatever useShikiTheme imports. Moving the constant saves zero bytes until the diff viewers are lazy-loaded. That lazy-loading is the real, separate change.
  • (gap-daemon-client-reconnect) Every status WS reconnect forces a full /api/sessions body per tab, re-serialized for each request: list_sessions already has ETag and 304 per revision. The full body is only built after a daemon restart or reconnect, and serializing one small list per tab is microseconds. A per-snapshot body cache and seed filtering are not worth the complexity.
  • (gap-daemon-client-reconnect) Passphrase-auth WebSocket connect reads cached session files from disk on every connect: The cache is per HttpClient by design, and the on-disk read is two tiny files once per WS connect, which already costs a network handshake. Login only happens after a 401 retry. A process-wide static would wrongly mix endpoints.
  • (gap-daemon-client-reconnect) Session-authenticated requests take two global write locks and hash the owner token on every request: The write-locked sections are a HashMap lookup and a remove with no await inside, so hold time is nanoseconds. Persisting is already throttled by REFRESH_PERSIST_THRESHOLD. A SHA-256 over a short token costs about 1 microsecond, far below the per-request network cost.

7. Coverage notes per finder

session-instance

Read fully, non-test code: status_update.rs (1-652), polling.rs (1-917), pane_status.rs (1-206), status.rs, capture_slot.rs (1-249), retroactive_capture.rs (1-191), tmux_session.rs (1-163), kill.rs (60-548), merge.rs (1-540). Read partly: accessors.rs (120-330, 380-800), execution.rs (140-420, 1866-1925), start.rs (1-420), session_id.rs (480-880), container.rs (40-105, 290-345, 405-680), hooks.rs (100-160, 500-560, 900-988), ready.rs (160-225), resume.rs (255-300), sid_persist.rs (1-60, 170-230, 330-420), prime_capture.rs (505-714), omp.rs (7-30, 257-300), launch_command.rs (250-360, 915-1000), mod.rs (1-200 and the Instance field list), lifecycle.rs (function list only). Grep only, not read in depth: identity_sidecar.rs, flags.rs, terminal.rs, types.rs, reconcile.rs, and the rest of start.rs, launch_command.rs, execution.rs, resume.rs and hooks.rs (launch-path internals). Test modules were skipped. To get frequency and cost I also read code outside the slice: server/status_poll.rs (tick is 500ms with subscribers, 2s otherwise; maintenance runs every 2s), server/session_identity.rs, tmux/session.rs capture, tmux/utils.rs pane helpers, hooks/status_file.rs, profile_config::resolve_config (uncached: 3 TOML reads, typecheck, regex recompile), status_rules, and containers/mod.rs. Already well optimized: the status poll runs in spawn_blocking with batched pane metadata. Hookless manifest agents skip captures through window_activity and the observation key. owned_status reads no config for undeclared tools. declared_agent is gated on registry_declares. Poller start checks the thread budget before expensive I/O and checks lease contention before scanning profiles. The list API resolves the resume config once per profile. Repair backoff (5s to 30s reprobe) exists for the NotApplicable outcome. Status::attention_order allocates 9 elements and is negligible. Notes for other slices: drain_session_id_updates_in_state clones every Instance (about 130 fields) every 2s, and the daemon rebuilds rows from disk each tick (server/reload.rs). Config::load is uncached crate-wide. install_from_config logs a shadow warning on every resolve. The doc comment on launch_has_session_publisher (polling.rs:203-206) says it "reads memory only" and runs "every TUI refresh". In fact it resolves config and is only called on launch and sid-persist paths, so the comment is stale.

session-storage

I read these non-test sections fully: src/session/storage.rs lines 1-2640 (atomic_write, no-follow helpers, locked_update, LockedDataFile, flock acquisition, StorageTransition, SessionsFileCache, load/update paths, launch configuration, managed_capture_store_is_exclusive) and 3119-3630 (workspace ordering, recent projects, duplicate reconciliation). Also read fully: src/session/sync.rs 1-998, src/session/poller.rs 1-835, src/session/groups.rs 1-1124, src/session/config/profile_config.rs 1-330. Read in part: src/session/anchored_fs.rs 1-570, src/session/mod.rs (app dir, profile dirs, list_profiles, TUI presence 290-560 and 1140-1225), src/session/config/mod.rs (tmux config probe 3810-3840, load/update_config/app_state/default profile 4170-4500, resolve_tmux_setting), src/session/projects.rs 255-500 and 990-1075, src/session/deletion.rs 1240-1333 plus a function index, src/session/trash.rs 100-147 and 275-397, src/session/config/container_config.rs 1960-2040, 2125-2145, 2415-2460. Skimmed only (function index): purge_owners.rs, sandbox_store_reclaim.rs. I found nothing hot in either. They run only on explicit purge/reclaim actions. Not read: storage.rs 2637-3118 (profile move transaction), 3631-4210 (journal repair and backups), config/repo_config/, config/settings_schema/ except merge.rs, container_config/seed.rs, and most of container_config.rs. Checked outside the slice only to confirm call frequency: server/status_poll.rs, server/acp_events.rs, server/reload.rs, server/api/sessions/list.rs, server/api/sessions/delete.rs, tui/app.rs, tui/home/rows.rs, tui/home/config_refresh.rs, tmux/utils.rs probe_pane, tmux/status_rules.rs. Already well optimized: the server reload uses SessionsFileCache with stamp and settle-tick validation. Capture drain returns early with no storage I/O when no poller has an observation. The CLI capture loop sleeps 200ms and is bounded. The poller uses adaptive backoff from 2s to 60s and a thread budget. Passive status writes are batched per profile in one update_with_snapshot. LockedDataFile::update skips unchanged writes. Server config consumers hold no tokio locks across flocks and use spawn_blocking. The list endpoint caches cleanup defaults with a TTL. The trash path caches protected default branches per sweep. The TUI config refresh is driven by the file watcher, not polling. Deliberate tradeoffs I left alone: the 50ms flock polling with a warn after 1s (documented in the storage.rs module docs), the repeated verify_current revalidation of anchored profile files (security), and the no-follow anchored writes. One assumption: the fsync finding relies on Rust's File::sync_all mapping to F_FULLFSYNC on Apple targets. I did not measure its cost here.

session-misc

Read fully or near-fully (non-test): src/session/poller.rs, capture/mod.rs, capture/codex.rs (scan and poll paths), gemini.rs poll path, kimi.rs poll and index paths, hermes.rs poll path, prime.rs scan and poll paths, pi.rs observation path, opencode.rs (once-per-launch serve helper, fine), omp/mod.rs and omp/container.rs poll functions, sync.rs, idle_reap.rs, worktree_reconcile.rs, conversation_summary.rs, claude_import.rs, restart.rs wake worker, claim.rs, artifacts.rs, mod.rs (app dir, TUI heartbeat), skills_model.rs (discover, digest, sync), mcp/mcp_model.rs and mcp_state.rs (resolve and reconcile paths), smart_rename.rs non-test (run_oneshot, terminal rename, try_smart_rename, apply_auto_title), storage.rs update/load/flock/atomic-write/cache/cleanup_protection regions, anchored_fs.rs read, stamp and write helpers, projects.rs load, merge and find paths, groups.rs tree and sort paths, builder.rs base-branch resolution, environment.rs host env helpers. Also opened callers outside the slice to establish frequency: instance/polling.rs, tmux/mod.rs, tmux/utils.rs, tmux/env.rs, server/idle_reap.rs, server/status_poll.rs, tui/app.rs, tui/home/status.rs and projects.rs, server/lifecycle_feed.rs, plugin/host_api.rs.\n\nSkimmed (function inventories and targeted greps, no full read): deletion.rs (7k lines), trash.rs (reconcile, sweep, protected-branch caching looked fine), purge_owners.rs, sandbox_store_reclaim.rs (reclaim and purge parts), attach_project.rs and conversation_carry.rs (user-initiated one-offs, only the account-swap transcript scan is mildly O(ids x projects)), recovery.rs, lifecycle.rs, cityhall_bundle.rs (boot-time only), sandbox_login/helper.rs (blocking std::fs inside async start(), user-initiated and rare, not reported), opencode.rs, builder.rs provisioning and branch naming, capture/claude.rs.\n\nNot reached: fork.rs, import.rs, scratch.rs, update_restart.rs, worktree_edit.rs, path_identity.rs, move_journal.rs, rename_transaction.rs, projection.rs, civilizations.rs, sandbox_login/claude.rs and code.rs, mcp/mcp_overrides.rs and project_mcp.rs beyond signatures, config/ and instance/ (outside slice).\n\nWell optimized (no finding): SessionsFileCache stamp-based reuse with the timestamp-tick settle window; LockedDataFile::update skips the write when serialized content is unchanged; poller backoff 2s to 60s with an adaptive interval; PollerBudget thread cap with repair/reprobe backoff; codex and gemini scans are bounded by entry, candidate and depth caps with anchored fds; trash sweep interval scales with the shortest retention window; smart-rename uses spawn_blocking, semaphores, and inflight guards; reconcile_trashed_profile and worktree reconcile use per-repo caches. All findings come from static reading, so nothing was measured.

tui-loop-home

I read these fully or in their relevant parts:

  • src/tui/mod.rs (all)
  • src/tui/app.rs, lines 90-1640 (struct, new, draw, with_raw_mode_disabled, the whole run loop and tick body, render), plus plan/decide_disk_refresh (2033-2069), reconcile_structured_preview (2514-2594), attach_live_session (3190-3215), sandbox_in_use, spawn_image_update_check
  • src/tui/worker.rs (non-test), src/tui/metrics_poller.rs, src/tui/plugin_ui_poller.rs (non-test)
  • src/tui/home/lifecycle.rs (new, reload, reload_storage_only, load_storage_projection, refresh_projection_presentation, rewire)
  • src/tui/home/status.rs, lines 1-1000 (metrics, snapshot_requires_storage_reload, apply_canonical_projection, apply_session_feed_with_dialogs, apply_daemon_status_update)
  • src/tui/home/rows.rs (non-test), selection.rs (first 120 lines), config_refresh.rs (non-test), projects.rs (15-160), layout.rs (1-60), pollers.rs, last_prompt.rs (non-test), preview.rs (100-260)
  • src/tui/home/watchers.rs, lines 1-330
  • src/tui/home/render.rs: HomeView::render, render_list, render_item_line, the preview capture-worker sync, apply_worker_capture, passive fleet reconcile, refresh_*_cache_if_needed, render_preview, paint_preview_links, paint_preview_selection, the start of render_status_bar, and the status bar Enter/Tab resolution
  • src/tui/home/overlays.rs: tick and wants_paste_burst helpers

I also opened these to confirm costs: session/mod.rs presence helpers, update_restart.rs, git/remote.rs get_remote_owner_with_key, storage.rs load_complete_with_groups and SessionsFileCache, profile_config.rs resolve_config, tmux/status_rules.rs install_from_config, tmux/mod.rs snapshot poller, links.rs link_spans_for_line, components/preview.rs (grep only), structured_view/embedded.rs tick.

Skimmed only: input.rs (update_selected, move_cursor, search matches, link hit-testing, live_send takeover poll, shortcut tip, drag end, rename/diff git one-shots), bindings.rs (static table), live_send.rs (capture cadence constants and worker spawn header only), operations.rs (grep hits), session_feed.rs (grep: watch-channel coalescing).

Not read: creation.rs, dialogs.rs, send.rs, reorder.rs, persistence.rs, profiles.rs, panes.rs beyond paired_terminal_running_for_display, user_action.rs, live_send_prep.rs, most of live_send.rs (2600 lines of worker internals), all test files under src/tui/home/tests and file_watch_tests.rs.

Already well optimized:

  • List rendering is virtualized to the visible window.
  • The preview widget clones only the visible slice of parsed Text (components/preview.rs:537-556).
  • ANSI parsing is cached per content change.
  • The capture worker dedups unchanged frames and only wakes the loop on change.
  • tmux capture and passive resizes are off the paint thread.
  • Draws are ratatui-diffed inside synchronized updates, and the tick path draws only when refresh_needed.
  • Mouse-motion repaint is gated on actual hover or link change.
  • The session feed uses a coalescing watch channel.
  • Serve probe and metrics sampling run on worker threads.
  • Plugin UI apply skips the redraw when entries are unchanged.
  • Theme reapply is deduped.

Deliberate tradeoffs I respected:

  • The 33ms tick during live-send (tearing comment).
  • One tmux fork per coalesced live-send batch.
  • Passive resize debounce.

Observed but not filed:

  • The telemetry snapshot clones all instances, but only at the telemetry interval.
  • get_update_settings loads config every 60s (negligible).
  • Post-attach refresh_session_cache plus reload runs synchronously once per detach (acceptable).
  • resolve_config_or_warn on click_action and rename-dialog git probes are one-shots per user action.

tui-views

I did static reading only. No builds or runs.

Read fully (non-test code):

  • src/tui/structured_view/render.rs (1-2298)
  • structured_view/embedded.rs (1-590)
  • structured_view/reducer.rs (1-469)
  • structured_view/mention.rs
  • markdown.rs
  • diff/mod.rs, diff/render.rs (1-480), diff/split.rs
  • plugin_ui_poller.rs
  • plugin_ui.rs (1-330)
  • links.rs
  • hyperlink.rs (1-200)
  • components/preview.rs, components/text.rs
  • remote_home/mod.rs (1-200)

Read in part:

  • structured_view/mod.rs: loop, setup, apply_ws_message, redraw, mention filter.
  • structured_view/state.rs: ingest_plugin_ui, slash.
  • session_feed.rs: 340-1985, covering the writer, connect, drain_command_errors, enqueue and try_recv.
  • settings/mod.rs: search and dirty tracking. settings/fields.rs: build_fields_for_category, installed_oneshot_agents. settings/input.rs: search keys.
  • styles/mod.rs.
  • dialogs/changelog.rs and projects.rs.
  • components/dir_picker.rs: refresh_dirs.

Outside the slice, I checked these to confirm frequency or cost:

  • app.rs: select loop, spinner interval, embedded event draw.
  • home/render.rs: the diff takeover at 1150-1172, row statuses at 2236, link painting at 3880-3930.
  • acp/transcript.rs: one row per chunk at 315-335, upsert at 1030-1054.
  • daemon_manager.rs locate_daemon, daemon/mod.rs native_http_client, git/diff.rs compute_changed_files.

Not read, or grep-skimmed only:

  • plugin_ui.rs 330-897 (block rendering helpers)
  • structured_view/input.rs, queue.rs, slash.rs
  • settings/render.rs
  • styles/themes.rs, resolved.rs, contrast.rs, palette.rs
  • remote_home/render.rs
  • components help, diagnostics, list_picker, text_input, hint_buttons, cycler, tool_config
  • most dialogs: plugin_manager, skills_manager, intro, rename, context_menu, command_palette, restart, agent_question, others

The dialog grep found no per-frame fs, subprocess or Regex work.

Already well optimized:

  • components/preview.rs render_scrolled_output paints only the visible slice of a cached parse. PreviewCache parses once per content change.
  • RetainedView caches its wrapped transcript keyed by width, theme and roots.
  • links.rs skips most rows cheaply before allocating the column map.
  • hyperlink backend skips all OSC 8 work when a frame has no links.
  • SessionFeed uses watch channels with has_changed gating, so idle ticks cost no allocation. Snapshots are shared Arcs.
  • The plugin UI poller runs off the UI thread and stops on auth failure.
  • EmbeddedView::next_event uses pending() correctly when there is no socket.
  • markdown.rs keeps the original line when it fits without wrapping.
  • The changelog dialog parses once and renders only visible lines.
  • The dir picker reads the directory only on navigation.

server-api-sessions

Read fully (non-test): sessions/list.rs (1-712), sessions/model.rs, sessions/diff.rs, sessions/search.rs, sessions/mod.rs, file_provenance.rs (1-276), queue.rs (1-380), git.rs (1-375), acp/history.rs (1-589), acp/mod.rs (1-280), acp/attachments.rs. Partly read: acp/prompt.rs (1-420, 600-700), sessions/update.rs (1-200), sessions/ensure.rs (189-366), sessions/lifecycle.rs (630-760), sessions/send.rs (560-633), projects.rs (100-340), groups.rs (140-240, 740-830), acp/worker.rs (755-800), acp/install.rs (139-222), acp/view.rs (20-42, 784-844), mod.rs (1-480), sessions/create.rs (704-720, 1724-1790). Also opened supporting code: server/runtime.rs publish/publish_loop/session_mutation_response, server/state.rs changed_files_cached, acp/event_store turns/wakeups/replay/attachments/mod conn(), events latest_by_discriminant, profile_config resolve_config, repo_config, claude_settings, git remote/diff helpers, web useDiffFiles, BackgroundShells, replay.ts. Skimmed by function index only: lifecycle.rs (rest), delete.rs, create.rs (rest), rename.rs, file_edit.rs, cli_create.rs, artifacts.rs, acp/config.rs, acp/worker.rs (spawn/restart/switch), acp/view.rs (handoff). Not read: sessions/tests.rs and all in-module test blocks. Already good: list_sessions serves the published snapshot with ETag/304 and Cache-Control no-cache; the response is streamed through a borrowing Serialize (no clone); compression layer exists in router.rs; park probe overlay runs in spawn_blocking after dropping the instances lock; cleanup defaults have a 30s TTL cache; search_sessions uses spawn_blocking with a clamped limit; most mutation handlers and storage loads already run in spawn_blocking; replay pages use the pooled reader connection; acp_attachment responses are immutable-cached; acp_files caps at 5000 entries in spawn_blocking; create_session_progress is an in-memory snapshot. Frequency notes: publish_loop period is 500ms with WS subscribers and 2s otherwise (runtime.rs:787), so project_sessions cost is paid even by an idle daemon; touch_session_access is not called by the web client.

server-api-system

Read fully (non-test code): system.rs 1-2452 (tests 2453+ skipped; lines 1000-1090 drop_stale_leaves/record_applied only skimmed), plugins.rs 1-1178 (job registry and mutation gates skimmed), sandbox_image.rs 1-420 (rest of dismiss handler skimmed), setup.rs, mcp.rs, plugin_settings.rs (resolve_options; project_options/group_options/pinned_model helpers at the tail were not fully read), skills.rs (mutation tail skimmed), telemetry.rs, logs.rs, client_log.rs, log_level.rs, mutation_guard.rs. Followed into: metrics.rs sampler, resolve_command.rs, builder.rs adapter_installed, update_check.rs, discover.rs, settings_schema registry/resolved, ui_state snapshot, update/install.rs, web polling hooks. Not read: telemetry.rs lines 200+ and the Stats of AvailableTools beyond detect_with_custom_agents. Already well optimized (not findings): update_status install_kind (OnceCell) and update_actionable (TTL cache plus detached task), sandbox image status registry check (15 min TTL, single-flight, generations), AvailableTools agent probes (memoized with TTL), web-ui-state PATCH (400ms client debounce), plugin icon/page serving (spawn_blocking, canonicalize), plugin_ui_state 304 handling, useSystemHealth (single in-flight, visibility and detail-aware gap), logs redact (static LazyLock regexes, applied only to the kept tail), most write handlers already use spawn_blocking.

server-streaming

Read fully (non-test code): src/server/runtime_ws.rs (1-1063), src/server/live_ws.rs (1-2115), src/server/acp_ws.rs (1-781), src/server/acp_events.rs (1-1163), src/server/pane.rs (1-949), src/server/status_poll.rs (1-657), src/server/push.rs (1-1429). tunnel.rs was skimmed: 100-220, 300-380, 470-566, 740-800, 985-1010, 1155-1272, plus a grep of all fn/loop/sleep/Command sites. Not read: tunnel.rs 380-470, 566-740, 800-985, 1272-1793 (preflight/parsing and sync probes, all startup-only). In-module test blocks were skipped.

To prove costs I opened code outside the slice: tmux/session.rs:914-1000 (composited capture fork chain), tmux/utils.rs:288-392 (first_pane_id fork), tmux/mod.rs:652-659 and 744-760 (session scan) and 1434-1464 (batch_pane_metadata), tmux/vt.rs:2822-3030 (sample cache, reconcile and heartbeat throttles), session_service.rs:1880-1960 (fold_control_state cache and its measured 68ms/342ms rebuild cost), runtime.rs:278-360 and 787-803 (publish dedup and publish_loop), acp/event_store (conn mutex, fired_wakeup_for_prompt, first_turn_context, replay_from), acp/protocol.rs:48-69, session/mod.rs (unread_enabled is an atomic; is_tui_active scans a directory), state.rs:19 (ACP_CHANNEL_CAPACITY=256), push_send.rs:88-94.

Already well optimized, not reported: VtChannel::sample_with_deadline has a shared per-channel sample cache keyed on grid_gen, so grid viewers of one pane do not re-render. reconcile_grid (1/s) and the owner heartbeat (1.5s) are rate limited per channel. The grid path wakes on vt watch changes with a 250ms ceiling and honors the idle cadence for backgrounded tabs. The FRAME_MIN_INTERVAL 16ms floor caps spew. The live_ws out channel (capacity 8) gives natural backpressure to the capture loop. The per-connection deflate stream and row patches cut bytes well. Runtime publish dedups by contents and serializes the snapshot frame once for all subscribers. The status poll uses ProfileSessionsCache and a 2s/500ms cadence that depends on subscribers. Push fan-out in fire_due_pushes is semaphore-gated with a shared client. The dwell map is pruned on Stopped/Deleting. runtime_ws offloads build_snapshot to spawn_blocking with a semaphore of 8. The live_ws paste std::thread::sleep runs inside spawn_blocking, so it does not block the runtime.

Caveats: the status-tick publish finding depends on project_sessions cost in runtime.rs/api (another slice). Whether the runtime_ws disk re-read is a deliberate freshness requirement is not fully proven (confidence medium). The snapshot-transport fork count excludes any extra forks for multi-pane composites, which I did not read.

server-state

Read fully (non-test code): src/server/assets.rs; src/server/startup_recovery.rs (lines 1-636); src/server/runtime.rs (190-806); src/server/acp_reconciler/mod.rs (1-689); src/server/acp_reconciler/idle.rs (1-249); src/server/mcp/wait.rs; src/server/mcp/mod.rs; src/server/reload.rs (1-380, 452-770, 1136-1615); src/server/session_store.rs (30-862); src/server/auth.rs (280-860). Skimmed: session_service.rs (fn index, 850-1030, 1460-1660, 1875-2130, 2160-2275); login.rs (95-330, 400-530, 660-680, 880-905, 1010-1025); passkeys.rs (220-330); access.rs (225-560, 833-928); startup.rs (491-640, 1060-1320); session_spawn.rs (fn index, 300-420; per-create and run on spawn_blocking, so not hot); mcp/control.rs (355-400, 698-760); token.rs, rate_limit.rs, router.rs (520-603), status_poll.rs (85-135, 340-640), idle_reap.rs, plus supporting reads in worker_registry.rs, profile_config.rs, status_rules.rs, control_cache.rs, api/sessions/list.rs (40-200), acp_events.rs (440-465, 724-762). Not read: acp_reconciler/rate_limit.rs and resume.rs bodies (reap_rate_limit_resumes runs every 15s; resume_one runs per spawn), most of session_service.rs (send_turn, creation registry), mcp/control.rs beyond read_output, startup.rs 640-1060 and 1320-1543. Already well optimized: rust-embed assets send a strong ETag with 304 and immutable caching for content-hashed files. The token check is a constant-time string compare with no hashing (sha256 runs only after success). Argon2 is not on the per-request path. Login session persistence is throttled by REFRESH_PERSIST_THRESHOLD and runs in spawn_blocking. Passkey persistence uses spawn_blocking. MCP wait_for is event-driven on status_tx with a per-session filter and a deadline, not polling. The reconciler idle reap (60s), terminal repair (30s) and rate-limit pass (15s) are cadence-gated and batch last_event_at_for_sessions in one query. resolve_per_profile dedups profiles and runs off-runtime. instance_lock_in and prompt_gate prune unheld entries. publish_startup_identity batches tmux env writes using one LiveSessionSnapshot. The rate limiter map is bounded at 10k with periodic cleanup. Overlap: findings 2 and 3 touch status_poll.rs and api/sessions/list.rs, which other slices may also report. They are listed here because runtime.rs::publish_loop and reload.rs drive them.

acp-client

Read fully (non-test sections): acp_client/connection/mod.rs, connection/notifications.rs, connection/subagents.rs (lines 1-475), connection/prompt.rs (1-420, skimmed the rest), connection/command_loop.rs (1-200, 333-395), acp_client/session_identity.rs, aoe_ingress.rs, control.rs (1-883), update_events.rs (1-726), tool_output.rs, tool_context.rs, lifecycle.rs, watchdog.rs, between_prompt.rs, batch.rs, resolve_command.rs, fs_handlers.rs, terminal_handlers.rs, transcript_filter.rs, control_protocol.rs (1-254), protocol.rs (1-250), node.rs (1-329), version_probe.rs (1-247), client/ws.rs (1-385), client/passphrase_session.rs (1-300), client/daemon_manager.rs. Skimmed: client/http.rs (95-405, 825-900, 1060-1235), client/discovery.rs, client/autostart.rs, adapters.rs (130-215), agent_registry.rs (40-135), agent_compat.rs (signatures only, handshake-time code), spawn.rs (125-150, 440-627), runner.rs (230-290, 380-430), acp_client/mod.rs (540-640), connection/establish.rs (grep plus 295-360), plan.rs (40-90), lifecycle and opencode via grep. Also checked out-of-slice callers: aoe_meta/mod.rs, terminal_handler.rs create_and_run, server/startup.rs:822, supervisor/launch.rs:608 (confirms the runner path is the production default), and the SDK 5.0 docs confirming request callbacks block the dispatch loop. Not read: reset.rs, raw_input.rs body, rate_limit.rs, config_options.rs, permission_handlers.rs, steer.rs, delete.rs, list.rs, opencode.rs, errors.rs, session_sandbox.rs, establish.rs in full, recovery_tests.rs and connection/tests.rs (tests). Already well optimized, so not reported: static regexes use OnceLock (plan.rs, spawn.rs scrub_stderr_secrets); stderr scrub only runs when debug is enabled (inside the tracing macro); fs read/write use spawn_blocking; replay decoding uses spawn_blocking with SyncIoBridge and a 64 KiB BufReader; WS heartbeats are dropped without waking the consumer; session_identity skips encoded-size work on the established path (stated tradeoff, respected); ToolCallContextCache is bounded at 256; subagent routes are capped at 256; the resume-idle watchdog disarms itself; the orphan check timer only runs during a prompt; the permission and elicitation handlers already use conn.spawn; lifecycle signals are not sent between prompts. The SDK's own per-message handler-chain trace rendering is noted in session_identity.rs as a deliberate reason to keep one notification handler; not re-reported.

acp-supervisor

I read these fully, skipping test modules: src/events/mod.rs (lines 1-759), src/acp/event_store/mod.rs, event_store/replay.rs, event_store/turns.rs, event_store/wakeups.rs, event_store/search.rs (prod part), event_store/identity.rs (prod part), src/acp/supervisor/sink.rs (prod part), src/acp/background_agent.rs, src/acp/workflow_journal.rs, src/acp/task_transcript.rs, src/acp/aoe_meta/ordering.rs. I also read most of src/acp/transcript.rs (TranscriptModel core and helpers, lines 1-1056).

I read parts of these: src/acp/state.rs (AcpState fields and the full apply_event fold), src/acp/supervisor/mod.rs (540-928), supervisor/publish.rs (1-200), supervisor/drain.rs (pump only, 195-335), supervisor/requests.rs (wait_for_worker), supervisor/teardown.rs (shutdown_and_wait poll loop), src/acp/runner_lifecycle.rs (LifecycleTable and SystemProcessControl), src/acp/context_primer.rs (fold and build), src/acp/sandbox.rs (90-200), src/acp/elicitations.rs (validate_text only), src/acp/aoe_meta/mod.rs (envelope parsing). I skimmed event_store/rate_limit.rs (update_rate_limit_budget only).

I did not get to: supervisor/launch.rs and supervisor/agents.rs beyond a grep (their blocking work goes through spawn_blocking), most of teardown.rs, event_store/account_limits.rs, event_store/attachments.rs, aoe_meta/lint.rs and lease.rs, and most of elicitations.rs.

Already well optimized:

  • The ChannelSink writer thread decouples SQLite from the worker socket drain. The queue is bounded at 4096 and a persisted receipt is waited on only after the seq lock is released.
  • WAL mode with synchronous=NORMAL, so a commit does not fsync.
  • The read-connection pool (reader(), MAX_IDLE_READERS).
  • Indexed (session_id, discriminant, seq) and (session_id, created_at) lookups. last_event_at_for_topics prepares once and does one indexed lookup per topic.
  • first_turn_context streams rows and stops at the first Stopped.
  • task_transcript and the WorkflowJournal follow files through the shared file watcher with a 50 ms debounce, a 30 s safety reread, bounded chunk reads and a MAX_LINE_BYTES cap.
  • ArrivalOrder caps its held frames and seen keys.
  • recent_diffs, session_notices and finished background_shells are capped.
  • The control cache folds the state live, so prompt dispatch does not replay the log.

Retention prune and completed-work sweep costs apply only when acp.replay_events is non-zero. The default is 0 (unlimited), so with default settings the log, superseded progress snapshots and ToolCallContent snapshots grow without bound.

Out of slice but worth handing to the server slice:

  • src/server/acp_ws.rs serializes every broadcast frame once per WS client.
  • Each WS client keeps its own AcpState and TranscriptModel fold.
  • A lagged client triggers replay_from(session, 0).
  • project_sessions in src/server/api/sessions/list.rs runs synchronous SQLite queries per session directly on the async runtime.

The global worker_notify Notify wakes every waiter across all sessions. That only happens on install and stop transitions, so I did not report it.

tmux

Read fully (non-test parts): src/tmux/mod.rs 1-2850 (caches, scans, passive resize worker, snapshot poller, server identity), src/tmux/status_detection.rs 1-127, src/tmux/status_rules.rs 1-184, src/tmux/detect/mod.rs, detect/manifest.rs 1-550 plus evaluate, detect/region.rs, detect/adapter.rs, src/tmux/utils.rs 1-742, src/tmux/osc8.rs 1-179, src/tmux/env.rs 1-292, src/tmux/composite.rs 1-265, src/tmux/status_bar.rs 1-284, src/tmux/tool_retirement.rs 1-226, src/tmux/session_kind.rs 1-75. vt.rs read: 1-620, 700-1072, 1184-1290, 1397-1470, 1600-2260, 2430-2470, 2575-3120. session.rs read: 100-1520. tool_session.rs: 115-400, 955-985. terminal_session.rs: outline plus 150-170, 360-400. Skimmed: detect/omp.rs (regexes are LazyLock), vt.rs seed install/drain fence (1290-1400, 1470-1600), session.rs owner-lock helpers (1520-2400, signature level only). Not read: vt.rs 2260-2430 struct fields, 3120-3830 (resize/Osc52Channel/shutdown), session.rs 2400-2710 (env file, create args), tool_session.rs 400-955 (retirement/kill), mod.rs 2850-3577 (agent availability probes), all #[cfg(test)] modules, the manifest TOML bodies beyond rule counts. Already well optimized: tmux socket resolution and tmux_prefix_display are OnceLock-cached; the session cache and pane-meta cache with refresh ids and TTL keep paint paths fork-free (session_exists_for_display, pane_dead_for_display); LiveSessionSnapshot batches per-pass lookups; the passive resize worker dedupes per session; env get/set are batched into one chained tmux call; capture_pane_with_cursor and composite capture fold probes and capture into one fork; manifest regexes are compiled once in a LazyLock; Screen caches most regions in OnceLock; VtChannel caches samples by grid generation and rate-limits reconcile (1s) and owner heartbeat (1.5s); the __vt-pipe helper is dispatched early in main.rs before full init; window_activity lets the poller skip unchanged captures. Cross-slice notes for the orchestrator: server/status_poll.rs calls refresh_session_cache unconditionally every tick, and server/pane.rs calls batch_pane_metadata in about 6 handlers without reusing the tick's snapshot. Many Session helpers use .output() with no timeout, which is a hang risk rather than a throughput issue.

process-daemon

Read fully (non-test code): src/process/mod.rs (to the tests module at 2190), src/process/metrics.rs, src/process/worker.rs, src/process/unix.rs, src/status_hooks.rs, src/file_watch.rs (to 994), src/hooks/status_file.rs, src/daemon/runtime.rs, src/daemon/runtime_connection.rs, src/daemon/live.rs, src/daemon/transport.rs (to 417), src/daemon/lifecycle.rs, src/task_util.rs, src/telemetry/aggregate.rs. Read in large part: src/process/macos.rs (170-420, 690-1012, 1100-1250, 1320-1471), src/process/linux.rs (1195-1420, 1749-1990), src/process/worker_registry.rs (369-790), src/process/runner/mod.rs (20-40, 380-470), src/process/prime.rs (300-400, 640-700), src/process/systemd/mod.rs (280-310, 680-850), src/logging.rs (1-90, 493-870, 920-1046), src/daemon/mod.rs (request/response path 1047-1330), src/hooks/command.rs (51-182), src/hooks/trust.rs (100-135), src/telemetry/mod.rs (40-60, 360-516), src/telemetry/state.rs (185-242). Skimmed by grep: src/process/runner/{shared,connection,jsonrpc}.rs (tokio Mutex use only, nothing hot found), src/hooks/dir_guard.rs (base fd cached via cached_get_or_init_apply; per-read cost is a few at syscalls), src/hooks/mod.rs, src/daemon/websocket.rs, src/daemon/wire.rs. Not read: hooks installers (hermes, codex, kiro, kimi, json_settings, config_io, settl, targets bodies; these are launch-time only), telemetry sanitize, plugins, form_factor, features, events, daemon/error.rs, endpoint.rs, process/systemd/notify.rs, process/linux.rs prime/census sections 1548-1748. Already well optimized: FileWatchService uses NonRecursive watches, batches paths_mut commits, and filters tempfiles and lockfiles. EnvFilter is built with with_regex(false), and hot process.ppid traces are guarded by tracing::enabled!. SizeRotatingWriter stats only every 16KB. Prime observe() is cached for 500ms behind try_lock. processes_matching batches every candidate into one /proc walk or one ps call (startup only). The server serializes the runtime snapshot frame once per revision and dedups unchanged contents. The web health hook pauses when the tab is hidden and keeps one request in flight. The telemetry sampler runs every 30min and snapshots every 4h. On Linux, metrics read /proc directly with no forks. peer_pid_from_socket has a 100ms connect cap.

cli-startup

Read fully: src/main.rs; src/util.rs; src/tips.rs (non-test); src/cli/agents.rs; src/cli/hooks.rs (first 110 lines); src/update/mod.rs (non-test); src/migrations/mod.rs (runner, version helpers, non-test).

Read partially: src/cli/extract_session_id.rs (arg parsing, ancestor walk, run_inner); src/cli/ps.rs (collect_tmux_states, collect_rows, load_instances); src/cli/runtime_read/mod.rs (run, finish, execute_inner, execute_local_api); src/cli/session.rs (wait loop); src/cli/serve.rs (daemon ready wait, stop loops, sleep sites only); src/update/install.rs (detect_install_method, update_actionable and install_kind caches, brew probe); src/agents.rs (detection types, help probe cache, get_agent, native_definition); v027 and v033 migration reconcile entry points and registry loaders only; supporting code in src/tmux/mod.rs (agent probes, detect_on_path, batch_pane_metadata), src/telemetry (track_cli_command and state), src/session/config/mod.rs (load paths), src/process/mod.rs (run_with_timeout, get_pane_pid), src/process/macos.rs (parent_and_argv0), src/tui/mod.rs (startup sequence), src/tui/app.rs (update check cadence).

Skimmed via grep only: src/cli/add.rs, src/cli/acp.rs, src/cli/worktree.rs, src/cli/logs.rs, src/cli/uninstall.rs, src/cli/graft.rs.

Not opened: the rest of src/cli/ (session.rs, serve.rs, mcp.rs, plugin.rs, sandbox.rs, definition.rs, runtime_read/render.rs, dto.rs, endpoint.rs), the bodies of historical migrations v001-v057, and most of src/agents.rs (static agent table, hook and resume logic).

Already well optimized (no finding): TUI startup uses in-process which::which with a TTL memo (agent_availability_snapshot), and login-shell probing is deferred and batched into one shell. Update-banner install-method and Homebrew probes are cached in a OnceCell and a 1h TTL with detached tasks, so dropped requests do not duplicate probes. The 24h update cache is respected in check_for_update. CLI telemetry flush is gated to once per 24h with a 2s timeout. Hidden hot helpers (__frozen-env, __vt-pipe, __smart-rename, __opencode-yolo) bypass clap and migrations. The plugin registry loads only on a parse failure or on first use. Hot-path commands skip the log sink via skips_cli_sink. Migrations short-circuit on a current schema except for the reconcile scans noted above. The help-probe cache keys on binary mtime and size. Runtime reads use a single WebSocket exchange over a Unix socket.

plugin-git-containers

Read fully: src/plugin/host.rs (non-test), host_api.rs (non-test), ui_state.rs (non-test), automation_policy.rs (non-test), update_check.rs, auto_update.rs, integrity.rs, registry.rs, featured.rs, view.rs, contributions.rs, mod.rs, worker_logs.rs, src/git/mod.rs, git/command.rs, git/diff.rs (non-test), the hot parts of git/worktree/mod.rs, branch.rs, create.rs and cleanup.rs, src/containers/mod.rs, stats.rs, image_update.rs, the runtime.rs inspect/batch paths, the runtime_base.rs command/probe paths, src/sound/*, acp-worker/aoe-agent/src/index.ts and transcript.ts, src/github/client.rs (top 260 lines). Also read the callers I cite: status_poll.rs maintenance loop, server/state.rs changed_files_cached, api/sessions/diff.rs and list.rs, api/plugins.rs ui-state, web usePluginUiState.ts and useDiffFiles.ts, instance/container.rs start path, process/mod.rs run_with_timeout, events/mod.rs prune and scan.\n\nSkimmed: session_api.rs (non-test: dispatch, capabilities, sessions_create, turn_send), fetch.rs (fetch, git, ls_remote paths), discover.rs (discover/probe), agent_integration.rs (status, report, config cache), execution.rs in containers (first 200 lines), git/remote.rs (URL parsing and getters), git/worktree/relocate.rs and template.rs (grep only, rare paths).\n\nNot read: install.rs, launch.rs, changelog.rs, lockfile.rs, sandbox.rs, protocol.rs beyond its head, agent_definition.rs, bundled_agents.rs, plugin/execution.rs, containers/container_interface.rs and error.rs, git/error.rs, github/error.rs, sound/config.rs, aoe-plugin-api (manifest.rs 2k lines, only grepped for Regex/lazy: none), acp-worker/adapters (package.json only) and test-shim/shim.mjs (test-only).\n\nAlready well optimized (not findings): containers/stats.rs (off-thread docker stats with a 15s TTL and a single-flight flag, never blocks callers); batch_container_states (one docker ps for all sandboxes, post-filtered); plugin session-event queue (bounded 64, lossy, biased writer, so a stalled worker cannot grow memory); push_session_event skips work when no worker opted in; agent_integration effective_config (stamp-keyed single-entry cache); sample_sandbox_health skips docker entirely when no sandbox rows exist; git2 used for diff, status and branch lookups rather than subprocesses, with find_main_repo reading the gitfile first to avoid costly opens; the GitHub topic discovery probe phase is bounded (8 concurrent, 6s deadline); server plugin handlers use spawn_blocking for install, config and registry reload; walk_worktree_stats has a depth cap; the ReconcileCache amortizes list_worktrees in the reconcile sweep; PURGE markers and fs2 flock avoid git subprocesses.\n\nConfidence caveat: I did not measure anything. Impact is rated from code structure and call frequency, and the unbounded-log and ui-state items depend on runtime behavior I could not run."

sweep-async-blocking

Method: wrote a heuristic scanner in /tmp/aoe-scan (outside the repo) that labels each match of std::thread::sleep, std::fs, std::process::Command or .output(), block_on, Storage load/update, tmux/git helpers, and acp_event_store calls by its enclosing context (async fn, async block, spawn_blocking or thread). Also scanned for tokio lock guards that live across .await, unbounded_channel, and spawn-in-loop. I opened and read every hit on a repeated path before reporting it.

Clean or already well optimized (not reported):

  • std::thread::sleep: every hit is in a sync fn, a dedicated thread (restart.rs:119 wake worker) or a test. None runs directly in async non-test code.
  • std::sync guards across .await: none found. Clippy's await_holding_lock is on by default and not allowed anywhere.
  • Commands in async: all use tokio::process (tunnel.rs, background_agent.rs, acp install, sandbox_login helper). runner.rs:410 builds a std Command only as an env snapshot and never runs it.
  • Storage writes in session_service.rs:1332/1391/1436, idle.rs:137, status_poll refresh_sandbox_stores, pane.rs, groups.rs, ensure.rs, disk_watch.rs and startup_recovery all use spawn_blocking. Per-instance tokio locks held across those spawn_blocking calls are deliberate serialization.
  • acp_reconciler query_store/query_flushed (mod.rs:146-175) and fold_control_state (session_service.rs:1902) already move SQLite work off the runtime, with a comment citing 68 to 342ms scans.
  • The park-probe overlay in list.rs:338 is already in spawn_blocking.
  • The event writer is a dedicated thread behind a bounded 4096-slot SyncSender (sink.rs:111).
  • tmux refresh_session_cache does not hold SESSION_CACHE while it spawns.
  • live_ws per-keystroke input and resync use spawn_blocking sequentially, which keeps ordering.
  • Unbounded channels: plugin host.rs:747 is a documented deliberate tradeoff. file_watch.rs:283 receives notify events for profile dirs only (low volume). session_service.rs:2414+ is test-only. runner_lifecycle.rs:386 carries oneshot senders (low volume).
  • acp-worker TS: no *Sync fs or exec calls in aoe-agent/src; only test-shim uses appendFileSync.
  • Per-request config reads in system.rs get_settings and get_update_status, plus get_recent_projects (list.rs:28), are synchronous but per page open, so I treated them as negligible.

Read fully: src/server/api/sessions/list.rs (1-460), src/acp/supervisor/sink.rs (non-test), src/acp/session_tee.rs, src/server/runtime.rs publish and publish_loop, src/server/api/acp/config.rs (98-285), src/server/acp_reconciler/idle.rs (40-175), acp_reconciler/mod.rs (140-330, 590-685). Skimmed: status_poll.rs, reload.rs 1223-1460, live_ws.rs (600-660, 755-790, 1018-1175, 1720-1775), session_service.rs 1300-1460 and 1895-1935, storage.rs 1780-1840 and 2462-2560, event_store mod.rs, turns.rs, wakeups.rs, attachments.rs, replay.rs signatures, drain.rs 180-340, supervisor/mod.rs 880-920, publish.rs, history.rs 330-480, prompt.rs, queue.rs, pane.rs, ensure.rs, ready.rs, kill.rs, restart.rs, worker_registry list and is_record_live, tmux/mod.rs name resolution, vt.rs Osc52Channel, logging.rs sink setup, main.rs subscriber init, plugin/host.rs, file_watch.rs channel setup. Not covered: the TUI main loop's synchronous reload and config reads (src/tui/app.rs:1395-1460, left to the TUI slice), src/cli/* (one-shot processes), src/process/* internals beyond registry listing, src/plugin/* beyond host.rs, events/ retention cost per insert (prune_retention runs on every record(), which belongs to the event-store slice), and the remaining server/api handlers not caught by the scanner.

sweep-timers-polling

PERIODIC WAKEUP INVENTORY (period | per-tick work | scales with) Daemon / server:

  • status_poll_loop (server/status_poll.rs:463): 2s, 500ms with runtime WS subscribers. Runs tmux list-sessions + list-panes -a, opens the retirement journal, does a cached profile load, and per tmux session per tick: hook file read, plus capture-pane unless skipped. Ends with publish(). Scales with session count.
  • maintenance_loop (status_poll.rs:350): 2s. GC maps, reconcile_acp_workers (registry list, readopt, drains, rate-limit park SQLite per target), sandbox health docker ps every 5s, purge recovery every 30s, credential refresh every 30m, idle reap and sleep inhibit on their own cadences, ACP idle reap 60s, terminal repair 30s, rate-limit resume 15s. Scales with sessions and workers.
  • publish_loop (runtime.rs:786): 2s or 500ms, plus wake Notify. Runs project_sessions: O(N) work with SQLite and config reads.
  • runtime_ws heartbeat (runtime.rs:736): 30s ping per client.
  • session_status_ws (session_status_ws.rs:181): 25s ping per client. Dwell timers use sleep_until (good). Runs publish per status change per client.
  • acp_ws ping 30s, live_ws ping 30s per client.
  • live_ws capture loop (live_ws.rs:2007): 50ms fast or 250ms idle per open terminal. Grid-driven on unix, with idle cadence when the tab is backgrounded (deliberate). Not deep-audited; belongs to the terminal slice.
  • push consumer (push.rs:559): 500ms plus broadcast recv.
  • serve_snapshot (serve_snapshot.rs:19,24): about 4h plus a 30m sample. Fine.
  • rate_limit cleanup 60s, login cleanup 60s, recently_restarted GC 60s, recovery refresher 4s (only during startup recovery), trash sweep follows retention (sweep interval read via spawn_blocking).
  • token rotation: sleep(lifetime). Tunnel child watch 10s, funnel status every every (subprocess). Fine.
  • disk_watcher_consumer: event-driven (Notify) with retry backoff. Good.
  • file_watch dispatcher: event-driven, sleep_until the next debounce slot. Good.
  • status_hooks / callback: debounce sleeps only, not periodic. ACP / runner:
  • command_loop idle_tick 1s per live worker. Prompt orphan_check 5s, only during a turn. resume-idle watchdog during adopted turns only (bounded).
  • runner watchdog (process/runner/mod.rs:390): 10s per runner, reads its own record file. Cheap.
  • runner cleanup retry 500ms with no backoff (runner/mod.rs:489): rare failure path only.
  • background_agent tailers 500ms per sub-agent (docker exec for sandboxed sessions). task_transcript and workflow_journal use FileWatchService with a 30s safety reread and fall back to 500ms only without a watcher. Good.
  • session id poller (session/poller.rs): one OS thread per session, adaptive 2s to 60s backoff. Good backoff. Thread-per-session noted, not reported.
  • acp-worker/ (Node adapters): no production timers found. test-shim only. TUI:
  • main loop refresh_interval 33ms always. Inside it: spinner redraw 120ms, metrics 1s (only when health is visible), plugin UI HTTP 3s, serve probe 2s (pid file), presence count 3s (readdir), heartbeat write 10s, disk/projection heartbeat 5s, update check throttled.
  • structured view REDRAW_INTERVAL 120ms, plugin UI poll 3s, ws reconnect 250/500/1000ms (bounded).
  • LiveCaptureWorker 25ms fast or 250ms idle, vt grid when available, plus a 10s authoritative capture. Terminal slice, not deep-audited.
  • boot migration spinner 120ms (startup only). Web:
  • useSessions 3s recursive setTimeo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment