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