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
//! Daemon-side implementation of the MCP orchestration backend.
//!
//! Why: `trusty-mpm-mcp` defines the `OrchestratorBackend` trait but no
//! behaviour — the protocol crate is deliberately ignorant of daemon state.
//! This module is the Anti-Corruption Layer that translates MCP tool calls
//! into mutations on [`DaemonState`], so Claude Code sessions can drive the
//! orchestrator without reaching into its internals.
//! What: [`StateBackend`] wraps `Arc<DaemonState>` and implements every
//! `OrchestratorBackend` method by reading/writing the shared state.
//! Test: `cargo test -p trusty-mpm-daemon` calls each backend method against a
//! freshly-built state and asserts the JSON results.

use std::sync::Arc;

use crate::core::agent::{Delegation, ModelTier};
use crate::core::hook::{HookEvent, HookEventRecord};
use crate::core::memory::MemoryUsage;
use crate::core::session::SessionId;
use crate::mcp::OrchestratorBackend;
use crate::session_manager::record::ManagedSessionId;
use async_trait::async_trait;
use serde_json::{Value, json};
use uuid::Uuid;

use super::{session_record_kind::SessionRecordKind, state::DaemonState};

/// MCP backend backed by the daemon's shared state.
///
/// Why: a thin adapter keeps the protocol crate and the state crate decoupled
/// — either can be tested without the other.
/// What: holds an `Arc<DaemonState>` clone; cheap to construct per connection.
/// Test: see the module tests.
#[derive(Clone)]
pub struct StateBackend {
    state: Arc<DaemonState>,
    /// #7522: the trusty-secrets client `secrets_get_ref` dials; `None` is
    /// the process-wide default socket.
    #[cfg(unix)]
    secrets: Option<Arc<trusty_secrets::server::OnDemandSecrets>>,
}

impl StateBackend {
    /// Build a backend over shared daemon state.
    pub fn new(state: Arc<DaemonState>) -> Self {
        Self {
            state,
            #[cfg(unix)]
            secrets: None,
        }
    }

    /// Dial `client` instead of the default trusty-secrets socket (#7522).
    ///
    /// Test: `secrets_get_ref_reports_a_project_key_without_its_value`.
    #[cfg(unix)]
    #[must_use]
    pub fn with_secrets_client(
        mut self,
        client: Arc<trusty_secrets::server::OnDemandSecrets>,
    ) -> Self {
        self.secrets = Some(client);
        self
    }
}

/// Parse a session-id string into a `SessionId`, mapping failure to a message.
fn parse_session_id(raw: &str) -> Result<SessionId, String> {
    Uuid::parse_str(raw)
        .map(SessionId)
        .map_err(|_| format!("`{raw}` is not a valid session id (expected a UUID)"))
}

#[async_trait]
impl OrchestratorBackend for StateBackend {
    /// Return every session — legacy AND managed — as a JSON array.
    ///
    /// Why: a session provisioned via the managed path (`session_new` /
    /// `spawn_managed` / the in-project worktree spawn — the tm day-to-day path)
    /// lives in the [`crate::session_manager::SessionManager`] store, NOT the
    /// legacy `DaemonState` registry. The sibling `session_stop` / `session_resume`
    /// tools already target that store by id, so listing only the legacy registry
    /// left provisioned sessions invisible: the operator could never discover the
    /// id needed to stop the session they are in (#1946).
    /// What: unions the legacy `DaemonState.sessions` (native-process discovery,
    /// hook auto-register, `POST /sessions` bookkeeping — tagged `kind: "legacy"`)
    /// with every `SessionManager` record (tagged `kind: "managed"`, serialized via
    /// the shared [`crate::daemon::managed_routes::record_to_json`] so callers get
    /// the managed id + `workspace_path`/`cwd` used to target `session_stop`).
    /// Test: `session_list_returns_registered_sessions` (legacy path) and
    /// `session_list_includes_managed_sessions` (#1946 regression) in `tests`.
    async fn session_list(&self) -> Result<Value, String> {
        let mut items: Vec<Value> = Vec::new();
        // Legacy in-memory registry: native-process discovery, hook
        // auto-registration, and `POST /sessions` bookkeeping.
        for session in &self.state.list_sessions() {
            let mut value = serde_json::to_value(session).map_err(|e| e.to_string())?;
            if let Value::Object(map) = &mut value {
                map.insert("kind".into(), SessionRecordKind::Legacy.as_str().into());
            }
            items.push(value);
        }
        // Managed store: the sessions `session_stop`/`session_resume` can target.
        let manager = self.state.session_manager().await;
        for record in manager.list().await {
            let mut value = crate::daemon::managed_routes::record_to_json(&record);
            if let Value::Object(map) = &mut value {
                map.insert("kind".into(), SessionRecordKind::Managed.as_str().into());
            }
            items.push(value);
        }
        Ok(Value::Array(items))
    }

