magi-code 0.101.0

Repository-aware CLI coding agent for terminal work
Documentation
<!-- Generated by generate-agent-docs; preserve verified project-specific guidance when regenerating. -->
# Runtime source agent guide

Parent: [project guide](../AGENTS.md). Paths below are relative to `src/` unless qualified.

## Ownership

`lib.rs` exposes only `run_from_env()` and `run_from_env_with_exit_code()` for CLI startup. All modules and data types are internal. `bin/magi-code.rs` delegates to these entrypoints. Extract implementations behind owning facades; keep export changes explicit.

Subsystem guides: [agent](agent/AGENTS.md), [Code Mode](code_mode/AGENTS.md), [config](config/AGENTS.md), [context](context/AGENTS.md), [local agent](local_agent/AGENTS.md), [MCP](mcp/AGENTS.md), [output](output/AGENTS.md), [providers](providers/AGENTS.md), [sessions](sessions/AGENTS.md), [subagents](subagents/AGENTS.md), [tools](tools/AGENTS.md), [TUI](tui/AGENTS.md).

| Change | Owner |
| --- | --- |
| Launch parsing and validation | `cli.rs`, `cli/validation.rs`; subcommands: `cli/{sessions,mcp}.rs` |
| Shared settings/discovery/MCP startup snapshot | `runtime_context.rs` |
| Pipe protocol, sessions and turns | `local_agent.rs`, `local_agent/` |
| Slash grammar and runtime selection | `commands.rs`, `commands/runtime.rs` |
| Turn provider selection/construction | `agent/runner/preparation.rs`, `providers/factory.rs` |
| Credentials, readiness, runtime resolution, login | `auth.rs`, `auth/{runtime,readiness,codex_oauth,login}.rs`; data: `credentials.rs`; MCP login: `mcp/oauth.rs` |
| Cargo update bounds and restart | `updates.rs`, `updates/`; idle handoff: `tui/controller/app/updates.rs` |
| Title provider work and summary observer/log | `session_titles.rs`, `summarizer.rs`; durable titles: `sessions/`; display: `tui/state/summary.rs` |
| Passive event-summary scheduling/provider work | `progressive_session_maintenance.rs`, `progressive_session_maintenance/generation.rs`; durable batches: `sessions/progressive_summaries.rs` |
| Compaction generation/live snapshots/rotation | `compaction.rs`, `compaction/cached_request.rs`, `sessions/write.rs`; early timing: `agent/compaction_timing.rs` |
| Review snapshots/comments | `diff_review.rs`, `diff_review/`; display: `tui/diff/` |
| Hooks and post-edit diagnostics | `hooks.rs`, `hooks/`; `lsp.rs`, `lsp/` |
| Redaction/display metadata vs semantic lines | `output/` vs `rendering/`; normalization: `output/tool_display/`; shared safe tool meaning: `output/tool_card/` |
| Appearance roles/styles | `appearance.rs`, `appearance/roles.rs` |
| Checkpoint rewind planning/mutation | `checkpoints/rewind.rs`, `checkpoints/rewind/` |
| Runtime and platform-shell spawning | `shell.rs`, `shell/runtime.rs`; bounded stdin: `shell/child_pipe_writer.rs` |
| Protected file access | `persistence.rs` |
| Shared leaf helpers | `support.rs`, `support/`; cancellation: `cancellation.rs` |
| Jev requests/cache/evidence | `typesafe.rs`, `typesafe/evidence.rs`; feature policy: `protection/` and verifier owners |
| Startup/touched-path instructions and skills | `instructions.rs`, `instructions/subdir.rs`, `skills.rs` |
| Offline tool-output reports | `tool_output_measurement.rs`, `tool_output_measurement/{scanner,codecs}.rs` |

## Dependency boundaries

