trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
//! # trusty-mpm-mcp
//!
//! Why: Claude Code sessions (and their subagents) need to talk to the
//! trusty-mpm daemon directly — to enumerate sibling sessions, request agent
//! delegations, protect their own context window, inspect circuit-breaker
//! state, and (Phase 3) surface / preview / file captured bug reports.
//! MCP is the protocol Claude Code already speaks, so trusty-mpm exposes
//! an MCP server rather than inventing a bespoke channel.
//!
//! What: defines the full MCP tool catalog ([`tools::TOOL_CATALOG`], thirty-six
//! tools) — nine orchestration/bug-reporting (six core + three bug-reporting:
//! `list_recent_errors`, `preview_bug_report`, `report_bug`), eleven
//! session-lifecycle tools (#1221: `session_new`, `session_stop`,
//! `session_resume`, `session_decommission`, `session_activity`, `session_send`,
//! plus the PM pause/resume context tools `session_context_catchup` +
//! `session_context_pause` — a DIFFERENT concept from managed-sub-session
//! lifecycle, kept in the same tool group for file-count reasons only), five
//! console-facing tools, four project-registry tools, four session-manager
//! proxy tools, the Disk-dashboard survey (#6927), and `secrets_get_ref`
//! (#7522) — the [`OrchestratorBackend`] trait the daemon implements to
//! service them, and [`dispatch`], which routes a JSON-RPC [`Request`] to the
//! backend. The daemon wires [`dispatch`] into both `run_stdio_loop` (the `tm
//! daemon --mcp` path) and the loopback `POST /rpc` endpoint (the `serve
//! --stdio` bridge path).
//!
//! Test: `cargo test -p trusty-mpm` exercises the tool catalog, argument
//! parsing, and dispatch against an in-memory mock backend.
//!
//! [`tools::TOOL_CATALOG`]: crate::mcp::tools::TOOL_CATALOG
//! [`OrchestratorBackend`]: crate::mcp::OrchestratorBackend
//! [`dispatch`]: crate::mcp::dispatch
//! [`Request`]: trusty_mcp::Request

use async_trait::async_trait;
use serde_json::{Value, json};
use trusty_mcp::{Request, Response, error_codes};

pub mod project_dispatch;
pub mod proxy_dispatch;
pub mod session_dispatch;
pub mod tools;

pub use tools::{TOOL_CATALOG, tool_catalog};

/// Server identity reported in the MCP `initialize` handshake.
pub const SERVER_NAME: &str = "trusty-mpm";

/// Server version reported in the MCP `initialize` handshake.
pub const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Orchestration services the MCP layer exposes to Claude Code.
///
/// Why: the MCP crate must stay free of daemon internals (process spawning,
/// tmux, sockets) so it is unit-testable; the daemon supplies a concrete impl.
/// This is the Dependency Inversion seam between protocol and orchestration.
/// What: one async method per MCP tool. Each takes already-parsed arguments
/// and returns a JSON result or an error message. Phase 3 adds three
/// bug-reporting methods (`list_recent_errors`, `preview_bug_report`,
/// `report_bug`).
/// Test: `tests` module provides a `MockBackend` impl driven by `dispatch`.
#[async_trait]
pub trait OrchestratorBackend: Send + Sync {
    /// Back `session_list`: return a JSON array of session summaries.
    async fn session_list(&self) -> Result<Value, String>;

    /// Back `session_status`: return a detailed status object for `session_id`.
    async fn session_status(&self, session_id: &str) -> Result<Value, String>;

    /// Back `agent_delegate`: request a delegation to `agent` with `task`,
    /// optionally on an explicit model `tier`. Returns the new delegation id.
    async fn agent_delegate(
        &self,
        session_id: &str,
        agent: &str,
        task: &str,
        tier: Option<&str>,
    ) -> Result<Value, String>;

    /// Back `memory_protect`: report (and optionally act on) context-window
    /// pressure for `session_id` given `used`/`window` token counts.
    async fn memory_protect(
        &self,
        session_id: &str,
        used_tokens: u64,
        window_tokens: u64,
    ) -> Result<Value, String>;

    /// Back `circuit_breaker_status`: return the breaker state for `agent`
    /// (or all agents when `agent` is `None`).
    async fn circuit_breaker_status(&self, agent: Option<&str>) -> Result<Value, String>;

    /// Back `hook_event`: ingest a Claude Code hook event into the daemon's
    /// observability pipeline. Returns an acknowledgement.
    async fn hook_event(
        &self,
        session_id: &str,
        event: &str,
        payload: Value,
    ) -> Result<Value, String>;

    // ── Phase 3: bug-reporting tools ─────────────────────────────────────────

    /// Back `list_recent_errors`: return a JSON array of recently captured
    /// errors across all trusty-* daemon stores, deduplicated by fingerprint.
    ///
    /// Why: the user must be able to browse what errors have been captured
    ///      before deciding which ones to file.
    /// What: aggregates up to `limit` (default 20) errors from all known
    ///       daemon stores, returns them as a JSON array with summary info.
    /// Test: `dispatch_list_recent_errors_tool` in the `tests` module.
    async fn list_recent_errors(&self, limit: u64) -> Result<Value, String>;

