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 bundled and wired in as of Slice E, #2958);
178/// `EmbeddedSkill`/`DEFAULT_SKILLS` (trusty-mpm's universal skill set, minus
179/// the `tm-*` orchestration skills).
180/// Test: `assets::tests::*`.
181pub mod assets;
182
183/// Agent configuration loading.
184///
185/// Why: Sub-agents are defined declaratively in Markdown+frontmatter files
186/// under `.claude/agents/` (#2897 Slice D — TOML retired) so model, prompt,
187/// and parameters can evolve without code changes.
188/// What: `AgentConfig`, `AgentInfo`, `LlmParams`, `SystemPrompt`, `ToolsConfig`,
189/// `RunnerConfig`, `RunnerKind`, `discover_agents`, `load_all_agents`.
190/// Test: `agents::tests::*`.
191pub mod agents;
192
193/// Progressive-disclosure skill discovery for `.claude/skills/` (#2069,
194/// vision spec §5.3, Resolved Decision #7).
195///
196/// Why: A skill catalog's full Markdown bodies cost far more tokens than the
197/// PM/agents need up front — most skills in a session are never invoked.
198/// Splitting discovery into cheap, always-cached metadata (name +
199/// description) and an on-demand-loaded body is the token-efficiency layer
200/// P1B wires into `prompt::assemble_system_prompt_for_mode`'s `DailyDriver`
201/// arm.
202/// What: `SkillMetadata`, `locate_skills_dir` (`.claude/skills`, the
203/// Claude-Code-compatible path), `discover_skill_metadata`,
204/// `load_skill_body` (the lazy on-invoke loader), `format_skill_catalog`
205/// (prompt-injection rendering), and `FsSkillResolver` (the concrete
206/// `tools::SkillResolver` impl the `use_skill` tool is built on).
207/// Test: `skills::tests::*`.
208pub mod skills;
209
210/// Claude Code plugin ingestion, Phase 1: local-directory agents + skills
211/// only (issue #3539).
212///
213/// Why: a plugin packages agents/skills for drop-in use the same way a
214/// project's own `.claude/agents`/`.claude/skills` do; this module scans
215/// `.claude/plugins/<plugin>/` and layers the result additively, namespaced
216/// `<plugin>:<name>`, onto `agents::protocol::agents_list`,
217/// `skills::protocol::skills_list`, `agents::resolve_agent`, and
218/// `skills::FsSkillResolver` — never overriding an unnamespaced
219/// project/embedded/bundled entry.
220/// What: `discover_plugin_roots`, `agents::discover_plugin_agents`/
221/// `agents::find_plugin_agent_config`,
222/// `skills::discover_plugin_skills`/`skills::resolve_plugin_skill_body`.
223/// Test: `plugins::tests::*`, `plugins::agents::tests::*`,
224/// `plugins::skills::tests::*`.
225pub mod plugins;
226
227/// Harness mode selection: `daily-driver` (default, token-efficiency
228/// consumption point) vs `parity` (full-schema benchmark mode) — #2059,
229/// vision spec §5.9.
230///
231/// Why: reconciles the parity spec's byte-identical-schema requirement with
232/// the production harness's future token-efficiency work by making the
233/// choice an explicit, resolvable, queryable mode rather than picking one
234/// behaviour permanently.
235/// What: `HarnessMode`, `resolve_mode` (the three-tier precedence: env var >
236/// `task.run` param > `.claude/settings.json` > default).
237/// Test: `mode::tests::*`.
238pub mod mode;
239
240/// Caller identity hierarchy for memory scoping.
241///
242/// Why: Memory must be scoped according to who is calling — operator, PM, or
243/// sub-agent — so agents cannot self-elevate their recall scope.
244/// What: `CallerIdentity` enum, `RecallCeiling`, env-var constructors.
245/// Test: `identity::tests::*`.
246pub mod identity;
247
248/// Tracing and logging initialisation.
249///
250/// Why: All binaries need consistent stderr-bound tracing setup; centralising
251/// it prevents duplicated setup across entry points.
252/// What: `init_tracing`, `init_tracing_for_test`, `DEFAULT_LOG_LEVEL`.
253/// Test: `logging::tests::*`.
254pub mod logging;
255
256/// Provider abstraction and per-agent model routing.
257///
258/// Why: Each agent routes to its own model, possibly behind a different backend
259/// (OpenRouter today, AWS Bedrock later). The agent loop depends on the
260/// `Provider` trait rather than branching on the backend, and a factory maps a
261/// model slug to the right implementation.
262/// What: `Provider`, `ToolChoice`, `OpenRouterProvider`, `BedrockProvider`,
263/// `provider_for`, `resolve_model`, `DEFAULT_MODEL`.
264/// Test: `provider::*` submodule tests.
265pub mod provider;
266
267/// Project-context ingestion — load `CLAUDE.md` for prompt injection (#1033).
268///
269/// Why: A Claude-Code-compatible harness must give the PM and every sub-agent
270/// the same project-specific rules a human Claude Code session sees — the
271/// project-root `CLAUDE.md`. This module reads that file, bounds its size so a
272/// runaway file cannot blow the model context budget, and degrades gracefully
273/// when the file is absent.
274/// What: `load_project_context` (root then `.claude/` lookup, size-capped with a
275/// provenance note on truncation) and `MAX_CONTEXT_BYTES`.
276/// Test: `project_context::tests::*`.
277pub mod project_context;
278
279/// The typed project binding — projectless / non-git dir / git repo.
280///
281/// Why: "project" was one concept split across two disagreeing API surfaces —
282/// `task.run` demanded a path it could not omit, `session.create` accepted a
283/// label it could not index. Projectless was therefore inexpressible, which made
284/// the shell's entry state (spec DOC-39 screen 7a) unimplementable. This module
285/// is the single object both surfaces now converge on.
286/// What: `ProjectBinding` (`None` | `Directory` | `GitRepo`), `BindingError`,
287/// and `is_git_worktree` — the crate's one git-detection implementation.
288/// Binding is NOT gated on `.git`: a non-git directory is a bound, indexing
289/// state (#2728/#2747).
290/// Test: `binding::tests::*`.
291pub mod binding;
292
293/// Workstream domain model + flat JSON persistence + boot reconciliation
294/// (DOC-48 Phase 1A, issue #3293).
295///
296/// Why: DOC-39 §4B's Workstream domain object had no daemon-owned identity —
297/// a restart silently discarded the in-memory `SessionRegistry`'s workstream
298/// grouping. This module gives it one: a serializable domain object plus a
299/// single flat, atomically-written JSON store per project.
300/// What: `WorkstreamId`, `WorkstreamState` (computed, never persisted),
301/// `Workstream` (the domain record); `WorkstreamStore` (load/save/create/get/
302/// list, the `set_active` persistence primitive, and boot reconciliation).
303/// Activation-lock RPC semantics, the RPC/REST/CLI surface, and SSE
304/// aggregation are out of scope here (#3294–#3297).
305/// Test: `cargo test -p trusty-code workstreams::`.
306pub mod workstreams;
307
308// ── Phase 4 orchestration layer (per #1028) ──
309
310/// Multi-turn agent loop driving an LLM through tool calls to completion.
311///
312/// Why: A task needing file reads, tool runs, and reaction to results cannot be
313/// done in one chat call; the loop is the bounded control structure that calls
314/// the model, dispatches gated tool calls, feeds results back, and iterates.
315/// What: `AgentLoop`, `AgentLoopConfig`, `AgentLoopError`, and `Transcript`. The
316/// loop is bounded by a turn cap and a wall-clock timeout, accrues token usage
317/// via `PerfCollector`, and returns an `AgentOutput`.
318/// Test: `agent_loop::tests::*` (stubbed two-turn flow, turn-cap abort,
319/// recoverable tool error, usage accrual) plus an `#[ignore]`-gated live test.
320pub mod agent_loop;
321
322/// In-process agent runner — the runtime execution layer (per #1029).
323///
324/// Why: The PM's `delegate_to_agent` tool dispatches to an `AgentRunner`; the M1
325/// harness runs the delegated sub-agent *in-process* so a delegation cycle is
326/// cheap, fully observable, and rolls the sub-agent's token usage onto the same
327/// shared LLM client as the PM. This module is the production implementation of
328/// that seam — and `RunnerKind::InProcess` is the real default backend.
329/// What: `InProcessAgentRunner` (implements `tools::AgentRunner`), the
330/// `RegistryFactory` DI seam for sub-agent tool assembly, `InProcessRunnerConfig`
331/// (default turn/timeout budget), `RunnerError`, and `agent_config_exists`. Each
332/// `run` loads the agent config, gates its tools by `tools.allowed`, resolves the
333/// model + assembled system prompt, drives an `AgentLoop`, and returns its output.
334/// Test: `runner::tests::*` (stubbed-PM delegation, return-to-PM output,
335/// `tools.allowed` enforcement, usage roll-up) — all offline.
336pub mod runner;
337
338/// `tcode run-task` end-to-end execution layer (#1034, #1035).
339///
340/// Why: This is the orchestration closer that makes the `tcode` binary run a task
341/// for real — load project context, assemble the PM prompt, run the PM loop, let
342/// it delegate to the engineer in-process, capture the diff + transcript + usage,
343/// and render a human or JSON report with meaningful exit codes. The LLM client is
344/// injected so the whole path is testable offline with a scripted mock.
345/// What: `RunTaskParams`, `execute_run_task`, `RunReport`, `ExitCode`, and the
346/// transcript types (`TurnRecord`, `SharedTranscript`, `RecordingLlmClient`).
347/// Test: `run_task::tests::*` (all offline, mocked LLM).
348pub mod run_task;
349
350/// Verify-before-finish gate (#2279): rejects a premature `finish_task` with
351/// a recoverable retry when a named test command was never run.
352///
353/// Why: (bake-off L2 diagnosis) An engineer that never runs the visible,
354/// prompt-named test suite can still call `finish_task` successfully today;
355/// this module gives both the delegated engineer's loop and the delegating
356/// PM's loop a turn-boundary hook to reject that specific case.
357/// What: [`agent_loop::FinishGate`] constructors `default_finish_gate` (own
358/// transcript) and `pm_finish_gate` (externally shared engineer transcript),
359/// plus the pure `names_test_command`/`is_test_command` regex predicates
360/// they share.
361/// Test: `verify_gate::tests::*`.
362pub mod verify_gate;
363
364/// Redundant full-suite test re-run suppression (#2682): the complement to
365/// [`verify_gate`] — it stops the suite running MORE than it needs to.
366///
367/// Why: (bake-off L1 diagnosis) The engineer re-runs the full suite 7-14x per
368/// run as repeated "one final run to confirm" passes, even when no code has
369/// changed since the last clean pass, inflating tcode's turn count far above
370/// claude-code's on the same challenge.
371/// What: The pure `is_redundant_test_rerun` predicate the agent loop consults
372/// (when suppression is enabled) to short-circuit a redundant test re-run with
373/// [`redundant_run::REDUNDANT_RERUN_MESSAGE`] instead of spawning the suite.
374/// Test: `redundant_run::tests::*`.
375pub mod redundant_run;
376
377/// DOC-28 catch-up context injection for the PM prompt (#1762, PR2).
378///
379/// Why: The PM agent needs recent project-activity context (paused sessions,
380/// git commits, memory palace entries) at task start so it can orient without
381/// interrogating the operator. This module wraps the shared engine in
382/// trusty-common and exposes a single `pm_catchup_context` fn that is wired
383/// into the PM prompt path only (sub-agents receive `None`).
384/// What: `pm_catchup_context(project_dir) -> Option<String>` — async,
385/// fail-open (returns `None` on any error or empty result), never advances the
386/// watermark (advancement is owned by trusty-mpm `session_launch`).
387/// Test: `catchup::tests::pm_catchup_context_does_not_panic_on_empty_repo`.
388pub mod catchup;
389
390/// Shared trusty-memory `tools/call` envelope helpers (#2424).
391///
392/// Why: trusty-memory direct-dispatches only its `TOOL_METHODS` allowlist —
393/// every `chat_*` tool is reachable ONLY via the MCP `tools/call` envelope,
394/// which the #2343 soak found the turn recorder was not using (100% of
395/// durable writes failed `-32601`). One shared implementation of the
396/// envelope build/unwrap keeps the write side (`session::memory_sink`) and
397/// the read side (`tools::recall_session`) on the same verified shape.
398/// What: `tools_call_params`, `parse_tools_call_envelope`,
399/// `call_tool_wrapped`.
400/// Test: `memory_envelope::tests::*`.
401pub mod memory_envelope;
402
403/// A stand-in trusty-memory daemon on a temp Unix socket, for tests (#6286).
404///
405/// Test-only: the rigs that used to bind an ephemeral TCP port and serve
406/// `POST /rpc` share one accept loop here instead.
407#[cfg(test)]
408pub(crate) mod uds_mock;
409
410/// System-prompt assembly layer implementing the parity spec.
411///
412/// Why: The cross-model comparison harness must assemble the same fixed
413/// instruction surface for every model so the comparison measures the model,
414/// not the scaffolding (`docs/trusty-code/parity-spec.md` §1). This module owns
415/// that surface: the byte-identical BASE preamble, its version token, and the
416/// fixed-order assembler that merges BASE + agent prompt + project `CLAUDE.md`
417/// context + optional per-tier fallback guidance (the #1023 seam).
418/// What: `BASE_PREAMBLE`, `BASE_PREAMBLE_VERSION`, `PromptAssembler`, and
419/// `assemble_system_prompt`.
420/// Test: `prompt::tests::*`.
421pub mod prompt;
422
423// ── Phase 5 daemon transport layer (#2053, M1 control-plane cut line) ──
424
425/// JSON-RPC 2.0 core: wire types (re-exported from `trusty_mcp`) plus
426/// the tcode-specific `Router`/`RpcError` extensibility seam.
427///
428/// Why: `tcode serve` must speak the same JSON-RPC-over-STDIO contract as
429/// the rest of the trusty-* family; the `Router` is the new piece that lets
430/// later tickets register `session.*`/`task.*`/`harness.describe` methods
431/// without touching the transport loop.
432/// What: `Request`, `Response`, `error_codes` (re-exported), `RpcError`,
433/// `MethodHandler`, `Router`.
434/// Test: `jsonrpc::error::tests::*`, `jsonrpc::router::tests::*`.
435pub mod jsonrpc;
436
437/// `tcode serve` daemon: STDIO + HTTP JSON-RPC transports + proof-of-life
438/// methods.
439///
440/// Why: the foundation of the M1 control-plane cut line (#2053) — proves the
441/// transport + router work end-to-end via `ping`/`health` before `session.*`
442/// (#2054), `task.*` (#2056), and `harness.describe` (#2066) land on top.
443/// Both transports dispatch through the same `Router`, so the method
444/// surface can never drift between `--stdio` and `--http`.
445/// What: `build_router`, `run_stdio`, `run_http`, `DEFAULT_HTTP_PORT`, and
446/// the `methods`/`transport`/`http` submodules.
447/// Test: `serve::tests::*`, `serve::methods::tests::*`,
448/// `serve::transport::tests::*`, `serve::http::tests::*`.
449pub mod serve;
450
451/// Daemon-side directory inspection for the UI's project picker (UI Phase-1).
452///
453/// Why: the UI is a thin client — no UI target (web OR Tauri) touches the
454/// filesystem directly, so browsing the local disk to pick a project has to be
455/// a daemon API. One call serves both the picker's rendering (screen 7a's
456/// breadcrumb + per-entry `git` badge) and the three-state project binding
457/// model (projectless → non-git dir → git repo).
458/// What: `list_dir`, `DirListing`, `DirEntryInfo`, `ListDirError`, and
459/// `fs_browse::protocol::register` (wires `fs.list_dir` onto a `Router`).
460/// Test: `fs_browse::tests::*`, `fs_browse::protocol::tests::*`.
461pub mod fs_browse;
462
463/// Daemon-owned session model + attach/detach protocol (#2054, Axiom 4).
464///
465/// Why: "The Daemon OWNS Sessions; CLI Attaches Over the API" — sessions
466/// are first-class objects living inside `tcode serve`, reachable via
467/// `session.*` JSON-RPC methods over both transports.
468/// What: `Session`, `SessionStatus`, `SessionRegistry`, and
469/// `session::protocol::register` (wires the seven `session.*` methods onto
470/// a `Router`).
471/// Test: `session::model::tests::*`, `session::registry::registry_tests::*`,
472/// `session::protocol::tests::*`; API-driven end-to-end coverage in
473/// `tests/session_e2e.rs`.
474pub mod session;
475
476/// Daemon-owned task execution: `task.run` + background agent-loop
477/// orchestration (#2056, M1 control-plane cut line).
478///
479/// Why: wires the session/event layer to the existing engine
480/// (`agent_loop`/`runner`/`tools`/`llm`) so a task actually EXECUTES through
481/// the daemon and streams live tool/lifecycle events to attached clients —
482/// the keystone that closes the M1 control-plane cut line.
483/// What: `task.run` JSON-RPC method, background execution orchestration, the
484/// concrete `SessionToolEventSink`, and the offline "echo" mock LLM
485/// (`TCODE_MOCK_LLM=echo`) that makes the whole flow black-box testable
486/// without a live model.
487/// Test: `task::executor::tests::*`, `task::protocol::tests::*`,
488/// `task::sink::tests::*`, `task::mock_llm::tests::*`; API-driven end-to-end
489/// coverage in `tests/task_e2e.rs`.
490pub mod task;
491
492/// Thin JSON-RPC client the `tcode` CLI binary drives against its own
493/// spawned `tcode serve --stdio` child (#2060, vision spec §4.4 "CLI as
494/// Thin Client" / Axiom 3 "API-First").
495///
496/// Why: the CLI must hold no orchestration logic of its own — every
497/// session/task operation goes through the SAME JSON-RPC surface `tcode
498/// serve` exposes, so a human, a script, and a future TUI see identical
499/// behaviour.
500/// What: `cli_client::stdio::StdioRpcClient` (spawn + NDJSON request/
501/// response/notification I/O) and `cli_client::render` (pure formatting for
502/// `session list`/`attach`/`run-task`/`transcript`).
503/// Test: `cli_client::stdio::tests::*`, `cli_client::render::tests::*`;
504/// end-to-end coverage in `tests/cli_e2e.rs`.
505pub mod cli_client;
506
507/// `CodeEngine` — the `trusty-code-tui` engine adapter driving a long-lived
508/// `tcode serve --http` daemon for the interactive `tcode tui` (#3415,
509/// DOC-50 §3.3/§3.4, epic #3411 Slice 3).
510///
511/// Why: `cli_client` (above) spawns an EPHEMERAL `--stdio` child per CLI
512/// invocation — the right shape for one-shot commands, wrong for an
513/// interactive REPL that needs to hold a session open, stream responses
514/// live, and observe workstream activation pushed from OTHER clients. This
515/// module is the HTTP counterpart: a thin `trusty_code_tui::TuiEngine`
516/// implementation that discovers an already-running daemon and drives it
517/// over pooled HTTP + SSE, translating daemon responses into
518/// `trusty_code_tui::ReplEvent`s — no business logic of its own (DOC-39 §2.1
519/// thin-client axiom).
520/// What: `tui_client::discovery` (daemon lookup: `TCODE_DAEMON_URL` env var
521/// -> `serve::discovery`'s `http_addr` file -> liveness ping), `tui_client::rpc`
522/// (pooled `POST /rpc` client, reusing `trusty_mcp::{Request,Response}`
523/// exactly like `cli_client::stdio` does over STDIO), `tui_client::sse` (a
524/// minimal SSE line pump over `reqwest`'s byte stream), and
525/// `tui_client::engine::CodeEngine` (the `TuiEngine` impl itself).
526/// Test: `tui_client::*::tests` for the pure helpers; the full
527/// discover/setup/stream/cancel/workstream-activation flow against a mock
528/// HTTP daemon in `tests/tui_client_engine.rs`.
529pub mod tui_client;
530
531// ── Package-level re-exports ──
532
533/// Version string, re-exported so integration tests can assert it without
534/// hard-coding the constant.
535///
536/// Why: Single source of truth for the version across CLI and any future API
537/// responses that embed it.
538/// What: The `CARGO_PKG_VERSION` compile-time env var, captured at build time.
539/// Test: `cargo run -p trusty-code -- --version` must print this value.
540pub const VERSION: &str = env!("CARGO_PKG_VERSION");
541
542/// Test-only cross-module log-capture support for the #2857 observability
543/// tests (`*_logs_warn`/`*_logs_info` across `agent_loop`, `verify_gate`,
544/// `recall_session`, and `tools::delegate`).
545///
546/// Why: An EARLIER version of this support used
547/// `tracing::subscriber::set_default` (a per-thread SCOPED override),
548/// installed/removed fresh by every capturing test. `tracing`'s callsite
549/// "interest" cache is process-GLOBAL and is only recomputed when a
550/// subscriber is installed or removed; with many capture tests concurrently
551/// installing/removing their own scoped subscriber across a wide
552/// `cargo test` thread pool, the cache would intermittently settle on
553/// "nobody is interested" for a callsite at the exact moment a genuinely
554/// interested thread's event fired, silently dropping it — reproduced
555/// directly (an empty capture buffer in ~1-in-3 to 1-in-2 full-suite runs at
556/// `--test-threads` >= 4, but NEVER at `--test-threads=1`). Serializing the
557/// scoped installs did not fix it, because interest churn from ANY
558/// concurrently active install/remove anywhere in the process could still
559/// race the check.
560/// What: Installs exactly ONE global default subscriber, exactly once, for
561/// the whole test-binary process ([`ensure_global_capture_installed`], via
562/// `std::sync::Once`) — no scoped per-thread overrides, no repeated
563/// install/remove churn, so the callsite interest cache settles to "always
564/// interested" the first time each callsite is hit and never gets
565/// invalidated again. Its layer ([`GlobalCaptureLayer`]) writes every
566/// event's level + message into a `thread_local!` buffer — thread-local
567/// storage is inherently race-free across concurrent test threads (each
568/// thread only ever sees its OWN events), and a fresh `#[test]`/
569/// `#[tokio::test]` on a REUSED pool thread runs strictly after the
570/// previous one on that same thread finished, so [`begin_capture`]'s clear
571/// can never race a still-running previous test. [`captured_at_least`]
572/// reads back messages at `min_level` or more severe.
573/// `logging::tests::init_tracing_for_test_is_idempotent` also calls
574/// [`begin_capture`] before its own `try_init()`, guaranteeing this
575/// module's global install always wins the one-shot `set_global_default`
576/// race regardless of which test the harness happens to schedule first.
577/// Test: exercised indirectly by every `*_logs_warn`/`*_logs_info` test in
578/// this crate; a regression here would reintroduce the intermittent
579/// empty-capture failure this module exists to eliminate.
580#[cfg(test)]
581pub(crate) mod test_support {
582    use std::cell::RefCell;
583    use std::sync::Once;
584
585    thread_local! {
586        static CAPTURED: RefCell<Vec<(tracing::Level, String)>> = const { RefCell::new(Vec::new()) };
587    }
588
589    /// The permanent, process-wide capture layer (see module docs).
590    struct GlobalCaptureLayer;
591
592    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for GlobalCaptureLayer {
593        fn on_event(
594            &self,
595            event: &tracing::Event<'_>,
596            _ctx: tracing_subscriber::layer::Context<'_, S>,
597        ) {
598            struct MessageVisitor(String);
599            impl tracing::field::Visit for MessageVisitor {
600                fn record_debug(
601                    &mut self,
602                    field: &tracing::field::Field,
603                    value: &dyn std::fmt::Debug,
604                ) {
605                    if field.name() == "message" {
606                        self.0 = format!("{value:?}");
607                    }
608                }
609            }
610            let mut visitor = MessageVisitor(String::new());
611            event.record(&mut visitor);
612            let level = *event.metadata().level();
613            CAPTURED.with(|c| c.borrow_mut().push((level, visitor.0)));
614        }
615    }
616
617    static INSTALL_ONCE: Once = Once::new();
618
619    /// Install [`GlobalCaptureLayer`] as the process's global default
620    /// subscriber, exactly once. Idempotent and safe to call from every
621    /// capturing test's setup.
622    pub(crate) fn ensure_global_capture_installed() {
623        INSTALL_ONCE.call_once(|| {
624            use tracing_subscriber::layer::SubscriberExt as _;
625            let subscriber = tracing_subscriber::registry().with(GlobalCaptureLayer);
626            // Best-effort: every subscriber-touching test in this crate calls
627            // this function (directly or via `begin_capture`) before doing
628            // anything else tracing-related, so this install always wins the
629            // one-shot `set_global_default` race in practice.
630            let _ = tracing::subscriber::set_global_default(subscriber);
631        });
632    }
633
634    /// Ensure the global capture layer is installed and clear THIS thread's
635    /// captured-event buffer, ready to record a fresh test's events.
636    ///
637    /// Why/What: see module docs above.
638    pub(crate) fn begin_capture() {
639        ensure_global_capture_installed();
640        CAPTURED.with(|c| c.borrow_mut().clear());
641    }
642
643    /// This thread's captured event messages at `min_level` or more severe,
644    /// recorded since the last [`begin_capture`] call on this thread.
645    ///
646    /// Why/What: see module docs above.
647    pub(crate) fn captured_at_least(min_level: tracing::Level) -> Vec<String> {
648        CAPTURED.with(|c| {
649            c.borrow()
650                .iter()
651                .filter(|(level, _)| *level <= min_level)
652                .map(|(_, msg)| msg.clone())
653                .collect()
654        })
655    }
656}
657
658// #3036, #3195: keeps every spawned `tcode` child hermetic against the
659// developer's live trusty-search daemon.
660#[cfg(test)]
661mod daemon_isolation_tests;
662
663#[cfg(test)]
664mod tests {
665    use super::*;
666
667    #[test]
668    fn version_is_non_empty() {
669        // Why: guard against accidental blank version strings.
670        // What: asserts that VERSION is not the empty string.
671        // Test: this test itself.
672        assert!(!VERSION.is_empty());
673    }
674}