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/// Native OpenRouter LLM client.
137///
138/// Why: trusty-code agents need to invoke LLMs via the OpenRouter API without
139/// depending on third-party Rust SDK crates that pin us to specific provider
140/// contracts. A thin native client gives full control over the wire format,
141/// headers, and error handling.
142/// What: Exports `LlmClient`, `LlmClientConfig`, all request/response types
143/// (`ChatRequest`, `ChatResponse`, `ChatMessage`, `ToolDefinition`, …), and
144/// `LlmError`. The API key is injected at construction time.
145/// Test: `cargo test -p trusty-code` covers serialisation, deserialisation,
146/// and error-mapping unit tests. `--include-ignored` adds the live HTTP test.
147pub mod llm;
148
149/// Agent configuration loading.
150///
151/// Why: Sub-agents are defined declaratively in TOML files under
152/// `.claude/agents/` so model, prompt, and parameters can evolve without code
153/// changes.
154/// What: `AgentConfig`, `AgentInfo`, `LlmParams`, `SystemPrompt`, `ToolsConfig`,
155/// `RunnerConfig`, `RunnerKind`, `discover_agents`, `load_all_agents`.
156/// Test: `agents::tests::*`.
157pub mod agents;
158
159/// Progressive-disclosure skill discovery for `.claude/skills/` (#2069,
160/// vision spec §5.3, Resolved Decision #7).
161///
162/// Why: A skill catalog's full Markdown bodies cost far more tokens than the
163/// PM/agents need up front — most skills in a session are never invoked.
164/// Splitting discovery into cheap, always-cached metadata (name +
165/// description) and an on-demand-loaded body is the token-efficiency layer
166/// P1B wires into `prompt::assemble_system_prompt_for_mode`'s `DailyDriver`
167/// arm.
168/// What: `SkillMetadata`, `locate_skills_dir` (`.claude/skills`, the
169/// Claude-Code-compatible path), `discover_skill_metadata`,
170/// `load_skill_body` (the lazy on-invoke loader), `format_skill_catalog`
171/// (prompt-injection rendering), and `FsSkillResolver` (the concrete
172/// `tools::SkillResolver` impl the `use_skill` tool is built on).
173/// Test: `skills::tests::*`.
174pub mod skills;
175
176/// Harness mode selection: `daily-driver` (default, token-efficiency
177/// consumption point) vs `parity` (full-schema benchmark mode) — #2059,
178/// vision spec §5.9.
179///
180/// Why: reconciles the parity spec's byte-identical-schema requirement with
181/// the production harness's future token-efficiency work by making the
182/// choice an explicit, resolvable, queryable mode rather than picking one
183/// behaviour permanently.
184/// What: `HarnessMode`, `resolve_mode` (the three-tier precedence: env var >
185/// `task.run` param > `.claude/settings.json` > default).
186/// Test: `mode::tests::*`.
187pub mod mode;
188
189/// Caller identity hierarchy for memory scoping.
190///
191/// Why: Memory must be scoped according to who is calling — operator, PM, or
192/// sub-agent — so agents cannot self-elevate their recall scope.
193/// What: `CallerIdentity` enum, `RecallCeiling`, env-var constructors.
194/// Test: `identity::tests::*`.
195pub mod identity;
196
197/// Tracing and logging initialisation.
198///
199/// Why: All binaries need consistent stderr-bound tracing setup; centralising
200/// it prevents duplicated setup across entry points.
201/// What: `init_tracing`, `init_tracing_for_test`, `DEFAULT_LOG_LEVEL`.
202/// Test: `logging::tests::*`.
203pub mod logging;
204
205/// Provider abstraction and per-agent model routing.
206///
207/// Why: Each agent routes to its own model, possibly behind a different backend
208/// (OpenRouter today, AWS Bedrock later). The agent loop depends on the
209/// `Provider` trait rather than branching on the backend, and a factory maps a
210/// model slug to the right implementation.
211/// What: `Provider`, `ToolChoice`, `OpenRouterProvider`, `BedrockProvider`,
212/// `provider_for`, `resolve_model`, `DEFAULT_MODEL`.
213/// Test: `provider::*` submodule tests.
214pub mod provider;
215
216/// Project-context ingestion — load `CLAUDE.md` for prompt injection (#1033).
217///
218/// Why: A Claude-Code-compatible harness must give the PM and every sub-agent
219/// the same project-specific rules a human Claude Code session sees — the
220/// project-root `CLAUDE.md`. This module reads that file, bounds its size so a
221/// runaway file cannot blow the model context budget, and degrades gracefully
222/// when the file is absent.
223/// What: `load_project_context` (root then `.claude/` lookup, size-capped with a
224/// provenance note on truncation) and `MAX_CONTEXT_BYTES`.
225/// Test: `project_context::tests::*`.
226pub mod project_context;
227
228// ── Phase 4 orchestration layer (per #1028) ──
229
230/// Multi-turn agent loop driving an LLM through tool calls to completion.
231///
232/// Why: A task needing file reads, tool runs, and reaction to results cannot be
233/// done in one chat call; the loop is the bounded control structure that calls
234/// the model, dispatches gated tool calls, feeds results back, and iterates.
235/// What: `AgentLoop`, `AgentLoopConfig`, `AgentLoopError`, and `Transcript`. The
236/// loop is bounded by a turn cap and a wall-clock timeout, accrues token usage
237/// via `PerfCollector`, and returns an `AgentOutput`.
238/// Test: `agent_loop::tests::*` (stubbed two-turn flow, turn-cap abort,
239/// recoverable tool error, usage accrual) plus an `#[ignore]`-gated live test.
240pub mod agent_loop;
241
242/// In-process agent runner — the runtime execution layer (per #1029).
243///
244/// Why: The PM's `delegate_to_agent` tool dispatches to an `AgentRunner`; the M1
245/// harness runs the delegated sub-agent *in-process* so a delegation cycle is
246/// cheap, fully observable, and rolls the sub-agent's token usage onto the same
247/// shared LLM client as the PM. This module is the production implementation of
248/// that seam — and `RunnerKind::InProcess` is the real default backend.
249/// What: `InProcessAgentRunner` (implements `tools::AgentRunner`), the
250/// `RegistryFactory` DI seam for sub-agent tool assembly, `InProcessRunnerConfig`
251/// (default turn/timeout budget), `RunnerError`, and `agent_config_exists`. Each
252/// `run` loads the agent config, gates its tools by `tools.allowed`, resolves the
253/// model + assembled system prompt, drives an `AgentLoop`, and returns its output.
254/// Test: `runner::tests::*` (stubbed-PM delegation, return-to-PM output,
255/// `tools.allowed` enforcement, usage roll-up) — all offline.
256pub mod runner;
257
258/// `tcode run-task` end-to-end execution layer (#1034, #1035).
259///
260/// Why: This is the orchestration closer that makes the `tcode` binary run a task
261/// for real — load project context, assemble the PM prompt, run the PM loop, let
262/// it delegate to the engineer in-process, capture the diff + transcript + usage,
263/// and render a human or JSON report with meaningful exit codes. The LLM client is
264/// injected so the whole path is testable offline with a scripted mock.
265/// What: `RunTaskParams`, `execute_run_task`, `RunReport`, `ExitCode`, and the
266/// transcript types (`TurnRecord`, `SharedTranscript`, `RecordingLlmClient`).
267/// Test: `run_task::tests::*` (all offline, mocked LLM).
268pub mod run_task;
269
270/// DOC-28 catch-up context injection for the PM prompt (#1762, PR2).
271///
272/// Why: The PM agent needs recent project-activity context (paused sessions,
273/// git commits, memory palace entries) at task start so it can orient without
274/// interrogating the operator. This module wraps the shared engine in
275/// trusty-common and exposes a single `pm_catchup_context` fn that is wired
276/// into the PM prompt path only (sub-agents receive `None`).
277/// What: `pm_catchup_context(project_dir) -> Option<String>` — async,
278/// fail-open (returns `None` on any error or empty result), never advances the
279/// watermark (advancement is owned by trusty-mpm `session_launch`).
280/// Test: `catchup::tests::pm_catchup_context_does_not_panic_on_empty_repo`.
281pub mod catchup;
282
283/// System-prompt assembly layer implementing the parity spec.
284///
285/// Why: The cross-model comparison harness must assemble the same fixed
286/// instruction surface for every model so the comparison measures the model,
287/// not the scaffolding (`docs/trusty-code/parity-spec.md` §1). This module owns
288/// that surface: the byte-identical BASE preamble, its version token, and the
289/// fixed-order assembler that merges BASE + agent prompt + project `CLAUDE.md`
290/// context + optional per-tier fallback guidance (the #1023 seam).
291/// What: `BASE_PREAMBLE`, `BASE_PREAMBLE_VERSION`, `PromptAssembler`, and
292/// `assemble_system_prompt`.
293/// Test: `prompt::tests::*`.
294pub mod prompt;
295
296// ── Phase 5 daemon transport layer (#2053, M1 control-plane cut line) ──
297
298/// JSON-RPC 2.0 core: wire types (re-exported from `trusty_common::mcp`) plus
299/// the tcode-specific `Router`/`RpcError` extensibility seam.
300///
301/// Why: `tcode serve` must speak the same JSON-RPC-over-STDIO contract as
302/// the rest of the trusty-* family; the `Router` is the new piece that lets
303/// later tickets register `session.*`/`task.*`/`harness.describe` methods
304/// without touching the transport loop.
305/// What: `Request`, `Response`, `error_codes` (re-exported), `RpcError`,
306/// `MethodHandler`, `Router`.
307/// Test: `jsonrpc::error::tests::*`, `jsonrpc::router::tests::*`.
308pub mod jsonrpc;
309
310/// `tcode serve` daemon: STDIO + HTTP JSON-RPC transports + proof-of-life
311/// methods.
312///
313/// Why: the foundation of the M1 control-plane cut line (#2053) — proves the
314/// transport + router work end-to-end via `ping`/`health` before `session.*`
315/// (#2054), `task.*` (#2056), and `harness.describe` (#2066) land on top.
316/// Both transports dispatch through the same `Router`, so the method
317/// surface can never drift between `--stdio` and `--http`.
318/// What: `build_router`, `run_stdio`, `run_http`, `DEFAULT_HTTP_PORT`, and
319/// the `methods`/`transport`/`http` submodules.
320/// Test: `serve::tests::*`, `serve::methods::tests::*`,
321/// `serve::transport::tests::*`, `serve::http::tests::*`.
322pub mod serve;
323
324/// Daemon-owned session model + attach/detach protocol (#2054, Axiom 4).
325///
326/// Why: "The Daemon OWNS Sessions; CLI Attaches Over the API" — sessions
327/// are first-class objects living inside `tcode serve`, reachable via
328/// `session.*` JSON-RPC methods over both transports.
329/// What: `Session`, `SessionStatus`, `SessionRegistry`, and
330/// `session::protocol::register` (wires the seven `session.*` methods onto
331/// a `Router`).
332/// Test: `session::model::tests::*`, `session::registry::registry_tests::*`,
333/// `session::protocol::tests::*`; API-driven end-to-end coverage in
334/// `tests/session_e2e.rs`.
335pub mod session;
336
337/// Daemon-owned task execution: `task.run` + background agent-loop
338/// orchestration (#2056, M1 control-plane cut line).
339///
340/// Why: wires the session/event layer to the existing engine
341/// (`agent_loop`/`runner`/`tools`/`llm`) so a task actually EXECUTES through
342/// the daemon and streams live tool/lifecycle events to attached clients —
343/// the keystone that closes the M1 control-plane cut line.
344/// What: `task.run` JSON-RPC method, background execution orchestration, the
345/// concrete `SessionToolEventSink`, and the offline "echo" mock LLM
346/// (`TCODE_MOCK_LLM=echo`) that makes the whole flow black-box testable
347/// without a live model.
348/// Test: `task::executor::tests::*`, `task::protocol::tests::*`,
349/// `task::sink::tests::*`, `task::mock_llm::tests::*`; API-driven end-to-end
350/// coverage in `tests/task_e2e.rs`.
351pub mod task;
352
353/// Thin JSON-RPC client the `tcode` CLI binary drives against its own
354/// spawned `tcode serve --stdio` child (#2060, vision spec §4.4 "CLI as
355/// Thin Client" / Axiom 3 "API-First").
356///
357/// Why: the CLI must hold no orchestration logic of its own — every
358/// session/task operation goes through the SAME JSON-RPC surface `tcode
359/// serve` exposes, so a human, a script, and a future TUI see identical
360/// behaviour.
361/// What: `cli_client::stdio::StdioRpcClient` (spawn + NDJSON request/
362/// response/notification I/O) and `cli_client::render` (pure formatting for
363/// `session list`/`attach`/`run-task`/`transcript`).
364/// Test: `cli_client::stdio::tests::*`, `cli_client::render::tests::*`;
365/// end-to-end coverage in `tests/cli_e2e.rs`.
366pub mod cli_client;
367
368// ── Package-level re-exports ──
369
370/// Version string, re-exported so integration tests can assert it without
371/// hard-coding the constant.
372///
373/// Why: Single source of truth for the version across CLI and any future API
374/// responses that embed it.
375/// What: The `CARGO_PKG_VERSION` compile-time env var, captured at build time.
376/// Test: `cargo run -p trusty-code -- --version` must print this value.
377pub const VERSION: &str = env!("CARGO_PKG_VERSION");
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382
383 #[test]
384 fn version_is_non_empty() {
385 // Why: guard against accidental blank version strings.
386 // What: asserts that VERSION is not the empty string.
387 // Test: this test itself.
388 assert!(!VERSION.is_empty());
389 }
390}