    /// Back `preview_bug_report`: build and return the scrubbed issue preview
    /// for the given fingerprint without filing anything.
    ///
    /// Why: the user must review the exact scrubbed body before consenting.
    /// What: finds the error by fingerprint, runs the scrubber+preview builder,
    ///       returns the title, body, labels, and scrub-change log.
    /// Test: `dispatch_preview_bug_report_tool` in the `tests` module.
    async fn preview_bug_report(&self, fingerprint: &str) -> Result<Value, String>;

    /// Back `report_bug`: file or increment a GitHub issue.
    ///
    /// Why: the consent gate — nothing is filed without `confirm: true`.
    /// What: when `confirm` is `false`, returns a preview-only result (same as
    ///       `preview_bug_report`). When `true`, resolves the token, calls the
    ///       GitHub client, and returns `{ filed, deduped, issue_url,
    ///       issue_number }` or a graceful "no token" message.
    /// Test: `dispatch_report_bug_no_confirm_is_preview` in the `tests` module.
    async fn report_bug(&self, fingerprint: &str, confirm: bool) -> Result<Value, String>;

    // ── #6927: the Disk dashboard's worktree survey ──────────────────────────

    /// Back `disk_survey`: classify every managed worktree for the Disk view.
    ///
    /// Why: DOC-73 §16.4 — console reaches trusty-mpm through MCP only, and no
    /// tool exposed the merged-PR survey. This is READ-ONLY: it classifies and
    /// reports, and removes nothing.
    /// What: returns DOC-73 §16.5's tree — `generated_at`, the keep-list that
    /// was applied, and the workspace root's projects, each with its worktrees'
    /// bytes, tier and reasons. `project` scopes to one managed project;
    /// `budget_seconds` bounds classification, past which remaining worktrees
    /// are listed as `review` rather than omitted; it is clamped to the stdio
    /// bridge's forwarding timeout (#7313). `group_by` asks for the per-session
    /// roll-up (#7313) — `Some("session")`, or `None` for the tree alone.
    /// Test: `dispatch_disk_survey_tool` in the `tests` module.
    async fn disk_survey(
        &self,
        project: Option<&str>,
        budget_seconds: Option<u64>,
        group_by: Option<&str>,
    ) -> Result<Value, String>;

    // ── #7522: the reference-key secrets tool ────────────────────────────────

    /// Back `secrets_get_ref`: the `secret://` reference for `key` in `project`.
    ///
    /// Why: DOC-74 §10.2, ruling 34 — the model learns references, never
    /// values; the lookup runs on demand, with no session-start preload.
    /// What: a client of the trusty-secrets socket; returns
    /// `crate::secrets_client::RefAnswer` as JSON. `project` is an absolute
    /// directory; `key` is a key name or a `secret://` reference.
    /// Test: `dispatch_secrets_get_ref_tool` (mock) and
    /// `secrets_get_ref_reports_a_project_key_without_its_value` (daemon,
    /// real socket).
    async fn secrets_get_ref(&self, project: &str, key: &str) -> Result<Value, String>;

    // ── #1221: session-lifecycle tools ───────────────────────────────────────

    /// Back `session_new`: spawn a new managed session.
    ///
    /// Why: the driver skill needs a typed, JSON-native way to provision a
    ///      session workspace and launch a harness in it — without scraping
    ///      `tm session new` CLI text (the #842 defect).
    /// What: `repo_url` must be an ABSOLUTE path to a directory that already
    ///       exists on the daemon host — the session runs on that main checkout
    ///       itself, writing documents and configuration only (ADR-0037,
    ///       ADR-0044). A remote URL is an error: trusty-mpm clones nothing and
    ///       creates no worktree for a session (ADR-0055). This creates the tmux
    ///       host, launches the selected `runtime` (default claude-code) with
    ///       `task`, and returns the new session's id / tmux name / workspace
    ///       path / state / attach command. An unknown `runtime` value is an
    ///       error string.
    /// Test: `dispatch_session_new_tool` (mock) + the daemon-side
    ///       `session_new_spawns_via_manager` integration test; the ADR-0055
    ///       refusal by `mcp_session_new_refuses_a_remote_repo_url`.
    async fn session_new(
        &self,
        repo_url: &str,
        git_ref: &str,
        task: &str,
        name_hint: Option<&str>,
        runtime: Option<&str>,
        ephemeral: Option<bool>,
    ) -> Result<Value, String>;

    /// Back `session_stop`: stop a session's runtime, keeping its workspace.
    ///
    /// Why: a session endures beyond its running runtime; stopping must preserve
    ///      the workspace so the session can be resumed later.
    /// What: kills the tmux session + harness, marks the record Stopped, returns
    ///       the updated record summary. A missing id is an error string.
    /// Test: `dispatch_session_stop_tool` (mock).
    async fn session_stop(&self, session_id: &str) -> Result<Value, String>;

