@@ -0,0 +1,89 @@
1+# Code Health Analysis
2+
3+## Scope
4+Reviewed the TypeScript codebase in `src/` for code smells: duplication, tight coupling, oversized modules, unsafe patterns, and maintainability risks.
5+
6+---
7+
8+## Findings
9+
10+### 1) God module / high complexity: `src/agent/agent.ts`
11+- **Smell:** Single file with very broad responsibilities (session lifecycle, CLI interaction, subagent orchestration, MCP wiring, snapshot/undo flow, model turn handling).
12+- **Evidence:** ~775 lines and many nested functions (`runSubagent`, `processUserInput`, `renderStatusBarForSession`, etc.).
13+- **Impact:** Harder to reason about, test, and safely change; increases risk of regressions.
14+- **Recommendation:** Split into focused modules (e.g. `session-runner`, `subagent-runner`, `undo-snapshot`, `input-loop`, `mcp-runtime`). Keep `runAgent` as composition entrypoint.
15+
16+### 2) God module / rendering mixed with stateful stream logic: `src/cli/output.ts`
17+- **Smell:** UI primitives, spinner, glyph vocabulary, tool-call formatting, subagent stream rendering, diff rendering, status bar, error rendering all in one file.
18+- **Evidence:** ~935 lines, many responsibilities and nested queue/tick/flush behavior.
19+- **Impact:** High cognitive load and brittle changes; difficult targeted unit testing.
20+- **Recommendation:** Extract: `spinner.ts`, `tool-render.ts`, `stream-render.ts`, `status-bar.ts`, `error-render.ts`, and keep `output.ts` as facade.
21+
22+### 3) Tight coupling to global process state in CLI/output stack
23+- **Smell:** Direct writes and signal handling scattered in rendering/terminal functions.
24+- **Evidence:** `process.stdout.write`, `process.stderr.write`, `process.on("SIGINT"|"SIGTERM"|...)`, raw mode toggling in `src/cli/output.ts`.
25+- **Impact:** Hard to test deterministically, side effects leak across features, higher chance of terminal-state bugs.
26+- **Recommendation:** Introduce a thin `TerminalIO` abstraction injected where needed; centralize signal registration in one lifecycle module.
27+
28+### 4) Destructive DB migration strategy in `src/session/db.ts`
29+- Intentional, not an issue.
30+
31+### 5) Database layer combines many bounded contexts
32+- **Smell:** One module owns sessions, messages, prompt history, MCP server registry, settings, snapshots.
33+- **Evidence:** `src/session/db.ts` exposes many unrelated CRUD APIs in one file.
34+- **Impact:** Hidden coupling and broad blast radius for edits; hard to isolate tests and optimize specific query domains.
35+- **Recommendation:** Split repository-style modules by domain (`session-repo`, `message-repo`, `settings-repo`, `mcp-repo`, `snapshot-repo`) sharing one DB connection provider.
36+
37+### 6) Clear duplication across config loaders
38+- **Smell:** Repeated directory scanning/parsing/merge logic in:
39+ - `src/cli/agents.ts`
40+ - `src/cli/skills.ts`
41+ - `src/cli/custom-commands.ts`
42+- **Evidence:** Similar `loadFromDir` patterns (exists/readdir/read/parse/frontmatter/defaults/merge precedence).
43+- **Impact:** Bug fixes and behavior changes must be repeated; inconsistency risk.
44+- **Recommendation:** Create shared loader utility (`loadMarkdownConfigs`) parameterized by layout (`.md file` vs `folder/SKILL.md`), metadata mapping, and precedence rules.
45+
46+### 7) Business logic mixed with presentation concerns
47+- **Smell:** Runtime operations call rendering directly (e.g., tool events, hooks, info/error) instead of emitting structured events.
48+- **Evidence:** `agent.ts` imports many render methods from `cli/output.ts` and calls them inline through control flow.
49+- **Impact:** Strong coupling between core runtime and terminal UI; limits reuse (non-TTY / API mode), harder unit tests.
50+- **Recommendation:** Move to event-driven boundary (domain events -> renderer subscriber), or inject a narrow reporter interface.
51+
52+### 8) Broad `catch {}` swallowing and silent fallbacks
53+- **Smell:** Multiple places ignore errors with empty catches or comments.
54+- **Evidence:** e.g., context file loading in `agent.ts`, cleanup paths in `output.ts`, loader paths in config modules.
55+- **Impact:** Operational issues become invisible; debugging production edge cases is harder.
56+- **Recommendation:** Keep non-fatal behavior but log at debug/trace level (or structured diagnostics) with enough context.
57+
58+### 9) Unsafe JSON parsing without recovery path in message loading
59+- **Smell:** `loadMessages` does `JSON.parse(row.payload)` directly.
60+- **Evidence:** `src/session/db.ts` maps rows with direct parse cast to `CoreMessage`.
61+- **Impact:** Single corrupted row can break session load path.
62+- **Recommendation:** Add guarded parsing with skip/report strategy and optional integrity repair command.
63+
64+### 10) Sync filesystem use in hot-path-ish configuration loading
65+- **Smell:** `existsSync`, `readFileSync`, `readdirSync`, `statSync` widely used in CLI startup/runtime flows.
66+- **Evidence:** `agents.ts`, `skills.ts`, `custom-commands.ts`, and context file loading.
67+- **Impact:** Blocks event loop; usually acceptable at startup but can degrade responsiveness in larger repos/config sets.
68+- **Recommendation:** If responsiveness becomes an issue, move to async FS or memoized cache with invalidation.
69+
70+### 11) Minor test smell: console output in tests
71+- **Smell:** `console.log` in `src/tools/shell.test.ts` for skip notices.
72+- **Impact:** Noisy CI output; not harmful but less clean.
73+- **Recommendation:** Prefer test framework skip metadata or helper wrappers for conditional skips.
74+
75+---
76+
77+## Priority Recommendations
78+1. **High:** Decompose `agent.ts` and `output.ts` (largest maintainability win).
79+2. **High:** Replace destructive DB version reset with real migrations.
80+3. **Medium:** Introduce shared config-loader abstraction to remove duplication.
81+4. **Medium:** Decouple runtime from renderer via event/reporter interface.
82+5. **Medium:** Improve error observability (avoid silent catches).
83+
84+---
85+
86+## Positive Notes
87+- Strong typing overall; very little `any` / ts-ignore usage observed.
88+- Clear module naming and pragmatic structure in many utility files.
89+- Presence of focused unit tests across core tools (`replace`, `insert`, `snapshot`, etc.).