trusty_code/lib.rs
1//! trusty-code — per-project Claude-Code-compatible MPM orchestration harness.
2//!
3//! # Why
4//!
5//! Each Claude-Code project needs a harness that is *already* wired to its
6//! own `.claude` configuration: agents, skills, MCP connections, CLAUDE.md,
7//! and permissions. `trusty-code` fills that role as an original, purpose-built
8//! coding harness. It is the Claude-Code-native orchestration entry point —
9//! driven by API, CLI, or TUI — that runs the PM main-loop, enforces the
10//! mandatory workflow, and delegates authority to typed sub-agents according to
11//! MPM protocols. Its non-coding sibling, trusty-agents, is a
12//! separately-installable general-purpose orchestration platform for
13//! personal-productivity workflows; the two share architectural DNA but
14//! trusty-code is not extracted from it. Tracked under epic #2052.
15//!
16//! # Design constraints
17//!
18//! * **Claude-Code compatible** — reads `.claude/` config, agents, skills, MCP
19//! descriptors, `CLAUDE.md`, and permission grants exactly as Claude Code does.
20//! * **API / CLI / TUI driven** — no hooks support (hooks are a Claude Code
21//! shell-level feature; `tcode` operates above that layer via its event bus).
22//! * **Per-agent model routing** — each agent may specify its own model,
23//! independently choosing between AWS Bedrock models and OpenRouter models.
24//! * **Single-instance per project** — one `tcode serve` process per `.claude/`
25//! root; multiple CLI or TUI clients may attach to it.
26//! * **No `unwrap()` in library code** — all fallible paths use `?` with
27//! `thiserror`-derived error types (once errors exist to derive); application
28//! entry points use `anyhow::Result`.
29//!
30//! # What
31//!
32//! Phase 1 public surface (leaf/protocol modules, per #640):
33//!
34//! * [`events`] — process-global broadcast event bus.
35//! * [`ipc`] — NDJSON IPC protocol for PM ↔ sub-agent communication.
36//! * [`perf`] — per-phase latency + token/cost instrumentation.
37//! * [`intent`] — pure-Rust heuristic intent classifier.
38//! * [`progress`] — real-time phase progress reporter.
39//! * [`build_info`] — monotonic build counter + version banner.
40//!
41//! Phase 2 public surface (tools layer, per #641):
42//!
43//! * [`tools`] — `ToolExecutor` / `AgentRunner` / `SearchProvider` traits,
44//! `ToolRegistry` dispatcher, `DelegateToAgentTool`, `ToolResult`.
45//! * [`rbac`] — `ServiceTier`, `UserIdentity`, access-control helpers.
46//!
47//! Phase 3 public surface (agents + LLM layer, per #642):
48//!
49//! * [`agents`] — `AgentConfig` TOML schema, `discover_agents`, `load_all_agents`.
50//! * [`identity`] — `CallerIdentity`, `RecallCeiling` for memory scoping.
51//! * [`logging`] — tracing init helpers (`init_tracing`, `init_tracing_for_test`).
52//!
53//! # Test
54//!
55//! `cargo test -p trusty-code` — all modules carry their own unit tests.
56
57// ── Phase 1 leaf/protocol modules (per #640) ──
58
59/// Process-wide broadcast event bus for real-time UI streaming.
60///
61/// Why: Centralises telemetry emission so any code path can publish events
62/// without threading a sender through dozens of call sites.
63/// What: `Event` enum, `publish`/`subscribe`/`emit` helpers, the
64/// `EVENT_LINE_PREFIX` constant for subprocess relay.
65/// Test: `events::tests::publish_round_trips_through_subscribe`.
66pub mod events;
67
68/// NDJSON IPC protocol for PM ↔ sub-agent communication.
69///
70/// Why: Provides a framing-safe wire protocol over stdin/stdout pipes so the
71/// PM and sub-agent subprocesses exchange structured messages without ambiguity.
72/// What: `IpcMessage` enum (Task/Result/Error), `HistoryMessage` wire type,
73/// `serialize_message`/`parse_message` helpers.
74/// Test: `ipc::tests::*` round-trips every variant.
75pub mod ipc;
76
77/// Per-phase latency + token/cost instrumentation.
78///
79/// Why: Tracks how long each workflow phase takes, how many tokens it consumed,
80/// and the resulting USD cost so runs can be compared build-over-build.
81/// What: `TokenUsage`, `PhaseRecord`, `PerfRecord`, `PerfTotals`,
82/// `PerfCollector`, `cost_usd`.
83/// Test: `perf::tests::*`.
84pub mod perf;
85
86/// Pure-Rust heuristic intent classifier for PM fast-pathing.
87///
88/// Why: Avoids routing trivial conversational inputs through the full
89/// subprocess pipeline.
90/// What: `IntentClass` enum, `classify_intent` function.
91/// Test: `intent::classifier_tests::*`.
92pub mod intent;
93
94/// Real-time phase progress reporter to stderr.
95///
96/// Why: Workflow runs take 20–70 minutes; users need live feedback without
97/// polluting stdout.
98/// What: `ProgressReporter` struct with phase/wave lifecycle hooks and
99/// `format_duration` helper.
100/// Test: `progress::tests::*`.
101pub mod progress;
102
103/// Build and version tracking.
104///
105/// Why: A monotonic build counter pairs with semver for log correlation.
106/// What: `BuildInfo` struct, `VERSION`/`GIT_HASH`/`PKG_NAME` constants,
107/// `version_string` helper.
108/// Test: `build_info::tests::*`.
109pub mod build_info;
110
111// ── Phase 2 tools layer (per #641) ──
112
113/// Tool system: traits, registry, and the delegate tool.
114///
115/// Why: The PM loop needs a polymorphic tool dispatch layer so new capabilities
116/// plug in without touching orchestration code.
117/// What: `ToolExecutor`, `AgentRunner`, `RunContext`, `AgentOutput`,
118/// `SearchProvider`, `SkillResolver`, `ToolResult`, `ToolRegistry`,
119/// `DelegateToAgentTool`, `UseSkillTool` (#2069's progressive-disclosure
120/// on-invoke skill-body loader).
121/// Test: `tools::traits::tests::*`, `tools::registry::tests::*`,
122/// `tools::delegate::tests::*`, `tools::skill::tests::*`.
123pub mod tools;
124
125/// Role-based access control for tool execution.
126///
127/// Why: tcode exposes tools over multiple surfaces; RBAC gates execution on a
128/// stable tier ladder without per-deployment code branches.
129/// What: `ServiceTier`, `UserIdentity`, `filter_tools_for_user`,
130/// `can_access_tier`.
131/// Test: `rbac::tests::*`.
132pub mod rbac;
133
134// ── Phase 3 agents + LLM layer (per #642) ──
135
136/// LLM transports for trusty-code.
137///
138/// Why: trusty-code agents invoke LLMs via OpenAI-compatible endpoints
139/// (OpenRouter / Fireworks) and AWS Bedrock. Since #2406 (epic #2400) the
140/// OpenAI-compatible HTTP mechanics live in the shared `trusty_common::inference`
141/// adapter layer rather than a bespoke tcode client, so credential resolution,
142/// error classification, and the wire schema are shared across the ecosystem.
143/// What: Exports `OpenAiCompatClient` (shared OpenRouter/Fireworks transport),
144/// `DispatchingLlmClient` (slug-routed transport), `BedrockChatClient`, all
145/// request/response types (`ChatRequest`, `ChatResponse`, `ChatMessage`,
146/// `ToolDefinition`, …), and `LlmError`. Credentials resolve via the shared
147/// 3-tier chain (env > `.env.local` > secure store) at first use.
148/// Test: `cargo test -p trusty-code` covers serialisation, deserialisation,
149/// type-conversion, and error-mapping unit tests plus the offline black-box
150/// e2e (`tests/inference_shared_adapter_e2e.rs`). `--include-ignored` adds the
151/// live provider tests.
152pub mod llm;
153
154/// Agent configuration loading.
155///
156/// Why: Sub-agents are defined declaratively in TOML files under
157/// `.claude/agents/` so model, prompt, and parameters can evolve without code
158/// changes.
159/// What: `AgentConfig`, `AgentInfo`, `LlmParams`, `SystemPrompt`, `ToolsConfig`,
160/// `RunnerConfig`, `RunnerKind`, `discover_agents`, `load_all_agents`.
161/// Test: `agents::tests::*`.
162pub mod agents;
163
164/// Progressive-disclosure skill discovery for `.claude/skills/` (#2069,
165/// vision spec §5.3, Resolved Decision #7).
166///
167/// Why: A skill catalog's full Markdown bodies cost far more tokens than the
168/// PM/agents need up front — most skills in a session are never invoked.
169/// Splitting discovery into cheap, always-cached metadata (name +
170/// description) and an on-demand-loaded body is the token-efficiency layer
171/// P1B wires into `prompt::assemble_system_prompt_for_mode`'s `DailyDriver`
172/// arm.
173/// What: `SkillMetadata`, `locate_skills_dir` (`.claude/skills`, the
174/// Claude-Code-compatible path), `discover_skill_metadata`,
175/// `load_skill_body` (the lazy on-invoke loader), `format_skill_catalog`
176/// (prompt-injection rendering), and `FsSkillResolver` (the concrete
177/// `tools::SkillResolver` impl the `use_skill` tool is built on).
178/// Test: `skills::tests::*`.
179pub mod skills;
180
181/// Harness mode selection: `daily-driver` (default, token-efficiency
182/// consumption point) vs `parity` (full-schema benchmark mode) — #2059,
183/// vision spec §5.9.
184///
185/// Why: reconciles the parity spec's byte-identical-schema requirement with
186/// the production harness's future token-efficiency work by making the
187/// choice an explicit, resolvable, queryable mode rather than picking one
188/// behaviour permanently.
189/// What: `HarnessMode`, `resolve_mode` (the three-tier precedence: env var >
190/// `task.run` param > `.claude/settings.json` > default).
191/// Test: `mode::tests::*`.
192pub mod mode;
193
194/// Caller identity hierarchy for memory scoping.
195///
196/// Why: Memory must be scoped according to who is calling — operator, PM, or
197/// sub-agent — so agents cannot self-elevate their recall scope.
198/// What: `CallerIdentity` enum, `RecallCeiling`, env-var constructors.
199/// Test: `identity::tests::*`.
200pub mod identity;
201
202/// Tracing and logging initialisation.
203///
204/// Why: All binaries need consistent stderr-bound tracing setup; centralising
205/// it prevents duplicated setup across entry points.
206/// What: `init_tracing`, `init_tracing_for_test`, `DEFAULT_LOG_LEVEL`.
207/// Test: `logging::tests::*`.
208pub mod logging;
209
210/// Provider abstraction and per-agent model routing.
211///
212/// Why: Each agent routes to its own model, possibly behind a different backend
213/// (OpenRouter today, AWS Bedrock later). The agent loop depends on the
214/// `Provider` trait rather than branching on the backend, and a factory maps a
215/// model slug to the right implementation.
216/// What: `Provider`, `ToolChoice`, `OpenRouterProvider`, `BedrockProvider`,
217/// `provider_for`, `resolve_model`, `DEFAULT_MODEL`.
218/// Test: `provider::*` submodule tests.
219pub mod provider;
220
221/// Project-context ingestion — load `CLAUDE.md` for prompt injection (#1033).
222///
223/// Why: A Claude-Code-compatible harness must give the PM and every sub-agent
224/// the same project-specific rules a human Claude Code session sees — the
225/// project-root `CLAUDE.md`. This module reads that file, bounds its size so a
226/// runaway file cannot blow the model context budget, and degrades gracefully
227/// when the file is absent.
228/// What: `load_project_context` (root then `.claude/` lookup, size-capped with a
229/// provenance note on truncation) and `MAX_CONTEXT_BYTES`.
230/// Test: `project_context::tests::*`.
231pub mod project_context;
232
233// ── Phase 4 orchestration layer (per #1028) ──
234
235/// Multi-turn agent loop driving an LLM through tool calls to completion.
236///
237/// Why: A task needing file reads, tool runs, and reaction to results cannot be
238/// done in one chat call; the loop is the bounded control structure that calls
239/// the model, dispatches gated tool calls, feeds results back, and iterates.
240/// What: `AgentLoop`, `AgentLoopConfig`, `AgentLoopError`, and `Transcript`. The
241/// loop is bounded by a turn cap and a wall-clock timeout, accrues token usage
242/// via `PerfCollector`, and returns an `AgentOutput`.
243/// Test: `agent_loop::tests::*` (stubbed two-turn flow, turn-cap abort,
244/// recoverable tool error, usage accrual) plus an `#[ignore]`-gated live test.
245pub mod agent_loop;
246
247/// In-process agent runner — the runtime execution layer (per #1029).
248///
249/// Why: The PM's `delegate_to_agent` tool dispatches to an `AgentRunner`; the M1
250/// harness runs the delegated sub-agent *in-process* so a delegation cycle is
251/// cheap, fully observable, and rolls the sub-agent's token usage onto the same
252/// shared LLM client as the PM. This module is the production implementation of
253/// that seam — and `RunnerKind::InProcess` is the real default backend.
254/// What: `InProcessAgentRunner` (implements `tools::AgentRunner`), the
255/// `RegistryFactory` DI seam for sub-agent tool assembly, `InProcessRunnerConfig`
256/// (default turn/timeout budget), `RunnerError`, and `agent_config_exists`. Each
257/// `run` loads the agent config, gates its tools by `tools.allowed`, resolves the
258/// model + assembled system prompt, drives an `AgentLoop`, and returns its output.
259/// Test: `runner::tests::*` (stubbed-PM delegation, return-to-PM output,
260/// `tools.allowed` enforcement, usage roll-up) — all offline.
261pub mod runner;
262
263/// `tcode run-task` end-to-end execution layer (#1034, #1035).
264///
265/// Why: This is the orchestration closer that makes the `tcode` binary run a task
266/// for real — load project context, assemble the PM prompt, run the PM loop, let
267/// it delegate to the engineer in-process, capture the diff + transcript + usage,
268/// and render a human or JSON report with meaningful exit codes. The LLM client is
269/// injected so the whole path is testable offline with a scripted mock.
270/// What: `RunTaskParams`, `execute_run_task`, `RunReport`, `ExitCode`, and the
271/// transcript types (`TurnRecord`, `SharedTranscript`, `RecordingLlmClient`).
272/// Test: `run_task::tests::*` (all offline, mocked LLM).
273pub mod run_task;
274
275/// Verify-before-finish gate (#2279): rejects a premature `finish_task` with
276/// a recoverable retry when a named test command was never run.
277///
278/// Why: (bake-off L2 diagnosis) An engineer that never runs the visible,
279/// prompt-named test suite can still call `finish_task` successfully today;
280/// this module gives both the delegated engineer's loop and the delegating
281/// PM's loop a turn-boundary hook to reject that specific case.
282/// What: [`agent_loop::FinishGate`] constructors `default_finish_gate` (own
283/// transcript) and `pm_finish_gate` (externally shared engineer transcript),
284/// plus the pure `names_test_command`/`is_test_command` regex predicates
285/// they share.
286/// Test: `verify_gate::tests::*`.
287pub mod verify_gate;
288
289/// Redundant full-suite test re-run suppression (#2682): the complement to
290/// [`verify_gate`] — it stops the suite running MORE than it needs to.
291///
292/// Why: (bake-off L1 diagnosis) The engineer re-runs the full suite 7-14x per
293/// run as repeated "one final run to confirm" passes, even when no code has
294/// changed since the last clean pass, inflating tcode's turn count far above
295/// claude-code's on the same challenge.
296/// What: The pure `is_redundant_test_rerun` predicate the agent loop consults
297/// (when suppression is enabled) to short-circuit a redundant test re-run with
298/// [`redundant_run::REDUNDANT_RERUN_MESSAGE`] instead of spawning the suite.
299/// Test: `redundant_run::tests::*`.
300pub mod redundant_run;
301
302/// DOC-28 catch-up context injection for the PM prompt (#1762, PR2).
303///
304/// Why: The PM agent needs recent project-activity context (paused sessions,
305/// git commits, memory palace entries) at task start so it can orient without
306/// interrogating the operator. This module wraps the shared engine in
307/// trusty-common and exposes a single `pm_catchup_context` fn that is wired
308/// into the PM prompt path only (sub-agents receive `None`).
309/// What: `pm_catchup_context(project_dir) -> Option<String>` — async,
310/// fail-open (returns `None` on any error or empty result), never advances the
311/// watermark (advancement is owned by trusty-mpm `session_launch`).
312/// Test: `catchup::tests::pm_catchup_context_does_not_panic_on_empty_repo`.
313pub mod catchup;
314
315/// Shared trusty-memory `tools/call` envelope helpers (#2424).
316///
317/// Why: trusty-memory direct-dispatches only its `TOOL_METHODS` allowlist —
318/// every `chat_*` tool is reachable ONLY via the MCP `tools/call` envelope,
319/// which the #2343 soak found the turn recorder was not using (100% of
320/// durable writes failed `-32601`). One shared implementation of the
321/// envelope build/unwrap keeps the write side (`session::memory_sink`) and
322/// the read side (`tools::recall_session`) on the same verified shape.
323/// What: `tools_call_params`, `parse_tools_call_envelope`,
324/// `call_tool_wrapped`.
325/// Test: `memory_envelope::tests::*`.
326pub mod memory_envelope;
327
328/// System-prompt assembly layer implementing the parity spec.
329///
330/// Why: The cross-model comparison harness must assemble the same fixed
331/// instruction surface for every model so the comparison measures the model,
332/// not the scaffolding (`docs/trusty-code/parity-spec.md` §1). This module owns
333/// that surface: the byte-identical BASE preamble, its version token, and the
334/// fixed-order assembler that merges BASE + agent prompt + project `CLAUDE.md`
335/// context + optional per-tier fallback guidance (the #1023 seam).
336/// What: `BASE_PREAMBLE`, `BASE_PREAMBLE_VERSION`, `PromptAssembler`, and
337/// `assemble_system_prompt`.
338/// Test: `prompt::tests::*`.
339pub mod prompt;
340
341// ── Phase 5 daemon transport layer (#2053, M1 control-plane cut line) ──
342
343/// JSON-RPC 2.0 core: wire types (re-exported from `trusty_common::mcp`) plus
344/// the tcode-specific `Router`/`RpcError` extensibility seam.
345///
346/// Why: `tcode serve` must speak the same JSON-RPC-over-STDIO contract as
347/// the rest of the trusty-* family; the `Router` is the new piece that lets
348/// later tickets register `session.*`/`task.*`/`harness.describe` methods
349/// without touching the transport loop.
350/// What: `Request`, `Response`, `error_codes` (re-exported), `RpcError`,
351/// `MethodHandler`, `Router`.
352/// Test: `jsonrpc::error::tests::*`, `jsonrpc::router::tests::*`.
353pub mod jsonrpc;
354
355/// `tcode serve` daemon: STDIO + HTTP JSON-RPC transports + proof-of-life
356/// methods.
357///
358/// Why: the foundation of the M1 control-plane cut line (#2053) — proves the
359/// transport + router work end-to-end via `ping`/`health` before `session.*`
360/// (#2054), `task.*` (#2056), and `harness.describe` (#2066) land on top.
361/// Both transports dispatch through the same `Router`, so the method
362/// surface can never drift between `--stdio` and `--http`.
363/// What: `build_router`, `run_stdio`, `run_http`, `DEFAULT_HTTP_PORT`, and
364/// the `methods`/`transport`/`http` submodules.
365/// Test: `serve::tests::*`, `serve::methods::tests::*`,
366/// `serve::transport::tests::*`, `serve::http::tests::*`.
367pub mod serve;
368
369/// Daemon-owned session model + attach/detach protocol (#2054, Axiom 4).
370///
371/// Why: "The Daemon OWNS Sessions; CLI Attaches Over the API" — sessions
372/// are first-class objects living inside `tcode serve`, reachable via
373/// `session.*` JSON-RPC methods over both transports.
374/// What: `Session`, `SessionStatus`, `SessionRegistry`, and
375/// `session::protocol::register` (wires the seven `session.*` methods onto
376/// a `Router`).
377/// Test: `session::model::tests::*`, `session::registry::registry_tests::*`,
378/// `session::protocol::tests::*`; API-driven end-to-end coverage in
379/// `tests/session_e2e.rs`.
380pub mod session;
381
382/// Daemon-owned task execution: `task.run` + background agent-loop
383/// orchestration (#2056, M1 control-plane cut line).
384///
385/// Why: wires the session/event layer to the existing engine
386/// (`agent_loop`/`runner`/`tools`/`llm`) so a task actually EXECUTES through
387/// the daemon and streams live tool/lifecycle events to attached clients —
388/// the keystone that closes the M1 control-plane cut line.
389/// What: `task.run` JSON-RPC method, background execution orchestration, the
390/// concrete `SessionToolEventSink`, and the offline "echo" mock LLM
391/// (`TCODE_MOCK_LLM=echo`) that makes the whole flow black-box testable
392/// without a live model.
393/// Test: `task::executor::tests::*`, `task::protocol::tests::*`,
394/// `task::sink::tests::*`, `task::mock_llm::tests::*`; API-driven end-to-end
395/// coverage in `tests/task_e2e.rs`.
396pub mod task;
397
398/// Thin JSON-RPC client the `tcode` CLI binary drives against its own
399/// spawned `tcode serve --stdio` child (#2060, vision spec §4.4 "CLI as
400/// Thin Client" / Axiom 3 "API-First").
401///
402/// Why: the CLI must hold no orchestration logic of its own — every
403/// session/task operation goes through the SAME JSON-RPC surface `tcode
404/// serve` exposes, so a human, a script, and a future TUI see identical
405/// behaviour.
406/// What: `cli_client::stdio::StdioRpcClient` (spawn + NDJSON request/
407/// response/notification I/O) and `cli_client::render` (pure formatting for
408/// `session list`/`attach`/`run-task`/`transcript`).
409/// Test: `cli_client::stdio::tests::*`, `cli_client::render::tests::*`;
410/// end-to-end coverage in `tests/cli_e2e.rs`.
411pub mod cli_client;
412
413// ── Package-level re-exports ──
414
415/// Version string, re-exported so integration tests can assert it without
416/// hard-coding the constant.
417///
418/// Why: Single source of truth for the version across CLI and any future API
419/// responses that embed it.
420/// What: The `CARGO_PKG_VERSION` compile-time env var, captured at build time.
421/// Test: `cargo run -p trusty-code -- --version` must print this value.
422pub const VERSION: &str = env!("CARGO_PKG_VERSION");
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427
428 #[test]
429 fn version_is_non_empty() {
430 // Why: guard against accidental blank version strings.
431 // What: asserts that VERSION is not the empty string.
432 // Test: this test itself.
433 assert!(!VERSION.is_empty());
434 }
435}