    /// Back `session_resume`: re-spawn the runtime in the existing workspace.
    ///
    /// Why: the counterpart to `session_stop` — bring a stopped session back
    ///      without re-cloning.
    /// What: re-creates the tmux host rooted at the on-disk workspace, re-spawns
    ///       the SAME runtime backend, and returns the updated record. A missing
    ///       id (or an invalid state transition) is an error string.
    /// Test: `dispatch_session_resume_tool` (mock).
    async fn session_resume(&self, session_id: &str) -> Result<Value, String>;

    /// Back `session_decommission`: full, terminal teardown.
    ///
    /// Why: the only operation that removes the workspace from disk; terminal so
    ///      a session can be fully reclaimed.
    /// What: kills the runtime, removes the workspace dir, marks the record
    ///       Decommissioned (a tombstone is kept), and returns it. A missing id
    ///       is an error string.
    /// Test: `dispatch_session_decommission_tool` (mock).
    async fn session_decommission(&self, session_id: &str) -> Result<Value, String>;

    /// Back `session_delete`: hard-delete the session RECORD (#2012).
    ///
    /// Why: distinct from `session_decommission` — that op stops the runtime and
    ///      may remove the workspace but ALWAYS leaves a `Decommissioned`
    ///      tombstone; this permanently drops the record itself via the existing
    ///      tombstone-compaction primitive, for an operator who wants a
    ///      mis-provisioned or stale record gone outright. Fail-closed: a RUNNING
    ///      session is refused unless `force` is true.
    /// What: parses the id, calls
    ///       [`crate::session_manager::SessionManager::delete_record`], and
    ///       returns the pre-deletion record as JSON (plus `deleted: true`). A
    ///       missing id is an error string; a running session refused without
    ///       `force` is an error string naming the actionable next step. NEVER
    ///       touches the workspace directory on disk (store-only operation).
    /// Test: `dispatch_session_delete_tool`,
    ///       `dispatch_session_delete_refuses_running_without_force` (mock).
    async fn session_delete(&self, session_id: &str, force: bool) -> Result<Value, String>;

    /// Back `session_delete_records`: record-only bulk deletion (#6431).
    ///
    /// Why: the console's Sessions tab buckets every record with a missing or
    ///      unrecognised `state` under "unknown" — in practice the daemon's
    ///      legacy in-memory registry entries, which carry `status` and no
    ///      `state` at all. Clearing that bucket needs ONE call that deletes a
    ///      RECORD from whichever registry owns each id. #1511 (a prune that
    ///      `rm -rf`'d a live workspace) is why this deletes records and never
    ///      touches a worktree, workspace, or any other filesystem state.
    /// What: takes an explicit id list — never a server-side filter, so the set
    ///       the operator confirmed is exactly the set that is deleted —
    ///       deduplicates it, and routes each id to `delete_record` (managed) or
    ///       the legacy registry drop. Fail-closed: a malformed id, an unknown
    ///       id, and a RUNNING managed session (refused, because a bulk action
    ///       never forces) are each ONE failed row, never counted as a deletion.
    ///       Returns `{ requested, deleted, failed, results }`.
    /// Test: `dispatch_session_delete_records_tool`,
    ///       `dispatch_session_delete_records_rejects_bad_arguments` (mock);
    ///       behaviour in `crate::daemon::mcp_session_bulk`'s tests.
    async fn session_delete_records(&self, session_ids: &[String]) -> Result<Value, String>;

    /// Back `session_activity`: capture pane + lifecycle state.
    ///
    /// Why: the driver must reason about whether a session is working / idle /
    ///      blocked WITHOUT requiring an LLM key, so raw pane content is always
    ///      returned and the LLM classification is an optional overlay.
    /// What: captures the last `lines` (default 60) pane lines, reports
    ///       `runtime_active` + pending-decision fields, and includes an LLM
    ///       `classification` when OPENROUTER_API_KEY is set. A missing id is an
    ///       error string.
    /// Test: `dispatch_session_activity_tool` (mock).
    async fn session_activity(&self, session_id: &str, lines: u32) -> Result<Value, String>;

    /// Back `session_send`: inject a line into a session's pane.
    ///
    /// Why: drive a running session (answer prompts, issue commands) without
    ///      attaching to the tmux pane.
    /// What: sends `text` followed by Enter to the session's pane and returns a
    ///       confirmation with the tmux name. A missing id is an error string.
    /// Test: `dispatch_session_send_tool` (mock).
    async fn session_send(&self, session_id: &str, text: &str) -> Result<Value, String>;

    // ── PM pause/resume context tools (DIFFERENT concept from the managed
    // sub-session lifecycle above — these operate on the CALLING PM session's
    // own project-local snapshot/catch-up state, not a spawned sub-session) ──