    /// Return one session plus its memory snapshot and delegation count.
    ///
    /// Resolves BOTH session families (#1976): the legacy in-process
    /// `DaemonState` registry first, then — on a miss — the managed
    /// `SessionManager` store. Without the managed fallback, `session_status`
    /// reported "no such session" for the `tmpm-` sessions trusty-mpm itself
    /// spawns, even though `session_list` surfaces them. Managed records are
    /// serialized via the shared `record_to_json` (matching `session_list`) and
    /// carry no memory snapshot.
    ///
    /// # Delegation lookup (#4141)
    ///
    /// Delegations live in up to TWO key spaces. `agent_delegate` (#1976) keys
    /// a delegation by whatever session id the CALLER passed — for a managed
    /// session that is the MANAGED id itself (exercised over `/rpc` by
    /// `connectors::tm::WorkstreamConnector::delegate`, certified by
    /// `agent_delegate_accepts_managed_session` in `mcp_backend_tests.rs`).
    /// Hook-observed delegations (`delegation_tracker::observe`) are instead
    /// keyed by the Claude session UUID, reachable from a managed record only
    /// by bridging through `record.claude_session_id` (populated by
    /// `session_start_correlation::correlate_session_start`). Replacing the
    /// managed-id read with the bridged one — instead of unioning both —
    /// silently drops every `agent_delegate`-keyed record: the exact
    /// false-all-clear #4141 exists to eliminate, just relocated to the other
    /// key. The managed branch below reads BOTH spaces and de-duplicates by
    /// delegation id — but that only removes an exact record appearing
    /// twice, e.g. the same `Delegation` reachable under both the managed id
    /// and the Claude UUID. It does NOT merge a PM's `agent_delegate` call
    /// (managed-id record) with the hook-observed dispatch of the SAME
    /// logical subagent (Claude-UUID record): those are two distinct
    /// `Delegation`s with different ids and `delegation_tracker::dedup` only
    /// matches within one session/agent pairing, so it cannot span the
    /// bridge. `delegation_count` can therefore overcount one in-flight
    /// subagent as two — this is the existing, deliberate tracker trade-off
    /// (favouring overcount over a false merge, per `dedup`'s own doc
    /// comment), not new behaviour this fix introduces or is meant to close.
    ///
    /// The legacy branch's `id` equals the Claude session UUID only on the
    /// `SessionStart`-hook-auto-registered path; a tmux-pane-discovered,
    /// native-process-discovered, or `POST /sessions`-registered legacy
    /// session instead gets a freshly minted `SessionId` never correlated to
    /// anything, so `delegations_for(id)` can under-report there too. No
    /// marker distinguishes those three registration paths at this call site,
    /// so the legacy branch omits `delegation_lookup` rather than assert an
    /// `"ok"` it cannot establish for every path (that pre-existing gap is
    /// tracked separately from this fix).
    ///
    /// When the managed bridge itself is missing (no correlated Claude
    /// session id yet), `delegation_count` AND `delegations` are both an
    /// explicit `null` with `delegation_lookup: "unbridged"` — the managed-id
    /// half alone would be a floor masquerading as a total, so neither field
    /// may be read as a confident (even if empty) answer.
    async fn session_status(&self, session_id: &str) -> Result<Value, String> {
        let id = parse_session_id(session_id)?;
        // Legacy in-process registry first.
        if let Some(session) = self.state.session(id) {
            let memory = self.state.memory_for(id);
            let delegations = self.state.delegations_for(id);
            return Ok(json!({
                "session": session,
                "kind": SessionRecordKind::Legacy.as_str(),
                "memory": memory,
                "delegation_count": delegations.len(),
                "delegations": delegations,
            }));
        }
        // Managed store fallback (#1976): the `tmpm-` sessions `session_list`
        // surfaces and `session_stop`/`session_resume` already target by id.
        let manager = self.state.session_manager().await;
        if let Ok(record) = manager.get(&ManagedSessionId(id.0)).await {
            // #4141: read the managed-id key space unconditionally — this is
            // what `agent_delegate` (#1976) writes under for a managed
            // session — then union in the Claude-UUID key space when the
            // bridge resolves, de-duplicating by delegation id (removes an
            // exact record reachable under both keys; does NOT merge a
            // managed-id `agent_delegate` record with a separate
            // Claude-UUID hook-observed record for the same logical
            // subagent — see the doc comment above).
            let mut delegations = self.state.delegations_for(id);
            let claude_uuid = record
                .claude_session_id
                .as_deref()
                .and_then(|s| Uuid::parse_str(s).ok());
            let (delegation_count, delegations_value, lookup) = match claude_uuid {
                Some(uuid) => {
                    for d in self.state.delegations_for(SessionId(uuid)) {
                        if !delegations.iter().any(|existing| existing.id == d.id) {
                            delegations.push(d);
                        }
                    }
                    (json!(delegations.len()), json!(delegations), "ok")
                }
                // The hook-observed half is unreachable without the bridge,
                // so the managed-id half alone cannot stand in for the
                // total — report the explicit unknown for BOTH fields
                // rather than let a caller reading only `delegations` see a
                // confident empty list.
                None => (Value::Null, Value::Null, "unbridged"),
            };
            return Ok(json!({
                "session": crate::daemon::managed_routes::record_to_json(&record),
                "kind": SessionRecordKind::Managed.as_str(),
                "memory": Value::Null,
                "delegation_count": delegation_count,
                "delegations": delegations_value,
                "delegation_lookup": lookup,
            }));
        }
        Err(format!("no such session: {session_id}"))
    }

