Skip to main content

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` schema (loaded from `.md`), `discover_agents`,
50//!   `load_all_agents`.
51//! * [`identity`] — `CallerIdentity`, `RecallCeiling` for memory scoping.
52//! * [`logging`] — tracing init helpers (`init_tracing`, `init_tracing_for_test`).
53//!
54//! # Test
55//!
56//! `cargo test -p trusty-code` — all modules carry their own unit tests.
57
58// docs.rs builds a release's documentation once, from the uploaded tarball,
59// so a broken intra-doc link is baked into that version forever and only a new
60// release can correct it. Deny keeps this crate at zero rather than letting the
61// ratchet in `scripts/check_rustdoc_links.sh` absorb a new one.
62#![deny(rustdoc::broken_intra_doc_links)]
63
64// ── Phase 1 leaf/protocol modules (per #640) ──
65
66/// Process-wide broadcast event bus for real-time UI streaming.
67///
68/// Why: Centralises telemetry emission so any code path can publish events
69/// without threading a sender through dozens of call sites.
70/// What: `Event` enum, `publish`/`subscribe`/`emit` helpers, the
71/// `EVENT_LINE_PREFIX` constant for subprocess relay.
72/// Test: `events::tests::publish_round_trips_through_subscribe`.
73pub mod events;
74
75/// NDJSON IPC protocol for PM ↔ sub-agent communication.
76///
77/// Why: Provides a framing-safe wire protocol over stdin/stdout pipes so the
78/// PM and sub-agent subprocesses exchange structured messages without ambiguity.
79/// What: `IpcMessage` enum (Task/Result/Error), `HistoryMessage` wire type,
80/// `serialize_message`/`parse_message` helpers.
81/// Test: `ipc::tests::*` round-trips every variant.
82pub mod ipc;
83
84/// Per-phase latency + token/cost instrumentation.
85///
86/// Why: Tracks how long each workflow phase takes, how many tokens it consumed,
87/// and the resulting USD cost so runs can be compared build-over-build.
88/// What: `TokenUsage`, `PhaseRecord`, `PerfRecord`, `PerfTotals`,
89/// `PerfCollector`, `cost_usd`.
90/// Test: `perf::tests::*`.
91pub mod perf;
92
93/// Pure-Rust heuristic intent classifier for PM fast-pathing.
94///
95/// Why: Avoids routing trivial conversational inputs through the full
96/// subprocess pipeline.
97/// What: `IntentClass` enum, `classify_intent` function.
98/// Test: `intent::classifier_tests::*`.
99pub mod intent;
100
101/// Real-time phase progress reporter to stderr.
102///
103/// Why: Workflow runs take 20–70 minutes; users need live feedback without
104/// polluting stdout.
105/// What: `ProgressReporter` struct with phase/wave lifecycle hooks and
106/// `format_duration` helper.
107/// Test: `progress::tests::*`.
108pub mod progress;
109
110/// Build and version tracking.
111///
112/// Why: A monotonic build counter pairs with semver for log correlation.
113/// What: `BuildInfo` struct, `VERSION`/`GIT_HASH`/`PKG_NAME` constants,
114/// `version_string` helper.
115/// Test: `build_info::tests::*`.
116pub mod build_info;
117
118// ── Phase 2 tools layer (per #641) ──
119
120/// Tool system: traits, registry, and the delegate tool.
121///
122/// Why: The PM loop needs a polymorphic tool dispatch layer so new capabilities
123/// plug in without touching orchestration code.
124/// What: `ToolExecutor`, `AgentRunner`, `RunContext`, `AgentOutput`,
125/// `SearchProvider`, `SkillResolver`, `ToolResult`, `ToolRegistry`,
126/// `DelegateToAgentTool`, `UseSkillTool` (#2069's progressive-disclosure
127/// on-invoke skill-body loader).
128/// Test: `tools::traits::tests::*`, `tools::registry::tests::*`,
129/// `tools::delegate::tests::*`, `tools::skill::tests::*`.
130pub mod tools;
131
132/// Role-based access control for tool execution.
133///
134/// Why: tcode exposes tools over multiple surfaces; RBAC gates execution on a
135/// stable tier ladder without per-deployment code branches.
136/// What: `ServiceTier`, `UserIdentity`, `filter_tools_for_user`,
137/// `can_access_tier`.
138/// Test: `rbac::tests::*`.
139pub mod rbac;
140
141// ── Phase 3 agents + LLM layer (per #642) ──
142
143/// LLM transports for trusty-code.
144///
145/// Why: trusty-code agents invoke LLMs via OpenAI-compatible endpoints
146/// (OpenRouter / Fireworks) and AWS Bedrock. Since #2406 (epic #2400) the
147/// OpenAI-compatible HTTP mechanics live in the shared `trusty_common::inference`
148/// adapter layer rather than a bespoke tcode client; since #4425 (epic #4429)
149/// so does the ABSTRACTION — trusty-code defines no chat/provider trait of its
150/// own, it implements and consumes `trusty_common::inference::InferenceAdapter`.
151/// That is what gave trusty-code streaming: the shared trait's `chat_stream`
152/// already carried native SSE, which the deleted local trait had no method for.
153/// What: Exports `OpenAiCompatClient` (shared OpenRouter/Fireworks/Together/
154/// AtlasCloud transport), `DispatchingLlmClient` (slug-routed transport),
155/// `BedrockChatClient`, the trusty-code-local response views (`token_usage`,
156/// `finish_reason`, `resolved_model`), and RE-EXPORTS of the shared trait,
157/// error, and wire types (`InferenceAdapter`, `InferenceError`, `ChatRequest`,
158/// `ChatResponse`, `ChatMessage`, `ToolDefinition`, …) so `crate::llm::…` paths
159/// keep resolving. Credentials resolve via the shared 3-tier chain (env >
160/// `.env.local` > secure store) at first use.
161/// Test: `cargo test -p trusty-code` covers transport routing, the streaming
162/// decorators, and the local response views, plus the offline black-box e2e
163/// (`tests/inference_shared_adapter_e2e.rs`). `--include-ignored` adds the
164/// live provider tests.
165pub mod llm;
166
167/// Embedded default agents & skills (#2895; roster expanded to 31 agents in
168/// Slice E3, #2958; `pm` added as a 4th tcode-own default for #3437).
169///
170/// Why: A fresh project has no `.claude/agents/` or `.claude/skills/` yet;
171/// bundling a working default set at compile time (mirroring, not sharing,
172/// `trusty-mpm`'s embed pattern) gives every project a usable harness before
173/// any project-level config exists. Disk-based config always wins when present.
174/// What: `EmbeddedAgent`/`DEFAULT_AGENTS` (32 dispatchable tcode agents: the
175/// original 4 (`engineer`/`qa-agent`/`code-reviewer`/`pm`), authored as
176/// Markdown+frontmatter as of #2897 Slice C, plus 28 coding-relevant tm
177/// agents wired in as of Slice E, #2958, whose shared texts are read from
178/// instructional content since #9011);
179/// `EmbeddedSkill`/`DEFAULT_SKILLS` (trusty-mpm's universal skill set, minus
180/// the `tm-*` orchestration skills).
181/// Test: `assets::tests::*`.
182pub mod assets;
183
184/// Trusty Code's own configuration and state layout (#5426, epic #2892).
185///
186/// Why: every discovery site used to join the literal `.claude/` itself, which
187/// made another product's directory the source of truth for this one and left
188/// nothing stopping a write INTO it. #5426 makes `<project>/.trusty-code/` the
189/// read-preferred and write-only location, with `.claude/` (and `.open-mpm/`)
190/// demoted to compatibility inputs.
191/// What: `resolve_project_entry` (the one precedence rule: `.trusty-code` →
192/// `.claude` → `.open-mpm`, then a native default) plus the per-entry
193/// `agents_dir`/`skills_dir`/`plugins_dir`/`settings_file` wrappers;
194/// `native_config_dir`/`check_native_write_target` (the write boundary, symlink
195/// escapes included); `private_state` (`~/.trusty-code/`, mode `0700`); and
196/// `import` (the deterministic, non-overwriting `.claude/` import).
197/// Test: `paths::tests::*`, `paths::private_state::private_state_tests::*`,
198/// `paths::import::import_tests::*`.
199pub mod paths;
200
201/// Agent configuration loading.
202///
203/// Why: Sub-agents are defined declaratively in Markdown+frontmatter files
204/// under `.trusty-code/agents/` — or `.claude/agents/` on a project that has not
205/// imported yet (#5426; #2897 Slice D — TOML retired) so model, prompt,
206/// and parameters can evolve without code changes.
207/// What: `AgentConfig`, `AgentInfo`, `LlmParams`, `SystemPrompt`, `ToolsConfig`,
208/// `RunnerConfig`, `RunnerKind`, `discover_agents`, `load_all_agents`.
209/// Test: `agents::tests::*`.
210pub mod agents;
211
212/// Progressive-disclosure skill discovery for `.claude/skills/` (#2069,
213/// vision spec §5.3, Resolved Decision #7).
214///
215/// Why: A skill catalog's full Markdown bodies cost far more tokens than the
216/// PM/agents need up front — most skills in a session are never invoked.
217/// Splitting discovery into cheap, always-cached metadata (name +
218/// description) and an on-demand-loaded body is the token-efficiency layer
219/// P1B wires into `prompt::assemble_system_prompt_for_mode`'s `DailyDriver`
220/// arm.
221/// What: `SkillMetadata`, `locate_skills_dir` (`.claude/skills`, the
222/// Claude-Code-compatible path), `discover_skill_metadata`,
223/// `load_skill_body` (the lazy on-invoke loader), `format_skill_catalog`
224/// (prompt-injection rendering), and `FsSkillResolver` (the concrete
225/// `tools::SkillResolver` impl the `use_skill` tool is built on).
226/// Test: `skills::tests::*`.
227pub mod skills;
228
229/// Claude Code plugin ingestion, Phase 1: local-directory agents + skills
230/// only (issue #3539).
231///
232/// Why: a plugin packages agents/skills for drop-in use the same way a
233/// project's own `.claude/agents`/`.claude/skills` do; this module scans
234/// `.claude/plugins/<plugin>/` and layers the result additively, namespaced
235/// `<plugin>:<name>`, onto `agents::protocol::agents_list`,
236/// `skills::protocol::skills_list`, `agents::resolve_agent`, and
237/// `skills::FsSkillResolver` — never overriding an unnamespaced
238/// project/embedded/bundled entry.
239/// What: `discover_plugin_roots`, `agents::discover_plugin_agents`/
240/// `agents::find_plugin_agent_config`,
241/// `skills::discover_plugin_skills`/`skills::resolve_plugin_skill_body`.
242/// Test: `plugins::tests::*`, `plugins::agents::tests::*`,
243/// `plugins::skills::tests::*`.
244pub mod plugins;
245
246/// Harness mode selection: `daily-driver` (default, token-efficiency
247/// consumption point) vs `parity` (full-schema benchmark mode) — #2059,
248/// vision spec §5.9.
249///
250/// Why: reconciles the parity spec's byte-identical-schema requirement with
251/// the production harness's future token-efficiency work by making the
252/// choice an explicit, resolvable, queryable mode rather than picking one
253/// behaviour permanently.
254/// What: `HarnessMode`, `resolve_mode` (the three-tier precedence: env var >
255/// `task.run` param > `.claude/settings.json` > default).
256/// Test: `mode::tests::*`.
257pub mod mode;
258
259/// Per-verb glob-pattern tool permissions — `allow` / `ask` / `deny` (#7948).
260///
261/// Why: `tcode_tools:` is an exact-match allowlist and cannot express "run
262/// `git status` freely, never `rm`, ask about the rest"; the TUI permission
263/// prompt (#3422) also needs a decision object to prompt from.
264/// What: `parse_permissions`, `PermissionMap`, `PermissionGate`, the
265/// `PermissionBroker`, and `session.permission.respond`.
266/// Test: `permissions::tests::*`.
267pub mod permissions;
268
269/// Caller identity hierarchy for memory scoping.
270///
271/// Why: Memory must be scoped according to who is calling — operator, PM, or
272/// sub-agent — so agents cannot self-elevate their recall scope.
273/// What: `CallerIdentity` enum, `RecallCeiling`, env-var constructors.
274/// Test: `identity::tests::*`.
275pub mod identity;
276
277/// Tracing and logging initialisation.
278///
279/// Why: All binaries need consistent stderr-bound tracing setup; centralising
280/// it prevents duplicated setup across entry points.
281/// What: `init_tracing`, `init_tracing_for_test`, `DEFAULT_LOG_LEVEL`.
282/// Test: `logging::tests::*`.
283pub mod logging;
284
285/// `tcode serve`'s adoption of `trusty_common::log_drain::run_once` (#6537).
286///
287/// Why: `tcode serve` writes a durable file log (`logging::file_log_dir`)
288/// nothing collects. This is the single-project drain scheduler, the same
289/// shape as trusty-mpm's own Phase 3 wiring, scoped down to what one project's
290/// daemon needs.
291/// What: `LogDrainConfig` (`~/.trusty-code/log_drain.yaml`), `resolve_log_drain`,
292/// `spawn`.
293/// Test: `log_drain::config::tests`, `log_drain::resolve::tests`,
294/// `log_drain::scheduler::tests`.
295pub mod log_drain;
296
297/// Provider abstraction and per-agent model routing.
298///
299/// Why: Each agent routes to its own model, possibly behind a different backend
300/// (OpenRouter today, AWS Bedrock later). The agent loop depends on the
301/// `Provider` trait rather than branching on the backend, and a factory maps a
302/// model slug to the right implementation.
303/// What: `Provider`, `ToolChoice`, `OpenRouterProvider`, `BedrockProvider`,
304/// `provider_for`, `resolve_model`, `DEFAULT_MODEL`.
305/// Test: `provider::*` submodule tests.
306pub mod provider;
307
308/// Project-context ingestion — load `CLAUDE.md` for prompt injection (#1033).
309///
310/// Why: A Claude-Code-compatible harness must give the PM and every sub-agent
311/// the same project-specific rules a human Claude Code session sees — the
312/// project-root `CLAUDE.md`. This module reads that file, bounds its size so a
313/// runaway file cannot blow the model context budget, and degrades gracefully
314/// when the file is absent.
315/// What: `load_project_context` (root then `.claude/` lookup, size-capped with a
316/// provenance note on truncation) and `MAX_CONTEXT_BYTES`.
317/// Test: `project_context::tests::*`.
318pub mod project_context;
319
320/// The typed project binding — projectless / non-git dir / git repo.
321///
322/// Why: "project" was one concept split across two disagreeing API surfaces —
323/// `task.run` demanded a path it could not omit, `session.create` accepted a
324/// label it could not index. Projectless was therefore inexpressible, which made
325/// the shell's entry state (spec DOC-39 screen 7a) unimplementable. This module
326/// is the single object both surfaces now converge on.
327/// What: `ProjectBinding` (`None` | `Directory` | `GitRepo`), `BindingError`,
328/// and `is_git_worktree` — the crate's one git-detection implementation.
329/// Binding is NOT gated on `.git`: a non-git directory is a bound, indexing
330/// state (#2728/#2747).
331/// Test: `binding::tests::*`.
332pub mod binding;
333
334/// Workstream domain model + flat JSON persistence + boot reconciliation
335/// (DOC-48 Phase 1A, issue #3293).
336///
337/// Why: DOC-39 §4B's Workstream domain object had no daemon-owned identity —
338/// a restart silently discarded the in-memory `SessionRegistry`'s workstream
339/// grouping. This module gives it one: a serializable domain object plus a
340/// single flat, atomically-written JSON store per project.
341/// What: `WorkstreamId`, `WorkstreamState` (computed, never persisted),
342/// `Workstream` (the domain record); `WorkstreamStore` (load/save/create/get/
343/// list, the `set_active` persistence primitive, and boot reconciliation).
344/// Activation-lock RPC semantics, the RPC/REST/CLI surface, and SSE
345/// aggregation are out of scope here (#3294–#3297).
346/// Test: `cargo test -p trusty-code workstreams::`.
347pub mod workstreams;
348
349// ── Phase 4 orchestration layer (per #1028) ──
350
351/// Multi-turn agent loop driving an LLM through tool calls to completion.
352///
353/// Why: A task needing file reads, tool runs, and reaction to results cannot be
354/// done in one chat call; the loop is the bounded control structure that calls
355/// the model, dispatches gated tool calls, feeds results back, and iterates.
356/// What: `AgentLoop`, `AgentLoopConfig`, `AgentLoopError`, and `Transcript`. The
357/// loop is bounded by a turn cap and a wall-clock timeout, accrues token usage
358/// via `PerfCollector`, and returns an `AgentOutput`.
359/// Test: `agent_loop::tests::*` (stubbed two-turn flow, turn-cap abort,
360/// recoverable tool error, usage accrual) plus an `#[ignore]`-gated live test.
361pub mod agent_loop;
362
363/// In-process agent runner — the runtime execution layer (per #1029).
364///
365/// Why: The PM's `delegate_to_agent` tool dispatches to an `AgentRunner`; the M1
366/// harness runs the delegated sub-agent *in-process* so a delegation cycle is
367/// cheap, fully observable, and rolls the sub-agent's token usage onto the same
368/// shared LLM client as the PM. This module is the production implementation of
369/// that seam — and `RunnerKind::InProcess` is the real default backend.
370/// What: `InProcessAgentRunner` (implements `tools::AgentRunner`), the
371/// `RegistryFactory` DI seam for sub-agent tool assembly, `InProcessRunnerConfig`
372/// (default turn/timeout budget), `RunnerError`, and `agent_config_exists`. Each
373/// `run` loads the agent config, gates its tools by `tools.allowed`, resolves the
374/// model + assembled system prompt, drives an `AgentLoop`, and returns its output.
375/// Test: `runner::tests::*` (stubbed-PM delegation, return-to-PM output,
376/// `tools.allowed` enforcement, usage roll-up) — all offline.
377pub mod runner;
378
379/// `tcode run-task` end-to-end execution layer (#1034, #1035).
380///
381/// Why: This is the orchestration closer that makes the `tcode` binary run a task
382/// for real — load project context, assemble the PM prompt, run the PM loop, let
383/// it delegate to the engineer in-process, capture the diff + transcript + usage,
384/// and render a human or JSON report with meaningful exit codes. The LLM client is
385/// injected so the whole path is testable offline with a scripted mock.
386/// What: `RunTaskParams`, `execute_run_task`, `RunReport`, `ExitCode`, and the
387/// transcript types (`TurnRecord`, `SharedTranscript`, `RecordingLlmClient`).
388/// Test: `run_task::tests::*` (all offline, mocked LLM).
389pub mod run_task;
390
391/// Verify-before-finish gate (#2279): rejects a premature `finish_task` with
392/// a recoverable retry when a named test command was never run.
393///
394/// Why: (bake-off L2 diagnosis) An engineer that never runs the visible,
395/// prompt-named test suite can still call `finish_task` successfully today;
396/// this module gives both the delegated engineer's loop and the delegating
397/// PM's loop a turn-boundary hook to reject that specific case.
398/// What: [`agent_loop::FinishGate`] constructors `default_finish_gate` (own
399/// transcript) and `pm_finish_gate` (externally shared engineer transcript),
400/// plus the pure `names_test_command`/`is_test_command` regex predicates
401/// they share.
402/// Test: `verify_gate::tests::*`.
403pub mod verify_gate;
404
405/// Redundant full-suite test re-run suppression (#2682): the complement to
406/// [`verify_gate`] — it stops the suite running MORE than it needs to.
407///
408/// Why: (bake-off L1 diagnosis) The engineer re-runs the full suite 7-14x per
409/// run as repeated "one final run to confirm" passes, even when no code has
410/// changed since the last clean pass, inflating tcode's turn count far above
411/// claude-code's on the same challenge.
412/// What: The pure `is_redundant_test_rerun` predicate the agent loop consults
413/// (when suppression is enabled) to short-circuit a redundant test re-run with
414/// [`redundant_run::REDUNDANT_RERUN_MESSAGE`] instead of spawning the suite.
415/// Test: `redundant_run::tests::*`.
416pub mod redundant_run;
417
418/// L1-L3 bake-off milestone exit gate (#5441).
419///
420/// Why: [`verify_gate`] and [`redundant_run`] act inside a single run; this
421/// acts on the evidence a whole milestone's bake-off left behind. #5441 makes
422/// a real L1-L3 run the condition for closing a Trusty Code milestone, and the
423/// first qualification attempt showed prose cannot enforce it — three passing
424/// levels were still disqualified because nothing mechanically checked that the
425/// retained metadata identified the candidate build, the runner, or the sources
426/// it consumed.
427/// What: [`bakeoff::preflight()`] rejects incomplete L1-L3 coverage, missing
428/// artifacts or provenance, mock-only evidence, a stale runner, and results
429/// produced by a different `tcode` build; [`bakeoff::compare_against_baseline`]
430/// blocks correctness and completion regressions against the previous accepted
431/// baseline and requires a written disposition for cost/token/turn/duration
432/// changes outside tolerance. Entirely offline — it reads a retained bundle and
433/// never runs a model. Operator surface: `tcode bakeoff-gate`.
434/// Test: `bakeoff::tests::*`, plus `tests/bakeoff_gate_e2e.rs`.
435pub mod bakeoff;
436
437/// DOC-28 catch-up context injection for the PM prompt (#1762, PR2).
438///
439/// Why: The PM agent needs recent project-activity context (paused sessions,
440/// git commits, memory palace entries) at task start so it can orient without
441/// interrogating the operator. This module wraps the shared engine in
442/// trusty-common and exposes a single `pm_catchup_context` fn that is wired
443/// into the PM prompt path only (sub-agents receive `None`).
444/// What: `pm_catchup_context(project_dir) -> Option<String>` — async,
445/// fail-open (returns `None` on any error or empty result), never advances the
446/// watermark (advancement is owned by trusty-mpm `session_launch`).
447/// Test: `catchup::tests::pm_catchup_context_does_not_panic_on_empty_repo`.
448pub mod catchup;
449
450/// Shared trusty-memory `tools/call` envelope helpers (#2424).
451///
452/// Why: trusty-memory direct-dispatches only its `TOOL_METHODS` allowlist —
453/// every `chat_*` tool is reachable ONLY via the MCP `tools/call` envelope,
454/// which the #2343 soak found the turn recorder was not using (100% of
455/// durable writes failed `-32601`). One shared implementation of the
456/// envelope build/unwrap keeps the write side (`session::memory_sink`) and
457/// the read side (`tools::recall_session`) on the same verified shape.
458/// What: `tools_call_params`, `parse_tools_call_envelope`,
459/// `call_tool_wrapped`.
460/// Test: `memory_envelope::tests::*`.
461pub mod memory_envelope;
462
463/// A stand-in trusty-memory daemon on a temp Unix socket, for tests (#6286).
464///
465/// Test-only: the rigs that used to bind an ephemeral TCP port and serve
466/// `POST /rpc` share one accept loop here instead.
467#[cfg(test)]
468pub(crate) mod uds_mock;
469
470/// System-prompt assembly layer implementing the parity spec.
471///
472/// Why: The cross-model comparison harness must assemble the same fixed
473/// instruction surface for every model so the comparison measures the model,
474/// not the scaffolding (`docs/trusty-code/parity-spec.md` §1). This module owns
475/// that surface: the byte-identical BASE preamble, its version token, and the
476/// fixed-order assembler that merges BASE + agent prompt + project `CLAUDE.md`
477/// context + optional per-tier fallback guidance (the #1023 seam).
478/// What: `BASE_PREAMBLE`, `BASE_PREAMBLE_VERSION`, `PromptAssembler`, and
479/// `assemble_system_prompt`.
480/// Test: `prompt::tests::*`.
481pub mod prompt;
482
483// ── Phase 5 daemon transport layer (#2053, M1 control-plane cut line) ──
484
485/// JSON-RPC 2.0 core: wire types (re-exported from `trusty_mcp`) plus
486/// the tcode-specific `Router`/`RpcError` extensibility seam.
487///
488/// Why: `tcode serve` must speak the same JSON-RPC-over-STDIO contract as
489/// the rest of the trusty-* family; the `Router` is the new piece that lets
490/// later tickets register `session.*`/`task.*`/`harness.describe` methods
491/// without touching the transport loop.
492/// What: `Request`, `Response`, `error_codes` (re-exported), `RpcError`,
493/// `MethodHandler`, `Router`.
494/// Test: `jsonrpc::error::tests::*`, `jsonrpc::router::tests::*`.
495pub mod jsonrpc;
496
497/// The MCP servers this run is configured with, loaded and live (#5428).
498///
499/// Why: before this, `tcode` could reach exactly one MCP server — the
500/// hard-coded `search_code` tool. Every other connector in the file
501/// `trusty-agents` already reads (`~/.trusty-tools/mcp/servers.toml`) was
502/// invisible here.
503/// What: `McpToolSet::load` resolves the global and project tiers, gates the
504/// untrusted project tier by content, spawns each enabled stdio server in
505/// isolation, and exposes each advertised tool as `mcp__<server>__<tool>`;
506/// `register_configured_tools` puts them in a `ToolRegistry`.
507/// Test: `mcp::tests`, `crates/trusty-code/tests/mcp_loader_e2e.rs`.
508pub mod mcp;
509
510/// `tcode serve` daemon: STDIO + HTTP JSON-RPC transports + proof-of-life
511/// methods.
512///
513/// Why: the foundation of the M1 control-plane cut line (#2053) — proves the
514/// transport + router work end-to-end via `ping`/`health` before `session.*`
515/// (#2054), `task.*` (#2056), and `harness.describe` (#2066) land on top.
516/// Both transports dispatch through the same `Router`, so the method
517/// surface can never drift between `--stdio` and `--http`.
518/// What: `build_router`, `run_stdio`, `run_http`, `DEFAULT_HTTP_PORT`, and
519/// the `methods`/`transport`/`http` submodules.
520/// Test: `serve::tests::*`, `serve::methods::tests::*`,
521/// `serve::transport::tests::*`, `serve::http::tests::*`.
522pub mod serve;
523
524/// Daemon-side directory inspection for the UI's project picker (UI Phase-1).
525///
526/// Why: the UI is a thin client — no UI target (web OR Tauri) touches the
527/// filesystem directly, so browsing the local disk to pick a project has to be
528/// a daemon API. One call serves both the picker's rendering (screen 7a's
529/// breadcrumb + per-entry `git` badge) and the three-state project binding
530/// model (projectless → non-git dir → git repo).
531/// What: `list_dir`, `DirListing`, `DirEntryInfo`, `ListDirError`, and
532/// `fs_browse::protocol::register` (wires `fs.list_dir` onto a `Router`).
533/// Test: `fs_browse::tests::*`, `fs_browse::protocol::tests::*`.
534pub mod fs_browse;
535
536/// Daemon-owned session model + attach/detach protocol (#2054, Axiom 4).
537///
538/// Why: "The Daemon OWNS Sessions; CLI Attaches Over the API" — sessions
539/// are first-class objects living inside `tcode serve`, reachable via
540/// `session.*` JSON-RPC methods over both transports.
541/// What: `Session`, `SessionStatus`, `SessionRegistry`, and
542/// `session::protocol::register` (wires the seven `session.*` methods onto
543/// a `Router`).
544/// Test: `session::model::tests::*`, `session::registry::registry_tests::*`,
545/// `session::protocol::tests::*`; API-driven end-to-end coverage in
546/// `tests/session_e2e.rs`.
547pub mod session;
548
549/// Daemon-owned task execution: `task.run` + background agent-loop
550/// orchestration (#2056, M1 control-plane cut line).
551///
552/// Why: wires the session/event layer to the existing engine
553/// (`agent_loop`/`runner`/`tools`/`llm`) so a task actually EXECUTES through
554/// the daemon and streams live tool/lifecycle events to attached clients —
555/// the keystone that closes the M1 control-plane cut line.
556/// What: `task.run` JSON-RPC method, background execution orchestration, the
557/// concrete `SessionToolEventSink`, and the offline "echo" mock LLM
558/// (`TCODE_MOCK_LLM=echo`) that makes the whole flow black-box testable
559/// without a live model.
560/// Test: `task::executor::tests::*`, `task::protocol::tests::*`,
561/// `task::sink::tests::*`, `task::mock_llm::tests::*`; API-driven end-to-end
562/// coverage in `tests/task_e2e.rs`.
563pub mod task;
564
565/// Thin JSON-RPC client the `tcode` CLI binary drives against its own
566/// spawned `tcode serve --stdio` child (#2060, vision spec §4.4 "CLI as
567/// Thin Client" / Axiom 3 "API-First").
568///
569/// Why: the CLI must hold no orchestration logic of its own — every
570/// session/task operation goes through the SAME JSON-RPC surface `tcode
571/// serve` exposes, so a human, a script, and a future TUI see identical
572/// behaviour.
573/// What: `cli_client::stdio::StdioRpcClient` (spawn + NDJSON request/
574/// response/notification I/O) and `cli_client::render` (pure formatting for
575/// `session list`/`attach`/`run-task`/`transcript`).
576/// Test: `cli_client::stdio::tests::*`, `cli_client::render::tests::*`;
577/// end-to-end coverage in `tests/cli_e2e.rs`.
578pub mod cli_client;
579
580/// `CodeEngine` — the `trusty-code-tui` engine adapter driving a long-lived
581/// `tcode serve` daemon for the interactive `tcode tui` (#3415, DOC-50
582/// §3.3/§3.4, epic #3411 Slice 3; retransported onto the daemon's Unix socket
583/// in #6637).
584///
585/// Why: `cli_client` (above) spawns an EPHEMERAL `--stdio` child per CLI
586/// invocation — the right shape for one-shot commands, wrong for an
587/// interactive REPL that needs to hold a session open, stream responses
588/// live, and observe workstream activation pushed from OTHER clients. This
589/// module is the daemon counterpart: a thin `trusty_code_tui::TuiEngine`
590/// implementation that dials the daemon's socket and translates its responses
591/// into `trusty_code_tui::ReplEvent`s — no business logic of its own (DOC-39
592/// §2.1 thin-client axiom).
593/// What: `tui_client::uds_rpc` (the framed JSON-RPC client, unary calls and
594/// streams) and `tui_client::engine::CodeEngine` (the `TuiEngine` impl
595/// itself). The `discovery`/`rpc`/`sse` trio went with the HTTP transport —
596/// the socket path is derived rather than discovered, and the two SSE routes
597/// are now the `session.events` and `workstream.events` stream methods.
598/// Test: `tui_client::*::tests` for the pure helpers; the full
599/// setup/stream/cancel/workstream-activation flow against a real daemon socket
600/// in `tests/tui_client_engine.rs`.
601pub mod tui_client;
602
603/// The client-side credential for the daemon's transient HTTP listener
604/// (#5439, relocated in #6637).
605///
606/// Why its own module: it used to sit in `tui_client::discovery`, which #6637
607/// deleted along with the rest of the HTTP client. `session::connector`'s
608/// `TcodeConnector` still speaks HTTP until PR 2 moves the webview bridge into
609/// `trusty-code-gui`, so the credential half outlives the discovery half.
610/// What: `TCODE_DAEMON_TOKEN` and the loopback-gated resolver.
611/// Test: `http_credential::http_credential_tests`.
612pub mod http_credential;
613
614// ── Package-level re-exports ──
615
616/// Version string, re-exported so integration tests can assert it without
617/// hard-coding the constant.
618///
619/// Why: Single source of truth for the version across CLI and any future API
620/// responses that embed it.
621/// What: The `CARGO_PKG_VERSION` compile-time env var, captured at build time.
622/// Test: `cargo run -p trusty-code -- --version` must print this value.
623pub const VERSION: &str = env!("CARGO_PKG_VERSION");
624
625/// Test-only cross-module log-capture support for the #2857 observability
626/// tests (`*_logs_warn`/`*_logs_info` across `agent_loop`, `verify_gate`,
627/// `recall_session`, and `tools::delegate`).
628///
629/// Why: An EARLIER version of this support used
630/// `tracing::subscriber::set_default` (a per-thread SCOPED override),
631/// installed/removed fresh by every capturing test. `tracing`'s callsite
632/// "interest" cache is process-GLOBAL and is only recomputed when a
633/// subscriber is installed or removed; with many capture tests concurrently
634/// installing/removing their own scoped subscriber across a wide
635/// `cargo test` thread pool, the cache would intermittently settle on
636/// "nobody is interested" for a callsite at the exact moment a genuinely
637/// interested thread's event fired, silently dropping it — reproduced
638/// directly (an empty capture buffer in ~1-in-3 to 1-in-2 full-suite runs at
639/// `--test-threads` >= 4, but NEVER at `--test-threads=1`). Serializing the
640/// scoped installs did not fix it, because interest churn from ANY
641/// concurrently active install/remove anywhere in the process could still
642/// race the check.
643/// What: Installs exactly ONE global default subscriber, exactly once, for
644/// the whole test-binary process ([`ensure_global_capture_installed`], via
645/// `std::sync::Once`) — no scoped per-thread overrides, no repeated
646/// install/remove churn, so the callsite interest cache settles to "always
647/// interested" the first time each callsite is hit and never gets
648/// invalidated again. Its layer ([`GlobalCaptureLayer`]) writes every
649/// event's level + message into a `thread_local!` buffer — thread-local
650/// storage is inherently race-free across concurrent test threads (each
651/// thread only ever sees its OWN events), and a fresh `#[test]`/
652/// `#[tokio::test]` on a REUSED pool thread runs strictly after the
653/// previous one on that same thread finished, so [`begin_capture`]'s clear
654/// can never race a still-running previous test. [`captured_at_least`]
655/// reads back messages at `min_level` or more severe.
656/// `logging::tests::init_tracing_for_test_is_idempotent` also calls
657/// [`begin_capture`] before its own `try_init()`, guaranteeing this
658/// module's global install always wins the one-shot `set_global_default`
659/// race regardless of which test the harness happens to schedule first.
660/// Test: exercised indirectly by every `*_logs_warn`/`*_logs_info` test in
661/// this crate; a regression here would reintroduce the intermittent
662/// empty-capture failure this module exists to eliminate.
663#[cfg(test)]
664pub(crate) mod test_support {
665    use std::cell::RefCell;
666    use std::sync::Once;
667
668    thread_local! {
669        static CAPTURED: RefCell<Vec<(tracing::Level, String)>> = const { RefCell::new(Vec::new()) };
670    }
671
672    /// The permanent, process-wide capture layer (see module docs).
673    struct GlobalCaptureLayer;
674
675    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for GlobalCaptureLayer {
676        fn on_event(
677            &self,
678            event: &tracing::Event<'_>,
679            _ctx: tracing_subscriber::layer::Context<'_, S>,
680        ) {
681            struct MessageVisitor(String);
682            impl tracing::field::Visit for MessageVisitor {
683                fn record_debug(
684                    &mut self,
685                    field: &tracing::field::Field,
686                    value: &dyn std::fmt::Debug,
687                ) {
688                    if field.name() == "message" {
689                        self.0 = format!("{value:?}");
690                    }
691                }
692            }
693            let mut visitor = MessageVisitor(String::new());
694            event.record(&mut visitor);
695            let level = *event.metadata().level();
696            CAPTURED.with(|c| c.borrow_mut().push((level, visitor.0)));
697        }
698    }
699
700    static INSTALL_ONCE: Once = Once::new();
701
702    /// Install [`GlobalCaptureLayer`] as the process's global default
703    /// subscriber, exactly once. Idempotent and safe to call from every
704    /// capturing test's setup.
705    pub(crate) fn ensure_global_capture_installed() {
706        INSTALL_ONCE.call_once(|| {
707            use tracing_subscriber::layer::SubscriberExt as _;
708            let subscriber = tracing_subscriber::registry().with(GlobalCaptureLayer);
709            // Best-effort: every subscriber-touching test in this crate calls
710            // this function (directly or via `begin_capture`) before doing
711            // anything else tracing-related, so this install always wins the
712            // one-shot `set_global_default` race in practice.
713            let _ = tracing::subscriber::set_global_default(subscriber);
714        });
715    }
716
717    /// Ensure the global capture layer is installed and clear THIS thread's
718    /// captured-event buffer, ready to record a fresh test's events.
719    ///
720    /// Why/What: see module docs above.
721    pub(crate) fn begin_capture() {
722        ensure_global_capture_installed();
723        CAPTURED.with(|c| c.borrow_mut().clear());
724    }
725
726    /// This thread's captured event messages at `min_level` or more severe,
727    /// recorded since the last [`begin_capture`] call on this thread.
728    ///
729    /// Why/What: see module docs above.
730    pub(crate) fn captured_at_least(min_level: tracing::Level) -> Vec<String> {
731        CAPTURED.with(|c| {
732            c.borrow()
733                .iter()
734                .filter(|(level, _)| *level <= min_level)
735                .map(|(_, msg)| msg.clone())
736                .collect()
737        })
738    }
739}
740
741// #3036, #3195: keeps every spawned `tcode` child hermetic against the
742// developer's live trusty-search daemon.
743#[cfg(test)]
744mod daemon_isolation_tests;
745
746#[cfg(test)]
747mod tests {
748    use super::*;
749
750    #[test]
751    fn version_is_non_empty() {
752        // Why: guard against accidental blank version strings.
753        // What: asserts that VERSION is not the empty string.
754        // Test: this test itself.
755        assert!(!VERSION.is_empty());
756    }
757}