    /// Back `session_context_catchup`: a structured (JSON) resume digest.
    ///
    /// Why: `/tm-session-resume` used to shell out to `tm session catchup` +
    ///      `git log`/`git status` + snapshot-file reads to rebuild PM context;
    ///      this is the same three-source digest (paused sessions, git commits,
    ///      palace drawers) as typed JSON instead of scraped text. `project_dir`
    ///      is required because the `serve --stdio` bridge forwards no cwd/env —
    ///      the daemon cannot infer it.
    /// What: returns `{ sessions, recent_commits, recent_memory,
    ///       resolved_snapshot, resolved_via, watermark_advanced }`. This is a
    ///       manual PEEK — it NEVER advances the incremental-catchup watermark
    ///       (only automatic session-start injection does), so
    ///       `watermark_advanced` is always `false` and repeated calls are
    ///       always safe. `tmux_window` is the caller's own
    ///       `session_name:window_index:window_id`; it resolves a snapshot only
    ///       when `session_id` matched nothing, and `resolved_via` says which
    ///       of the two answered. #8408: `tmux_session_created` is the
    ///       caller's tmux `#{session_created}` (Unix seconds); without it the
    ///       tmux-session route resolves nothing. #5557: `sessions` is a
    ///       bounded PAGE starting at `sessions_offset`, and the response
    ///       carries `sessions_total` / `sessions_next_offset` / `truncated` /
    ///       `truncation_notice` so a short page can never read as a complete
    ///       one.
    /// Test: `dispatch_session_context_catchup_tool` (mock),
    ///       `dispatch_session_context_catchup_forwards_tmux_window`,
    ///       `dispatch_session_context_catchup_forwards_sessions_offset`.
    #[allow(clippy::too_many_arguments)]
    async fn session_context_catchup(
        &self,
        project_dir: &str,
        session_id: Option<&str>,
        tmux_window: Option<&str>,
        tmux_session_created: Option<i64>,
        all_projects: bool,
        full: bool,
        sessions_offset: usize,
    ) -> Result<Value, String>;

    /// Back `session_context_pause`: write a pause snapshot + prune worktrees.
    ///
    /// Why: `/tm-session-pause` used to shell out to write the
    ///      `session-*.md` snapshot and append the pause log line by hand; this
    ///      replaces that bash plumbing with an in-process writer that emits the
    ///      EXACT section shape the catch-up reader already parses.
    /// What: writes `<project_dir>/.trusty-mpm/sessions/session-<ts>.md`,
    ///       appends a `pause` line to `sessions-log.jsonl`, and — unless
    ///       `prune_worktrees` is `false` — prunes orphaned managed-session git
    ///       worktrees in-process (the same engine `tm session prune-worktrees`
    ///       uses, called directly rather than looped back over HTTP). Returns
    ///       `{ snapshot_path, timestamp, pruned_worktrees }`. Never touches
    ///       tmux (#8408: resume no longer realigns to the recorded window).
    ///
    /// #6888: `session_id` is optional. Omitted, the daemon derives it from the
    ///        caller's own identity — the same derivation
    ///        `session_context_catchup` runs — so the pause and the next resume
    ///        key the same string instead of two PM guesses. An explicit id is
    ///        honored unchanged.
    /// Test: `dispatch_session_context_pause_tool` (mock),
    ///       `dispatch_session_context_pause_allows_a_missing_session_id`.
    #[allow(clippy::too_many_arguments)]
    async fn session_context_pause(
        &self,
        project_dir: &str,
        session_id: Option<&str>,
        summary: &str,
        completed: Vec<String>,
        in_progress: Vec<String>,
        next_steps: Vec<String>,
        tmux_window: Option<&str>,
        prune_worktrees: bool,
    ) -> Result<Value, String>;

    // ── #1508: fleet-wide teardown tools ─────────────────────────────────────

    /// Back `session_decommission_ephemeral`: bulk-tear-down every ephemeral session.
    ///
    /// Why: e2e harnesses and drivers need a typed, JSON-native "clean up all my
    ///      throwaway test sessions" verb without scraping the CLI. REAL sessions
    ///      default `ephemeral=false` and are unreachable, so durable work is safe.
    /// What: decommissions every `ephemeral == true` session (kill runtime + remove
    ///       workspace + tombstone) and returns `{ decommissioned: <count> }`.
    /// Test: `dispatch_session_decommission_ephemeral_tool` (mock).
    async fn session_decommission_ephemeral(&self) -> Result<Value, String>;

    /// Back `session_prune`: by-state prune + tombstone compaction.
    ///
    /// Why: ONE fleet-wide tool to tear down ephemeral/stopped sessions AND compact
    ///      the store by dropping decommissioned tombstones, so legacy stale records
    ///      can be purged over MCP with the same engine that cleans up test sessions.
    /// What: parses `state` (`ephemeral`|`stopped`|`decommissioned`|`all`); a RUNNING
    ///       session is NEVER torn down unless `include_active`; with `dry_run`
    ///       NOTHING is mutated. Returns the `PruneOutcome` JSON. An unknown `state`
    ///       is an error string.
    /// Test: `dispatch_session_prune_tool`, `dispatch_session_prune_rejects_bad_state`
    ///       (mock).
    async fn session_prune(
        &self,
        state: &str,
        dry_run: bool,
        include_active: bool,
    ) -> Result<Value, String>;