    /// Gate and record a new agent delegation.
    ///
    /// The circuit breaker is consulted first: an open breaker refuses the
    /// delegation with an explanatory error instead of silently queueing it.
    async fn agent_delegate(
        &self,
        session_id: &str,
        agent: &str,
        task: &str,
        tier: Option<&str>,
    ) -> Result<Value, String> {
        let id = parse_session_id(session_id)?;
        // Accept BOTH session families (#1976): the gating registry historically
        // only knew the legacy in-process registry, so delegations from the
        // managed (`tmpm-`) sessions trusty-mpm itself spawns were rejected
        // outright. Fall back to the managed store on a legacy miss. The
        // delegation is keyed by UUID, so tracking works for either family.
        let known = self.state.session(id).is_some()
            || self
                .state
                .session_manager()
                .await
                .get(&ManagedSessionId(id.0))
                .await
                .is_ok();
        if !known {
            return Err(format!("no such session: {session_id}"));
        }
        let breaker = self.state.breaker(agent);
        if !breaker.allows_delegation() {
            return Err(format!(
                "circuit breaker for agent `{agent}` is {:?}; delegation refused",
                breaker.state
            ));
        }
        let tier = match tier {
            Some("haiku") => ModelTier::Haiku,
            Some("sonnet") => ModelTier::Sonnet,
            Some("opus") => ModelTier::Opus,
            Some(other) => return Err(format!("unknown model tier: `{other}`")),
            None => ModelTier::Sonnet,
        };
        let delegation = Delegation::new(id, None, agent, tier, task);
        let delegation_id = delegation.id;
        self.state.upsert_delegation(delegation);
        Ok(json!({
            "delegation_id": delegation_id.0,
            "agent": agent,
            "tier": tier,
            "circuit": breaker.state,
        }))
    }