- `provider_ids`, `credentials` and `tool_contract` have no subsystem dependencies. Import provider identity directly from its leaf, not through provider execution.
- `support` and `cancellation` must not import subsystems. Reuse `support/path.rs` for lexical normalization. Shared bash classification, credential-key filtering and stable hashing belong in `support/{bash_mode,security,hash}.rs`; single-caller helpers stay with their caller. Bash classification serves agent/TUI input; credential filtering stays independent of output; hashing serves summary identity and transcript activity-link caches.
- `auth` → `config` for settings; credential data stays in `credentials`, runtime resolution/provider selection in `auth/runtime.rs`. Config uses `provider_ids`, `credentials`, `thinking`, `persistence` and pure validation/default/catalog helpers, never auth or sessions. Its only tools import is `tools::names::canonical_disabled_key`, never `ToolRuntime`.
- Startup prepares config directories, then calls `sessions::prepare_session_root`. `McPaths::ensure_runtime_dirs` does not prepare session permissions.
- Sessions use config/persistence/shared output data, not execution or subagent scheduling. Their tools dependency is dispatch-name equivalence in chat reconciliation only.
- Tools and subagents consume shared result data from `output`; result fields/serde contracts live in `output/{tool_result,subagent_result}.rs`, validation/projection with execution owners. See [output boundaries]output/AGENTS.md.
- Context uses providers only for conversation/request semantics and prompt limits; IDs come from the leaf. Fast policy/observations live in `providers/fast.rs`, exposed through its facade.

Existing mutual dependencies are bounded responsibilities, not permission for unrelated reverse edges:

| Pairs | Retained responsibility |
| --- | --- |
| agent ↔ subagents, compaction, herdr | Child execution, live compaction context, run reporting |
| auth ↔ providers | Provider-specific readiness and credential refresh |
| config ↔ appearance, thinking, model_catalog, providers | Defaults, reasoning protocols and cached limits |
| config ↔ tools, subagents, mcp, typesafe | Narrow name/depth/header/service validation |
| checkpoints, compaction, progressive_session_maintenance ↔ sessions | Rewind/retention, live snapshots and durable maintenance observation |
| code_mode ↔ tools, output; context ↔ providers, output | Guarded execution/display evidence; request budgeting and sanitized projections |
| model_catalog ↔ providers; providers ↔ thinking | Catalog transport/capabilities and reasoning protocols |
| mcp, providers, subagents ↔ tools | Schemas, advertisement/search and child policy |
| output ↔ providers, protection, tools | Fast observations, protected replay, capability/patch presentation |
| sessions ↔ tools | Saved-call dispatch-name equivalence only |

## Runtime contracts

- Keep title-provider work outside storage and durable/security-sensitive behavior outside display. Compaction uses its selected provider without a Jev summary check; optional Jev timing only decides whether to compact early.
- Cache-preserving compaction captures settled live requests in `Session` memory. Match provider/model and history fingerprint; preserve instructions/tools and append summary instructions. Never dispatch summary tools. Fallback stays tool-free, cancellation stops both paths, and each provider attempt owns separate usage accounting.
- `persistence::open_regular_file` and `read_regular_file_bounded` reject final symlinks and Unix FIFOs through held handles. Callers own parent containment and byte bounds; lock renewal verifies ownership and updates time through the same handle.
- CLI routing must not recreate provider/auth/tool/session policy. `AppError::Usage` exits 2; `AppError::Runtime` exits 1. Clap owns parsing, `cli/validation.rs` cross-mode checks before side effects, config override precedence.
- `serve --stdio` routes before terminal setup. `--update` runs standalone before TTY/config/provider/session setup. TUI passes restart data only; update/restart runs after terminal cleanup, app drop, writer-lease release and Herdr release.
- `parse_slash_command` separates empty input, prompts, built-ins and unknown slash commands. Keep grammar/names/help in registry entries, not callers.
- `/settings` drafts belong in `tui/settings_editor.rs`; writes in `config/settings/editor.rs`. Model availability belongs in Settings → Models; keep retired `/models` out of help/autocomplete. `/model` selects cached models without refresh.
- Logout distinguishes removed credentials from absent entries. Command status is local, never provider conversation content.