    // ── #1222: console-facing tools ──────────────────────────────────────────

    /// Back `console_metrics`: the standard service-agnostic metrics report.
    ///
    /// Why: trusty-console polls every service's `console_metrics` tool uniformly
    ///      (#1104). trusty-mpm must speak the same contract so it renders in the
    ///      dashboard alongside search/memory/analyze/review.
    /// What: returns a serialised
    ///      [`trusty_common::console_metrics::ConsoleMetricsReport`] whose
    ///      `metrics` payload carries the fleet snapshot and auto-resume state.
    /// Test: `dispatch_console_metrics_tool` (mock).
    async fn console_metrics(&self) -> Result<Value, String>;

    /// Back `supervisor_status`: fleet snapshot + auto-resume control state.
    ///
    /// Why: the Sessions tab's supervisor widget needs lifecycle-state counts and
    ///      the auto-resume control state in one call.
    /// What: returns `{ fleet, auto_resume }`.
    /// Test: `dispatch_supervisor_status_tool` (mock).
    async fn supervisor_status(&self) -> Result<Value, String>;

    /// Back `auto_resume_set`: persist the operator's desired auto-resume flag.
    ///
    /// Why: the console toggle must durably set auto-resume without the CLI
    ///      (RFC §6 Q6). The supervisor reads the persisted flag on its next sweep.
    /// What: writes the desired flag and echoes `{ desired, env,
    ///      pending_restart }`.
    /// Test: `dispatch_auto_resume_set_tool` (mock).
    async fn auto_resume_set(&self, enabled: bool) -> Result<Value, String>;

    // ── #1220: config-convention tools ───────────────────────────────────────

    /// Back `config_read`: return trusty-mpm's `~/.trusty-tools/trusty-mpm/config.yaml`.
    ///
    /// Why: the console Config tab (#1220) edits the cross-crate config convention;
    ///      it first reads the current settings to render the form.
    /// What: returns `{ workspace_root_template, auto_resume, default_model }` (each
    ///      possibly null) plus the resolved absolute `workspace_root` so the UI can
    ///      show the effective path. An absent file yields the defaults.
    /// Test: `dispatch_config_read_tool` (mock).
    async fn config_read(&self) -> Result<Value, String>;

    /// Back `config_write`: persist edits to the config-convention file.
    ///
    /// Why: the console Config tab's save action durably records the operator's
    ///      workspace-root / auto-resume / default-model choices (#1220), and —
    ///      since #2184 — the global GitHub identity binding plus per-project
    ///      GitHub/commit identity overrides, all MCP-settable without
    ///      hand-editing YAML.
    /// What: merges the supplied fields onto the current config (omitted fields
    ///      unchanged), writes `~/.trusty-tools/trusty-mpm/config.yaml`, and returns
    ///      the merged config that was persisted. `project_name` routes the
    ///      `github_*`/`commit_*` fields to that `config.projects` entry instead of
    ///      the global `github:` section; omitting it targets the global section
    ///      (commit identity has no global tier — supplying `commit_name`/
    ///      `commit_email` with no `project_name` is an error). `untracked_sync_*`
    ///      (#2196) sets the untracked/secret-file sync allowlist and follows the
    ///      SAME `project_name` routing as `github_*` (it DOES have a global tier,
    ///      unlike commit identity).
    /// Test: `dispatch_config_write_tool` (mock).
    #[allow(clippy::too_many_arguments)]
    async fn config_write(
        &self,
        workspace_root_template: Option<&str>,
        auto_resume: Option<bool>,
        default_model: Option<&str>,
        project_name: Option<&str>,
        github_config_dir: Option<&str>,
        github_token_env: Option<&str>,
        github_account: Option<&str>,
        github_host: Option<&str>,
        commit_name: Option<&str>,
        commit_email: Option<&str>,
        untracked_sync_patterns: Option<Vec<String>>,
        untracked_sync_enabled: Option<bool>,
    ) -> Result<Value, String>;

    // ── #1519 WI-2: project-registry tools ───────────────────────────────────

    /// Back `project_list`: return a JSON array of all registered projects.
    ///
    /// Why: the driver skill and operators need a typed list of known projects
    ///      to pick a repository for a new session without specifying the URL
    ///      every time.
    /// What: lists all entries in the project registry and returns them as a
    ///      JSON array. An empty registry returns `[]`.
    /// Test: `dispatch_project_list_tool` (mock).
    async fn project_list(&self) -> Result<Value, String>;