    /// Record token usage and report the resulting memory pressure.
    async fn memory_protect(
        &self,
        session_id: &str,
        used_tokens: u64,
        window_tokens: u64,
    ) -> Result<Value, String> {
        let id = parse_session_id(session_id)?;
        if window_tokens == 0 {
            return Err("window_tokens must be greater than zero".into());
        }
        let usage = MemoryUsage {
            used_tokens,
            window_tokens,
        };
        let pressure = self.state.record_memory(id, usage);
        Ok(json!({
            "fraction": usage.fraction(),
            "pressure": pressure,
            "config": self.state.memory_config,
        }))
    }

    /// Return one or all agents' circuit-breaker states.
    async fn circuit_breaker_status(&self, agent: Option<&str>) -> Result<Value, String> {
        match agent {
            Some(name) => {
                let cb = self.state.breaker(name);
                Ok(json!({ "agent": name, "breaker": cb }))
            }
            None => {
                let all: Vec<Value> = self
                    .state
                    .all_breakers()
                    .into_iter()
                    .map(|(name, cb)| json!({ "agent": name, "breaker": cb }))
                    .collect();
                Ok(json!({ "breakers": all }))
            }
        }
    }

    /// Ingest a Claude Code hook event into the observability ring buffer.
    ///
    /// Subagent-stop events additionally feed the agent's circuit breaker so
    /// repeated failures trip it: a `SubagentStopFailure` is a failure, a plain
    /// `SubagentStop` a success. The agent name is read from the payload's
    /// `agent` field when present.
    async fn hook_event(
        &self,
        session_id: &str,
        event: &str,
        payload: Value,
    ) -> Result<Value, String> {
        let id = parse_session_id(session_id)?;
        let parsed =
            HookEvent::from_wire(event).ok_or_else(|| format!("unknown hook event: `{event}`"))?;

        // Drive the circuit breaker from subagent lifecycle events.
        if let Some(agent) = payload.get("agent").and_then(Value::as_str) {
            match parsed {
                HookEvent::SubagentStop => self.state.record_outcome(agent, true),
                HookEvent::SubagentStopFailure => self.state.record_outcome(agent, false),
                _ => {}
            }
        }

        // Compress PostToolUse output before it enters the ring buffer.
        let mut payload = payload;
        if parsed == HookEvent::PostToolUse {
            let tool_name = payload
                .get("tool")
                .and_then(Value::as_str)
                .unwrap_or("unknown")
                .to_string();
            let cfg = self.state.optimizer_config();
            super::optimizer::optimize_tool_output(&cfg, &tool_name, &mut payload);
        }

        self.state
            .push_hook_event(HookEventRecord::now(id, parsed, payload));
        Ok(json!({ "received": event, "session_id": session_id }))
    }

    /// Return recent captured errors across all known daemon stores.
    ///
    /// Why: aggregates errors from trusty-search, trusty-memory, trusty-analyze,
    ///      and trusty-mpm JSONL stores so the MCP user sees a unified view. The
    ///      body lives in `super::mcp_bugreport` (a thin wrapper, matching the
    ///      `mcp_session`/`mcp_console`/`mcp_project` sibling-module convention)
    ///      to keep this file under the 500-SLOC cap.
    /// What: delegates to [`super::mcp_bugreport::list_recent_errors`].
    /// Test: `list_recent_errors_returns_valid_json` in the `tests` module.
    async fn list_recent_errors(&self, limit: u64) -> Result<Value, String> {
        super::mcp_bugreport::list_recent_errors(limit).await
    }

