trusty-code 0.8.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! 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.
#![deny(rustdoc::broken_intra_doc_links)]

// ── 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`.
pub mod events;

/// 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.
pub mod ipc;

/// 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::*`.
pub mod perf;

/// 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::*`.
pub mod intent;

/// 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::*`.
pub mod progress;

/// 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::*`.
pub mod build_info;

// ── 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::*`.
pub mod tools;

/// 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::*`.
pub mod rbac;

// ── 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.
pub mod llm;

/// Built-in default agents & skills (#2895; roster expanded to 31 agents in
/// Slice E3, #2958; `pm` added as a 4th tcode-own default for #3437), read from
/// instructional content at runtime since #9013.
///
/// Why: A fresh project has no `.claude/agents/` or `.claude/skills/` yet; a
/// working default set gives every project a usable harness before any
/// project-level config exists. Disk-based config always wins when present.
/// ADR-0064: nothing is compiled in; `assets::content` reads the texts.
/// 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 wired in as of Slice E, #2958, whose shared texts are read from
/// instructional content since #9011);
/// `DEFAULT_SKILL_NAMES` (trusty-mpm's universal skill set, minus
/// the `tm-*` orchestration skills).
/// Test: `assets::tests::*`.
pub mod assets;

/// Trusty Code's own configuration and state layout (#5426, epic #2892).
///
/// Why: every discovery site used to join the literal `.claude/` itself, which
/// made another product's directory the source of truth for this one and left
/// nothing stopping a write INTO it. #5426 makes `<project>/.trusty-code/` the
/// read-preferred and write-only location, with `.claude/` (and `.open-mpm/`)
/// demoted to compatibility inputs.
/// What: `resolve_project_entry` (the one precedence rule: `.trusty-code` →
/// `.claude` → `.open-mpm`, then a native default) plus the per-entry
/// `agents_dir`/`skills_dir`/`plugins_dir`/`settings_file` wrappers;
/// `native_config_dir`/`check_native_write_target` (the write boundary, symlink
/// escapes included); `private_state` (`~/.trusty-code/`, mode `0700`); and
/// `import` (the deterministic, non-overwriting `.claude/` import).
/// Test: `paths::tests::*`, `paths::private_state::private_state_tests::*`,
/// `paths::import::import_tests::*`.
pub mod paths;

/// Agent configuration loading.
///
/// Why: Sub-agents are defined declaratively in Markdown+frontmatter files
/// under `.trusty-code/agents/` — or `.claude/agents/` on a project that has not
/// imported yet (#5426; #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::*`.
pub mod agents;

/// 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::*`.
pub mod skills;

/// 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::*`.
pub mod plugins;

/// 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::*`.
pub mod mode;

/// Per-verb glob-pattern tool permissions — `allow` / `ask` / `deny` (#7948).
///
/// Why: `tcode_tools:` is an exact-match allowlist and cannot express "run
/// `git status` freely, never `rm`, ask about the rest"; the TUI permission
/// prompt (#3422) also needs a decision object to prompt from.
/// What: `parse_permissions`, `PermissionMap`, `PermissionGate`, the
/// `PermissionBroker`, and `session.permission.respond`.
/// Test: `permissions::tests::*`.
pub mod permissions;

/// 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::*`.
pub mod identity;

/// 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::*`.
pub mod logging;

/// `tcode serve`'s adoption of `trusty_common::log_drain::run_once` (#6537).
///
/// Why: `tcode serve` writes a durable file log (`logging::file_log_dir`)
/// nothing collects. This is the single-project drain scheduler, the same
/// shape as trusty-mpm's own Phase 3 wiring, scoped down to what one project's
/// daemon needs.
/// What: `LogDrainConfig` (`~/.trusty-code/log_drain.yaml`), `resolve_log_drain`,
/// `spawn`.
/// Test: `log_drain::config::tests`, `log_drain::resolve::tests`,
/// `log_drain::scheduler::tests`.
pub mod log_drain;

/// 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.
pub mod provider;

/// 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::*`.
pub mod project_context;

/// 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::*`.
pub mod binding;

/// 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::`.
pub mod 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.
pub mod agent_loop;

/// 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.
pub mod runner;

/// `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).
pub mod run_task;

/// 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::*`.
pub mod verify_gate;

/// 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::*`.
pub mod redundant_run;

/// L1-L3 bake-off milestone exit gate (#5441).
///
/// Why: [`verify_gate`] and [`redundant_run`] act inside a single run; this
/// acts on the evidence a whole milestone's bake-off left behind. #5441 makes
/// a real L1-L3 run the condition for closing a Trusty Code milestone, and the
/// first qualification attempt showed prose cannot enforce it — three passing
/// levels were still disqualified because nothing mechanically checked that the
/// retained metadata identified the candidate build, the runner, or the sources
/// it consumed.
/// What: [`bakeoff::preflight()`] rejects incomplete L1-L3 coverage, missing
/// artifacts or provenance, mock-only evidence, a stale runner, and results
/// produced by a different `tcode` build; [`bakeoff::compare_against_baseline`]
/// blocks correctness and completion regressions against the previous accepted
/// baseline and requires a written disposition for cost/token/turn/duration
/// changes outside tolerance. Entirely offline — it reads a retained bundle and
/// never runs a model. Operator surface: `tcode bakeoff-gate`.
/// Test: `bakeoff::tests::*`, plus `tests/bakeoff_gate_e2e.rs`.
pub mod bakeoff;

/// 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`.
pub mod catchup;

/// 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::*`.
pub mod memory_envelope;

/// 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.
#[cfg(test)]
pub(crate) mod uds_mock;

/// 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::*`.
pub mod prompt;