## Hooks, diagnostics, rendering and shell

- Hook phases: `before_tool`, `after_tool`, `after_assistant`, `after_reasoning`. Policies ignore/warn/block/fail; block applies only before tools. Preserve `target_ran` on post-target failures.
- Inject hook stdout only as parsed, byte-bounded, user-role `context_items`. Use tool cwd preflight/shared shell spawning; hooks own bounded pipes/cleanup. Payload refs stay under canonical session root with protected permissions; retain path count/length bounds and write-symlink rejection. Redact hook/injected-context records before storage.
- LSP uses Content-Length framing, not MCP newline JSON. Keep waits/cancellation in blocking workers and release children on shutdown. Versioned diagnostics must meet requested version; unversioned diagnostics must follow synchronization start. Preserve count/byte/redaction limits, idle shutdown and repeated-failure disabling. Unavailable is not clean; diagnostics never widen editing access.
- `rendering/` returns `DisplayLine`/`DisplaySpan` with `DisplayRole`, not colors. Callers own layout/limits/redaction/wrapping. Syntax loads lazily with `OnceLock`; highlight at most 400 lines / 64 KiB with fallback roles. Diff headers precede added/removed classification; rendering never applies patches.
- `ShellState` is runtime state, not a REPL. `spawn_platform_shell` creates piped output and a Unix process group; callers enforce cwd/limits/timeout/cancellation/cleanup. `ShellEnvPolicy::Sanitized` skips startup profiles.
- MCP/LSP share `ChildPipeWriter`: nonblocking stdin, serialized writes and deadline/cancellation checks. Reuse request deadlines; add no writer threads/queues.

## Instruction and skill discovery

- Startup order: user `AGENTS.md`, explicit project-root `AGENTS.md`, configured Markdown paths in listed order. No ancestor scan or automatic `CLAUDE.md`. Configured paths are absolute `.md` files; retain indexed setting errors.
- Startup caps: 256 KiB/file, 1 MiB combined. Ignore missing optional guides; propagate other startup read failures.
- Touched-path guides load nearest-first, excluding root/already-loaded canonical paths. Allow in-root links only to in-root targets; skill/profile symlink policy differs. Cap local guides at 256 KiB; return diagnostics alongside text. Discovery executes nothing and writes no memory files.
- Skill priority: repository `.agents/skills` > configured absolute roots (later wins) > `$MC_HOME/skills` > legacy `~/.agents/skills`. Discover `SKILL.md` directly in skill directories or one grouping level below; directory names are IDs.
- Reject non-regular/symlinked descriptors and symlink traversal. Cap descriptors at 1 MiB; failures are per-path diagnostics, output deterministic `BTreeMap` order. Frontmatter is flat key/value, not YAML; preserve CRLF, quoting and malformed-marker diagnostics.
- Disabled-name filtering is not opt-in discovery and never relaxes reference containment. Read skill/reference bodies through `tools/skill.rs`.

## Offline measurement and profiling

- Scan active primary and direct subagent sessions only, relative to held directory handles without following symlinks. Preserve open/scan signatures; newest modification time then path selects within file/byte/line limits.
- Require valid identity/success and exactly one text field (`content` or legacy `output`). Compare within the same Codex Responses-style item; local token estimates are not billing.
- JSON minification removes whitespace outside strings without reserialization. Select only a unique smaller candidate; helpers are neither public API nor live compression.
- `profiling/profile_harness/` separates find/content/CPU/render workloads; mixed/scroll reuse render helpers. No profiling CI or correctness suite.
- Hooks live in `profiling`/`profiling_support` children. Any `#[cfg(test)]` production struct field or hot-path block must name its consuming workload in a comment.