    /// Build and return the scrubbed issue preview for the given fingerprint.
    ///
    /// Why: the user must review the exact body that will be filed before
    ///      consenting. The preview IS the filed body — no transformation happens
    ///      between preview and filing.
    /// What: delegates to [`super::mcp_bugreport::preview_bug_report`].
    /// Test: `preview_bug_report_unknown_fingerprint_errors` in the `tests` module.
    async fn preview_bug_report(&self, fingerprint: &str) -> Result<Value, String> {
        super::mcp_bugreport::preview_bug_report(fingerprint).await
    }

    /// File or increment a GitHub issue for the given fingerprint.
    ///
    /// Why: the consent gate — nothing is filed unless `confirm` is `true`.
    /// What: delegates to [`super::mcp_bugreport::report_bug`], which resolves
    ///       the token, checks the rate-limit guard, and files via GitHub.
    /// Test: `report_bug_no_confirm_returns_preview_only`,
    ///       `report_bug_confirm_no_token_graceful_failure` in the `tests` module.
    async fn report_bug(&self, fingerprint: &str, confirm: bool) -> Result<Value, String> {
        super::mcp_bugreport::report_bug(fingerprint, confirm).await
    }

    // ── #1221: session-lifecycle tools ───────────────────────────────────────
    //
    // Each method is a thin wrapper over the existing `SessionManager` lifecycle
    // ops (the same ones the HTTP `…/managed/*` routes use), so MCP and HTTP
    // share one implementation. The wrapping logic lives in
    // `super::mcp_session` to keep this file under the 500-SLOC cap.

    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> {
        super::mcp_session::session_new(
            &self.state,
            repo_url,
            git_ref,
            task,
            name_hint,
            runtime,
            ephemeral,
        )
        .await
    }

    async fn session_stop(&self, session_id: &str) -> Result<Value, String> {
        super::mcp_session::session_stop(&self.state, session_id).await
    }

    async fn session_resume(&self, session_id: &str) -> Result<Value, String> {
        super::mcp_session::session_resume(&self.state, session_id).await
    }

    async fn session_decommission(&self, session_id: &str) -> Result<Value, String> {
        super::mcp_session::session_decommission(&self.state, session_id).await
    }

    async fn session_delete(&self, session_id: &str, force: bool) -> Result<Value, String> {
        super::mcp_session::session_delete(&self.state, session_id, force).await
    }

    // #6431: record-only bulk delete; see `mcp_session_bulk` for why it is a
    // separate path from `session_delete` and from the legacy `remove_session`.
    async fn session_delete_records(&self, session_ids: &[String]) -> Result<Value, String> {
        super::mcp_session_bulk::session_delete_records(&self.state, session_ids).await
    }

    async fn session_activity(&self, session_id: &str, lines: u32) -> Result<Value, String> {
        super::mcp_session::session_activity(&self.state, session_id, lines).await
    }

    async fn session_send(&self, session_id: &str, text: &str) -> Result<Value, String> {
        super::mcp_session::session_send(&self.state, session_id, text).await
    }

    // ── PM pause/resume context tools (delegate to mcp_context) ──────────────

    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> {
        super::mcp_context::session_context_catchup_with_session_created(
            project_dir,
            session_id,
            tmux_window,
            tmux_session_created,
            all_projects,
            full,
            sessions_offset,
        )
        .await
    }

    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> {
        super::mcp_context::session_context_pause(
            &self.state,
            project_dir,
            session_id,
            summary,
            completed,
            in_progress,
            next_steps,
            tmux_window,
            prune_worktrees,
        )
        .await
    }

    // ── #1508: fleet-wide teardown tools (delegate to mcp_session) ───────────

    async fn session_decommission_ephemeral(&self) -> Result<Value, String> {
        super::mcp_session::session_decommission_ephemeral(&self.state).await
    }

    async fn session_prune(
        &self,
        state: &str,
        dry_run: bool,
        include_active: bool,
    ) -> Result<Value, String> {
        super::mcp_session::session_prune(&self.state, state, dry_run, include_active).await
    }

    // ── #1222: console-facing tools (delegate to mcp_console) ────────────────

    async fn console_metrics(&self) -> Result<Value, String> {
        super::mcp_console::console_metrics(&self.state).await
    }