    /// Back `project_register`: upsert a project entry in the registry.
    ///
    /// Why: operators and the driver skill must be able to add or update a
    ///      project without restarting the daemon or editing config.yaml.
    ///      Registration is idempotent — calling with the same `name` updates
    ///      the entry rather than duplicating it. `gh_user` (#2081) lets an
    ///      operator declare the project's preferred `gh` account so callers
    ///      can scope `gh` operations to it without a per-session reminder.
    ///      `gh_account` (#3025) separately pins the account resolved into
    ///      `GH_TOKEN`/`GH_USER` at every session spawn/relaunch.
    /// What: upserts the project keyed by `name` and returns the persisted
    ///      project record as JSON.
    /// Test: `dispatch_project_register_tool`,
    ///       `dispatch_project_register_requires_name` (mock).
    #[allow(clippy::too_many_arguments)]
    async fn project_register(
        &self,
        name: &str,
        repo_url: &str,
        default_branch: Option<&str>,
        stack_hint: Option<&str>,
        tags: Option<Vec<String>>,
        description: Option<&str>,
        gh_user: Option<&str>,
        gh_account: Option<&str>,
    ) -> Result<Value, String>;

    /// Back `project_get`: look up a single project by name.
    ///
    /// Why: the driver skill needs a point-lookup to retrieve a project's
    ///      `repo_url` and `default_branch` before spawning a session without
    ///      listing all projects first.
    /// What: returns the project record as JSON or a descriptive error when
    ///      the name is not in the registry.
    /// Test: `dispatch_project_get_tool`,
    ///       `dispatch_project_get_missing_name` (mock).
    async fn project_get(&self, name: &str) -> Result<Value, String>;

    /// Back `project_resolve`: resolve a NL query to the best-matching project.
    ///
    /// Why: operators and driver skills need to route free-text task descriptions,
    ///      GitHub URLs, ticket IDs, and keywords to the correct registered project
    ///      without knowing exact names or URLs.
    /// What: runs the NL→project resolver over all registered projects, returning
    ///      the primary match, confidence score, reason, all candidates, and a
    ///      `needs_disambiguation` flag.
    /// Test: `dispatch_project_resolve_tool` (mock).
    async fn project_resolve(&self, query: &str) -> Result<Value, String>;

    // ── #2550: session-manager PROXY tools (#1440 follow-up) ─────────────────
    //
    // These expose the channel-agnostic [`crate::client::proxy::SessionProxy`]
    // focus/inject/summarize state machine — already reachable over Telegram and
    // the daemon's local HTTP routes — as a fourth surface: MCP tools. Every
    // method takes an explicit `conversation_key`: the MCP `dispatch` entry point
    // is stateless (no per-connection identity is threaded through it, unlike
    // Telegram's `chat_id` or an HTTP request), so the caller supplies the key,
    // exactly as the HTTP proxy routes' `conversation_key` body field does. The
    // daemon impl keys focus into the SAME `DaemonState::proxy_focus_store`, so a
    // focus set over MCP is visible to the HTTP/Telegram surfaces under the same
    // key and vice versa.

    /// Back `session_proxy_focus`: focus (or query) a session for a conversation.
    ///
    /// Why: the "session click" of the proxy model as an MCP verb — bind a
    /// conversation to ONE managed session so later `session_proxy_message`s route
    /// to it without a per-turn id.
    /// What: with a non-empty `session_id` (id, friendly name, or unambiguous
    /// prefix) validates + records the focus; with an empty `session_id` performs
    /// a read-only query of the current focus without touching the backend.
    /// Returns the tagged proxy focus outcome as JSON.
    /// Test: `dispatch_session_proxy_focus_tool` (mock) + the daemon-side
    /// `mcp_proxy` round-trip test against a real `SessionProxy`.
    async fn session_proxy_focus(
        &self,
        conversation_key: &str,
        session_id: &str,
    ) -> Result<Value, String>;

    /// Back `session_proxy_unfocus`: clear a conversation's focus.
    ///
    /// Why: the "back to fleet chat" action — drop the conversation's binding so
    /// later free text no longer injects.
    /// What: clears the focus for `conversation_key`, reporting the session that
    /// was cleared (or `null`). Never an error — unfocusing an unfocused
    /// conversation is a harmless no-op.
    /// Test: `dispatch_session_proxy_unfocus_tool` (mock) + the `mcp_proxy` test.
    async fn session_proxy_unfocus(&self, conversation_key: &str) -> Result<Value, String>;

    /// Back `session_proxy_message`: INJECT free text into the focused session.
    ///
    /// Why: the payoff of focus — a plain message becomes a `send` at the focused
    /// session. A vanished session auto-unfocuses; a transient failure preserves
    /// focus; no focus returns a `no_focus` outcome so the caller can fall back to
    /// its own handling instead of receiving an error.
    /// What: injects `text` into the conversation's focused session and returns the
    /// tagged inject outcome (`sent` / `auto_unfocused` / `failed` / `no_focus`).
    /// Test: `dispatch_session_proxy_message_tool` (mock) + the `mcp_proxy` test.
    async fn session_proxy_message(
        &self,
        conversation_key: &str,
        text: &str,
    ) -> Result<Value, String>;

    /// Back `session_proxy_summary`: SUMMARIZE the focused session's activity.
    ///
    /// Why: the second proxy direction — "what is my focused session doing?" —
    /// without attaching to tmux.
    /// What: returns a lightweight activity digest of the conversation's focused
    /// session as the tagged summarize outcome (`summary` / `auto_unfocused` /
    /// `failed` / `no_focus`).
    /// Test: `dispatch_session_proxy_summary_tool` (mock) + the `mcp_proxy` test.
    async fn session_proxy_summary(&self, conversation_key: &str) -> Result<Value, String>;
}

