Reduce structural complexity: state hubs, monolith functions, and parallel mechanisms

Aperta
#178 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
25/100
Tipo di issue
Refactoring
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
rust

Direzione di ricerca

Start with the relevant findings and acceptance criteria in this issue, then read the named entry points such as src/agent/run.rs, src/tools/mod.rs, and src/ui/tui.rs; the issue describes changes across many subsystems and leaves product decisions open. Pick one scoped phase or decision and trace its named tests or checks before changing anything. Done means the selected change meets its acceptance criteria while preserving the explicitly listed behavior; the issue gives no single completion target for the whole audit.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

area: agent-loop area: tools enhancement priority: P2

Preflight

  • Searched issues and discussions: no existing cross-cutting complexity audit. Related work stays in #169 (progress guards), #41 (duplicated tool inventory), #42 (schema pricing).
  • This is a harness change, not a request for the model to behave better.

Where it lives: agent loop, tools, TUI/CLI, docs and distribution.
Can code hold it? Yes — the splits are compiler-checked, and the existing integration suite pins behavior.

Summary

A static complexity review of the tracked tree at f96537f (after #172). The finding is not "too much duplicated code": 3,006 non-trivial function bodies contain 14 exact-duplicate groups (~133 LOC). The cost is scope and shared state:

  • three state hubs with 43, 52, and 19 fields;
  • two functions over 850 lines (run_loop 1,140, execute_batch 879);
  • five allow/deny/ask vocabularies;
  • 26 tools across 35 modules, 21.3k product LOC in src/tools/;
  • 144 config fields, 32 global options, 29 command entries, 30 slash commands.

Each piece is specified and tested. The question is not "what is sloppy?" but "which commitments are worth their maintenance and context cost?" The plan below removes ~2k lines, reorganizes ~2.7k, and leaves the product decisions explicit.

Scope and method

  • Tracked Rust only: 122,674 lines (src/ 107,609, tests/ 15,065). extensions/ and skills/ are gitignored reference material (.gitignore:3-4, ARCHITECTURE.md:2120) and are excluded.
  • Static analysis; the suite was not run.
  • Function lengths: brace matching after masking string literals and comments. Duplicates: normalized-body hashes for bodies ≥120 chars. ToolContext usage: ctx.<field> counts per tool module. Schema tokens: chars / 4, approximate, not tokenizer-exact.
  • Reproduction in the appendix.

F1 — Three state hubs

Hub Fields Shape
Core (agent/mod.rs:35) 43 18 Arc, 7 Mutex; derived text stored twice (system_prompt / repo_brief); tool_specs_json / tool_specs_cost are caches whose freshness depends on rebuilding Core
App (ui/tui.rs:402) 52 UI-only, in a 1,781-line file: transcript, turn state, input, modal, completion caches, telemetry, plan, running tools
ToolContext (tools/mod.rs:174) 19 median registered tool reads 3 of 19 fields; 7 of 35 tool modules read none; profile is set in three places and read by no tool

Proposal

  • ToolContext into Workspace { cwd, path_jail, paths }, Turn { session, artifacts, cancel, caps, packs }, Services { lsp, bg, sandbox, vision, reads, security }, Policy { trust, edit_mode, verify, format_on_edit }. Delete profile. 26 tool files, compiler-checked.
  • App into ChatState, TurnState, InputState, OverlayState, Telemetry.
  • Core into TurnInputs, Services, Caches; derive repo_brief once instead of storing it beside system_prompt. Do this last.

Acceptance: no state struct over ~20 fields; rg 'ctx\.profile' src/tools is empty; the 1,280 tests are unchanged.

F2 — Two functions hold the loop

Function Location Lines ~Branches
run_loop agent/run.rs:419 1,140 108
execute_batch agent/run.rs:2866 879 84
execute workflows/engine.rs:675 553 42
create_runtime app.rs:169 487 50
probe doctor.rs:101 330 —
finish_review agent/run.rs:3751 327 —
run cli.rs:363 317 —

35 functions are ≥150 lines; 7 are ≥300.

run_loop already delegates to named stages (prepare_turn_context, stream_assistant, execute_batch, auto_settle, finish_review). The orchestrator should be a turn state machine with six phases — prepare, stream, route, batch/approve, settle, finish — and a TurnState instead of threaded locals.

execute_batch should split by call class: read-only parallel, mutation sequential, and approval/retry.

Acceptance: no function over 300 lines in agent/run.rs; tests/agent_loop.rs passes with only helper renames.

F3 — Parallel mechanisms

Permission decisions

Five types carry an allow/deny/ask shape:

  • policy::Decision / PermissionMode (policy/mod.rs:33, :305) — the real engine.
  • hooks::Decision (hooks.rs:155) — hook block/allow.
  • provenance::Gate (provenance.rs:842) — instruction provenance.
  • security::Scope (security/scope.rs:45) — engagement scope.
  • serve::api::PermissionMode (serve/api.rs:44) — a full duplicate of the policy enum, with its own parse, label, policy mapping and tests.

Proposal: delete the serve enum and add parse to policy::PermissionMode; keep scope, provenance and hooks as fact producers; use one Decision at the dispatch boundary. This does not overlap #169, which is about progress guards.

Model-output recovery

Four sites own one conceptual job, ~2.7k LOC:

  • provider/accum.rs — SSE fragments and truncation;
  • agent/output.rs — think tags, text-embedded calls, repetition;
  • agent/repair.rs — aliases, coercion, name routing;
  • agent/run.rs — truncation verdicts and output recovery.

Proposal: one model_output pipeline with ordered, named stages: split reasoning → extract text calls → resolve name → repair args → validate → truncate/recover. Same behavior, one stage table and one test surface.

Command surfaces

32 global options, 13 top-level plus 16 nested subcommands, 30 slash-command arms (28 distinct names) with 25 handlers, and 873 LOC of completion. Adding a command currently means touching several of them.

Proposal: one metadata table (name, aliases, summary, handler) for slash help and completions; keep clap for parsing. Drop deprecated spellings (ask, dont-ask) and the tool-name shims test→verify, patch→edit (tools/mod.rs:683-696) — this is a pre-1.0 project.

F4 — Surface area

Tools

26 registered tools (tools/mod.rs:586). Default coding in text mode is ~3.2k schema tokens; full ~4.6k; the skill index adds ~600. That is 10–16% of a 32k window — tolerable. The cost is 21.3k product LOC and model choice, not the tokens.

Trim LOC Tokens/turn Note
Drop hash edit mode (patch.rs) ~1,400 total (≈720 product + tests) 478 when selected Builtin hash profile at config.rs:272; shared hunk/edit helpers stay
Merge glob into grep --files ~270 98
Merge recall into read --artifact ~297 118

Also: patch's description says "Exact-anchor edit by default" (tools/patch.rs:31), but tools/mod.rs:676 only exposes it in hash mode. Model-facing drift; fix or delete.

Before committing to any merge, A/B the reduced surface with provider/probe.rs, which already classifies tool-probe outcomes.

Config and CLI

144 fields across 20 structs in src/config.rs. Top-level fields have readers; the sub-structs need a full audit. Rule: every key has one non-config reader and one doc line, or it goes. The same applies to the 32 global options.

Docs

10,623 tracked Markdown lines (ARCHITECTURE 2,440). The 26-tool contract is stated in both ARCHITECTURE.md:818 and docs/usage.md:71; the permission-mode vocabulary appears 14 times across four documents. Keep ARCHITECTURE as the spec and docs as the guide; link instead of restating.

Distribution and media

Six install recipes (install.sh, AUR source, AUR binary, Homebrew, Nix, Docker) and four workflows before a release; AUR is still unpublished. Pick three and let distro packagers own the rest.

docs/assets is 14 MB; demo.gif (6.2 MB) and demo-short.mp4 (1.4 MB) are referenced nowhere. Removing them saves 7.6 MB in the checkout.

F5 — What is not the problem

  • Duplication: 14 groups, ~133 LOC across 3,006 bodies. Do not spend a week on a dedup pass.
  • Tests: 1,280 tests, 5,248 assertions, 23% of src. They are the safety net for every change here. The gap is UI at 7.2% inline tests, not too many tests.
  • Dependencies: 37 direct, 369 in the lock graph. textwrap has zero references and should go; the ten deps used in a single file are individually justified.

Plan

Phase Work Impact Risk Gate
1 Remove textwrap; serve duplicate enum; tool shims; dead profile; unreferenced media; fix patch description ~100 LOC, 1 dep, 7.6 MB Low cargo test
2 One Decision at dispatch; one recovery pipeline ~2.7k reorganized Medium 277 integration tests
3 Split ToolContext → App → Core 0 LOC, ~29 files Low–medium Compiler, behavior unchanged
4 Extract execute_batch, then run_loop; workflows::execute; create_runtime 0 LOC, less branch mass High Integration suite + headless replay
5 Product trims: hash mode, glob/recall; config audit; distribution ~2k LOC, ~216 tokens/turn Medium provider/probe.rs A/B, token accounting

What must not change

  • SSE accumulation across engine dialects (provider/accum.rs).
  • The session tree and its eight entry kinds (append-only).
  • run_turn as the single turn seam: cli, host (ACP and serve) and workflows all call it.
  • The policy engine, deterministic compaction, and the sandbox.
  • Model-output recovery itself: consolidate it, do not delete it.

Open product decisions

  1. Hash edit mode: keep the opt-in feature and its ~1.4k LOC, or drop it? #10 shipped it; this is a commitment question, not a defect.
  2. Tool count: merge glob/recall, or keep 26 for model reliability? Decide with the probe, not by taste.
  3. Distribution: which three install paths survive?
  4. Config: which keys are commitments, and which were experiments?

Related

  • #169 — five progress guards into one ledger. Separate mechanism; do not duplicate.
  • #41 — duplicated tool inventory in the system prompt.
  • #42 — price tool schemas once and by density.
  • #59 — AST/LSP multi-file refactors; affects the tool count.
  • #10 — hash-anchored edits (closed); the feature that carries the patch cost.

Appendix: reproduction

# tracked size
git ls-files -z '*.rs' | xargs -0 cat | wc -l          # 122674

# duplicates: mask strings/comments, normalize whitespace, hash bodies >=120 chars
# function lengths: mask strings/comments, brace-match each `fn`, report >=150

# ToolContext field usage
rg -o 'ctx\.[a-z_]+' src/tools/*.rs | sed 's/.*ctx\.//' | sort | uniq -c

# surface
./target/debug/tot --help | rg -c '^\s+(-|--)[a-z]'    # 32 global options
./target/debug/tot --help | sed -n '/^Commands:/,/^$/p' | rg -c '^  [a-z]'  # 13 top-level
awk '/match name \{/,/^        \}/' src/ui/tui/commands.rs | rg -c '^\s+"'   # 30 slash arms

# schema tokens (approx)
# sum string-literal bytes in each tool's schema() + description(), divide by 4
Lingua principale
Rust
Stelle
0
Fork
0
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di GotinhaAzul/LocalHarness

Tutte le issue di GotinhaAzul/LocalHarness

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.