    async fn supervisor_status(&self) -> Result<Value, String> {
        super::mcp_console::supervisor_status(&self.state).await
    }

    async fn auto_resume_set(&self, enabled: bool) -> Result<Value, String> {
        super::mcp_console::auto_resume_set(enabled).await
    }

    // ── #1220: config-convention tools (delegate to mcp_console) ─────────────

    /// Back `disk_survey` (#6927) — see [`crate::daemon::mcp_disk::disk_survey`].
    async fn disk_survey(
        &self,
        project: Option<&str>,
        budget_seconds: Option<u64>,
        group_by: Option<&str>,
    ) -> Result<Value, String> {
        crate::daemon::mcp_disk::disk_survey(&self.state, project, budget_seconds, group_by).await
    }

    /// Back `secrets_get_ref` (#7522) — see [`crate::secrets_client::get_ref`].
    #[cfg(unix)]
    async fn secrets_get_ref(&self, project: &str, key: &str) -> Result<Value, String> {
        use crate::secrets_client::{default_client, get_ref};
        let client = match &self.secrets {
            Some(client) => client.as_ref(),
            // `default_client` fails only when `$HOME` is unknown.
            None => default_client()
                .map_err(|_| "secrets_get_ref: the home directory is unavailable".to_owned())?,
        };
        let answer = get_ref(client, std::path::Path::new(project), key)
            .await
            .map_err(|e| e.to_string())?;
        serde_json::to_value(answer).map_err(|_| "secrets_get_ref: encode failed".to_owned())
    }

    /// Back `secrets_get_ref` (#7522): the trusty-secrets client is Unix-only.
    #[cfg(not(unix))]
    async fn secrets_get_ref(&self, _project: &str, _key: &str) -> Result<Value, String> {
        Err("secrets_get_ref: the secrets socket needs a Unix platform".to_owned())
    }

    async fn config_read(&self) -> Result<Value, String> {
        super::mcp_console::config_read()
    }

    #[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> {
        super::mcp_console::config_write(
            workspace_root_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,
        )
    }

    // ── #1519 WI-2: project-registry tools (delegate to mcp_project) ─────────

    async fn project_list(&self) -> Result<Value, String> {
        super::mcp_project::project_list(&self.state).await
    }

    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> {
        super::mcp_project::project_register(
            &self.state,
            name,
            repo_url,
            default_branch,
            stack_hint,
            tags,
            description,
            gh_user,
            gh_account,
        )
        .await
    }

    async fn project_get(&self, name: &str) -> Result<Value, String> {
        super::mcp_project::project_get(&self.state, name).await
    }

    // ── #1517 WI-5: NL→repo resolver (delegates to mcp_project) ─────────────

    async fn project_resolve(&self, query: &str) -> Result<Value, String> {
        super::mcp_project::project_resolve(&self.state, query).await
    }

    // ── #2550: session-manager proxy tools (delegate to mcp_proxy) ───────────
    //
    // Each builds a `SessionProxy` over the SAME shared focus store the HTTP
    // proxy routes use, so a focus set over MCP is visible to those surfaces
    // under the same `conversation_key` and vice versa.

    async fn session_proxy_focus(
        &self,
        conversation_key: &str,
        session_id: &str,
    ) -> Result<Value, String> {
        super::mcp_proxy::session_proxy_focus(&self.state, conversation_key, session_id).await
    }

    async fn session_proxy_unfocus(&self, conversation_key: &str) -> Result<Value, String> {
        super::mcp_proxy::session_proxy_unfocus(&self.state, conversation_key).await
    }

    async fn session_proxy_message(
        &self,
        conversation_key: &str,
        text: &str,
    ) -> Result<Value, String> {
        super::mcp_proxy::session_proxy_message(&self.state, conversation_key, text).await
    }

    async fn session_proxy_summary(&self, conversation_key: &str) -> Result<Value, String> {
        super::mcp_proxy::session_proxy_summary(&self.state, conversation_key).await
    }
}

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