/// Route a JSON-RPC request to the backend, returning the MCP response.
///
/// Why: the daemon's stdio loop needs one entry point that handles the MCP
/// handshake (`initialize`), tool discovery (`tools/list`), and tool calls
/// (`tools/call`) uniformly.
/// What: matches on `req.method`; for `tools/call` it extracts the tool name
/// and `arguments` object and forwards to the matching backend method.
/// Notifications (no id) are suppressed per JSON-RPC.
/// Test: `dispatch_*` tests cover initialize, listing, each tool, and errors.
pub async fn dispatch<B: OrchestratorBackend>(backend: &B, req: Request) -> Response {
    let id = req.id.clone();

    match req.method.as_str() {
        "initialize" => Response::ok(
            id,
            trusty_mcp::initialize_response(SERVER_NAME, SERVER_VERSION, None),
        ),
        "tools/list" => Response::ok(id, json!({ "tools": tool_catalog() })),
        "tools/call" => dispatch_tool_call(backend, id, req.params).await,
        "ping" => Response::ok(id, json!({})),
        // Notifications carry no id and must not produce a reply.
        _ if id.is_none() => Response::suppressed(),
        other => Response::err(
            id,
            error_codes::METHOD_NOT_FOUND,
            format!("unknown method: {other}"),
        ),
    }
}