// ── 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::*`.
pub mod jsonrpc;

/// The MCP servers this run is configured with, loaded and live (#5428).
///
/// Why: before this, `tcode` could reach exactly one MCP server — the
/// hard-coded `search_code` tool. Every other connector in the file
/// `trusty-agents` already reads (`~/.trusty-tools/mcp/servers.toml`) was
/// invisible here.
/// What: `McpToolSet::load` resolves the global and project tiers, gates the
/// untrusted project tier by content, spawns each enabled stdio server in
/// isolation, and exposes each advertised tool as `mcp__<server>__<tool>`;
/// `register_configured_tools` puts them in a `ToolRegistry`.
/// Test: `mcp::tests`, `crates/trusty-code/tests/mcp_loader_e2e.rs`.
pub mod mcp;

/// `tcode serve` daemon: the Unix-socket and STDIO JSON-RPC transports plus
/// 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 the socket. #6637: the
/// loopback HTTP transport is gone.
/// What: `build_router`, `run_stdio`, and the `methods`/`transport`/`uds`
/// submodules.
/// Test: `serve::tests::*`, `serve::methods::tests::*`,
/// `serve::transport::tests::*`, `serve::uds::uds_tests::*`.
pub mod serve;

/// 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::*`.
pub mod fs_browse;

/// 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`.
pub mod session;

/// 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`.
pub mod task;

/// 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`.
pub mod cli_client;

/// `CodeEngine` — the `trusty-code-tui` engine adapter driving a long-lived
/// `tcode serve` daemon for the interactive `tcode tui` (#3415, DOC-50
/// §3.3/§3.4, epic #3411 Slice 3; retransported onto the daemon's Unix socket
/// in #6637).
///
/// 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 daemon counterpart: a thin `trusty_code_tui::TuiEngine`
/// implementation that dials the daemon's socket and translates its responses
/// into `trusty_code_tui::ReplEvent`s — no business logic of its own (DOC-39
/// §2.1 thin-client axiom).
/// What: `tui_client::uds_rpc` (the framed JSON-RPC client, unary calls and
/// streams) and `tui_client::engine::CodeEngine` (the `TuiEngine` impl
/// itself). The `discovery`/`rpc`/`sse` trio went with the HTTP transport —
/// the socket path is derived rather than discovered, and the two SSE routes
/// are now the `session.events` and `workstream.events` stream methods.
/// Test: `tui_client::*::tests` for the pure helpers; the full
/// setup/stream/cancel/workstream-activation flow against a real daemon socket
/// in `tests/tui_client_engine.rs`.
pub mod tui_client;

// ── 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!("CARGO_PKG_VERSION");

/// 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.
#[cfg(test)]
pub(crate) mod test_support {
    use std::cell::RefCell;
    use std::sync::Once;

    thread_local! {
        static CAPTURED: RefCell<Vec<(tracing::Level, String)>> = const { RefCell::new(Vec::new()) };
    }

    /// The permanent, process-wide capture layer (see module docs).
    struct GlobalCaptureLayer;

    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for GlobalCaptureLayer {
        fn on_event(
            &self,
            event: &tracing::Event<'_>,
            _ctx: tracing_subscriber::layer::Context<'_, S>,
        ) {
            struct MessageVisitor(String);
            impl tracing::field::Visit for MessageVisitor {
                fn record_debug(
                    &mut self,
                    field: &tracing::field::Field,
                    value: &dyn std::fmt::Debug,
                ) {
                    if field.name() == "message" {
                        self.0 = format!("{value:?}");
                    }
                }
            }
            let mut visitor = MessageVisitor(String::new());
            event.record(&mut visitor);
            let level = *event.metadata().level();
            CAPTURED.with(|c| c.borrow_mut().push((level, visitor.0)));
        }
    }

    static INSTALL_ONCE: Once = Once::new();

    /// Install [`GlobalCaptureLayer`] as the process's global default
    /// subscriber, exactly once. Idempotent and safe to call from every
    /// capturing test's setup.
    pub(crate) fn ensure_global_capture_installed() {
        INSTALL_ONCE.call_once(|| {
            use tracing_subscriber::layer::SubscriberExt as _;
            let subscriber = tracing_subscriber::registry().with(GlobalCaptureLayer);
            // Best-effort: every subscriber-touching test in this crate calls
            // this function (directly or via `begin_capture`) before doing
            // anything else tracing-related, so this install always wins the
            // one-shot `set_global_default` race in practice.
            let _ = tracing::subscriber::set_global_default(subscriber);
        });
    }

    /// Ensure the global capture layer is installed and clear THIS thread's
    /// captured-event buffer, ready to record a fresh test's events.
    ///
    /// Why/What: see module docs above.
    pub(crate) fn begin_capture() {
        ensure_global_capture_installed();
        CAPTURED.with(|c| c.borrow_mut().clear());
    }

    /// This thread's captured event messages at `min_level` or more severe,
    /// recorded since the last [`begin_capture`] call on this thread.
    ///
    /// Why/What: see module docs above.
    pub(crate) fn captured_at_least(min_level: tracing::Level) -> Vec<String> {
        CAPTURED.with(|c| {
            c.borrow()
                .iter()
                .filter(|(level, _)| *level <= min_level)
                .map(|(_, msg)| msg.clone())
                .collect()
        })
    }
}

// #3036, #3195: keeps every spawned `tcode` child hermetic against the
// developer's live trusty-search daemon.
#[cfg(test)]
mod daemon_isolation_tests;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn version_is_non_empty() {
        // Why: guard against accidental blank version strings.
        // What: asserts that VERSION is not the empty string.
        // Test: this test itself.
        assert!(!VERSION.is_empty());
    }
}