/// Handle a `tools/call` request: pick the tool, parse args, call the backend.
async fn dispatch_tool_call<B: OrchestratorBackend>(
    backend: &B,
    id: Option<Value>,
    params: Option<Value>,
) -> Response {
    let params = params.unwrap_or(Value::Null);
    let name = match params.get("name").and_then(Value::as_str) {
        Some(n) => n,
        None => {
            return Response::err(
                id,
                error_codes::INVALID_PARAMS,
                "tools/call requires a `name` field",
            );
        }
    };
    let args = params
        .get("arguments")
        .cloned()
        .unwrap_or_else(|| json!({}));

    let result = match name {
        "session_list" => backend.session_list().await,
        "session_status" => match required_str(&args, "session_id") {
            Ok(sid) => backend.session_status(&sid).await,
            Err(e) => Err(e),
        },
        "agent_delegate" => {
            match (
                required_str(&args, "session_id"),
                required_str(&args, "agent"),
                required_str(&args, "task"),
            ) {
                (Ok(sid), Ok(agent), Ok(task)) => {
                    let tier = args.get("tier").and_then(Value::as_str);
                    backend.agent_delegate(&sid, &agent, &task, tier).await
                }
                (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => Err(e),
            }
        }
        "memory_protect" => {
            match (
                required_str(&args, "session_id"),
                required_u64(&args, "used_tokens"),
                required_u64(&args, "window_tokens"),
            ) {
                (Ok(sid), Ok(used), Ok(window)) => backend.memory_protect(&sid, used, window).await,
                (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => Err(e),
            }
        }
        "circuit_breaker_status" => {
            let agent = args.get("agent").and_then(Value::as_str);
            backend.circuit_breaker_status(agent).await
        }
        "hook_event" => {
            match (
                required_str(&args, "session_id"),
                required_str(&args, "event"),
            ) {
                (Ok(sid), Ok(event)) => {
                    let payload = args.get("payload").cloned().unwrap_or(Value::Null);
                    backend.hook_event(&sid, &event, payload).await
                }
                (Err(e), _) | (_, Err(e)) => Err(e),
            }
        }
        // ── Phase 3: bug-reporting tools ─────────────────────────────────────
        "list_recent_errors" => {
            let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(20);
            backend.list_recent_errors(limit).await
        }
        "preview_bug_report" => match required_str(&args, "fingerprint") {
            Ok(fp) => backend.preview_bug_report(&fp).await,
            Err(e) => Err(e),
        },
        "report_bug" => match required_str(&args, "fingerprint") {
            Ok(fp) => {
                let confirm = args
                    .get("confirm")
                    .and_then(Value::as_bool)
                    .unwrap_or(false);
                backend.report_bug(&fp, confirm).await
            }
            Err(e) => Err(e),
        },
        // ── #6927: the Disk dashboard's survey ───────────────────────────────
        "disk_survey" => {
            let project = args.get("project").and_then(Value::as_str);
            let budget_seconds = args.get("budget_seconds").and_then(Value::as_u64);
            // #7313: the per-session roll-up, opt-in so an existing consumer's
            // payload is unchanged.
            let group_by = args.get("group_by").and_then(Value::as_str);
            backend.disk_survey(project, budget_seconds, group_by).await
        }
        // #7522: references only, resolved on demand.
        "secrets_get_ref" => match (required_str(&args, "project"), required_str(&args, "key")) {
            (Ok(project), Ok(key)) => backend.secrets_get_ref(&project, &key).await,
            (Err(e), _) | (_, Err(e)) => Err(e),
        },
        // ── #1222: console-facing tools ──────────────────────────────────────
        "console_metrics" => backend.console_metrics().await,
        "supervisor_status" => backend.supervisor_status().await,
        "auto_resume_set" => match args.get("enabled").and_then(Value::as_bool) {
            Some(enabled) => backend.auto_resume_set(enabled).await,
            None => Err("missing required boolean argument: `enabled`".to_string()),
        },
        // ── #1220: config-convention tools ────────────────────────────────────
        "config_read" => backend.config_read().await,
        "config_write" => {
            let template = args.get("workspace_root_template").and_then(Value::as_str);
            let auto_resume = args.get("auto_resume").and_then(Value::as_bool);
            let default_model = args.get("default_model").and_then(Value::as_str);
            let project_name = args.get("project_name").and_then(Value::as_str);
            let github_config_dir = args.get("github_config_dir").and_then(Value::as_str);
            let github_token_env = args.get("github_token_env").and_then(Value::as_str);
            let github_account = args.get("github_account").and_then(Value::as_str);
            let github_host = args.get("github_host").and_then(Value::as_str);
            let commit_name = args.get("commit_name").and_then(Value::as_str);
            let commit_email = args.get("commit_email").and_then(Value::as_str);
            let untracked_sync_patterns = args.get("untracked_sync_patterns").and_then(|v| {
                v.as_array().map(|arr| {
                    arr.iter()
                        .filter_map(|p| p.as_str().map(str::to_string))
                        .collect::<Vec<String>>()
                })
            });
            let untracked_sync_enabled =
                args.get("untracked_sync_enabled").and_then(Value::as_bool);
            backend
                .config_write(
                    template,
                    auto_resume,
                    default_model,
                    project_name,
                    github_config_dir,
                    github_token_env,
                    github_account,
                    github_host,
                    commit_name,
                    commit_email,
                    untracked_sync_patterns,
                    untracked_sync_enabled,
                )
                .await
        }
        // #1519 WI-2: the three project-registry tools route through a sibling
        // module before the session tools so both groups can extend independently.
        other => match project_dispatch::try_dispatch(backend, other, &args).await {
            Some(result) => result,
            // #1221 + #1508: the eight session-lifecycle tools route through a sibling
            // module so this match stays focused and `mod.rs` stays under the SLOC cap.
            None => match session_dispatch::try_dispatch(backend, other, &args).await {
                Some(result) => result,
                // #2550: the four session-manager PROXY tools route through their
                // own sibling module, keeping this match and `mod.rs` small.
                None => match proxy_dispatch::try_dispatch(backend, other, &args).await {
                    Some(result) => result,
                    None => Err(format!("unknown tool: {other}")),
                },
            },
        },
    };

    match result {
        // MCP wraps tool results in a `content` array of typed blocks.
        Ok(value) => Response::ok(
            id,
            json!({
                "content": [{ "type": "text", "text": value.to_string() }],
                "isError": false,
            }),
        ),
        Err(message) => Response::ok(
            id,
            json!({
                "content": [{ "type": "text", "text": message }],
                "isError": true,
            }),
        ),
    }
}

/// Extract a required string argument or produce a descriptive error.
pub(crate) fn required_str(args: &Value, key: &str) -> Result<String, String> {
    args.get(key)
        .and_then(Value::as_str)
        .map(str::to_string)
        .ok_or_else(|| format!("missing required string argument: `{key}`"))
}

/// Extract a required NON-EMPTY array-of-strings argument (#6431).
///
/// Why: `session_delete_records` is destructive, so a caller that sends the
/// wrong shape — a bare string, an empty array, an array with a non-string in
/// it — must get a clear error instead of a silent no-op or a partial delete of
/// whatever happened to parse.
/// What: `Ok(Vec<String>)` when `key` is an array of at least one element and
/// EVERY element is a string; a descriptive error otherwise.
/// Test: `dispatch_session_delete_records_rejects_bad_arguments` in `tests.rs`,
/// which drives every rejected shape — missing, empty, bare string, and an
/// array with a non-string element.
pub(crate) fn required_str_array(args: &Value, key: &str) -> Result<Vec<String>, String> {
    let items = args
        .get(key)
        .and_then(Value::as_array)
        .ok_or_else(|| format!("missing required array argument: `{key}`"))?;
    if items.is_empty() {
        return Err(format!("`{key}` must name at least one session"));
    }
    items
        .iter()
        .map(|v| {
            v.as_str()
                .map(str::to_string)
                .ok_or_else(|| format!("`{key}` must contain only strings"))
        })
        .collect()
}

/// Extract a required unsigned-integer argument or produce a descriptive error.
fn required_u64(args: &Value, key: &str) -> Result<u64, String> {
    args.get(key)
        .and_then(Value::as_u64)
        .ok_or_else(|| format!("missing required integer argument: `{key}`"))
}

#[cfg(test)]
#[path = "tests.rs"]
mod tests;