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
//! Channel-agnostic session-manager PROXY layer (TELUI-6, #1440).
//!
//! Why: this is layer 2 of the three-layer control model — the session-manager
//! acting as a PROXY between an external channel (Telegram, Slack, a local HTTP
//! caller) and ONE managed session. Layer 1 is direct tmux attach; layer 3 (the
//! cross-scope project manager, #2109) is out of scope here. The proxy is
//! deliberately SINGLE-SESSION-focused: a conversation "focuses" one session and
//! then talks to it, in two directions — INJECT (free text routed to the
//! session's `managed-send`) and SUMMARIZE (the session's recent activity
//! digested back to the channel). Putting the focus state machine and both
//! directions HERE, behind a [`ManagedBackend`] abstraction, means every surface
//! — Telegram, Slack, and the daemon's OWN local HTTP proxy routes
//! (`daemon::managed_routes::proxy`) — share the identical [`SessionProxy`]
//! state machine and differ only in HOW they reach a managed session: over HTTP
//! via [`super::executor::CommandExecutor`] (external channels) or in-process via
//! the daemon's `SessionManager` (the local proxy routes). A caller can therefore
//! exercise this entire state machine with `curl` against the daemon before ever
//! wiring up a Telegram bot token.
//! What: [`SessionProxy`] owns the per-conversation focus map (keyed by an opaque
//! channel-supplied conversation string — Telegram passes its `chat_id`, Slack a
//! channel id, the local HTTP surface a caller-supplied `conversation_key`) and
//! exposes [`SessionProxy::focus`], [`SessionProxy::unfocus`],
//! [`SessionProxy::current_focus`], [`SessionProxy::inject`], and
//! [`SessionProxy::summarize`], each returning a structured, channel-agnostic
//! outcome the binding renders. [`route_free_text`] is the pure inject-vs-
//! coordinator routing decision. Focus state is in-memory and VOLATILE across a
//! daemon restart (no channel persists per-conversation state); a restart simply
//! drops every conversation back to fleet-wide chat.
//! Test: `proxy/tests.rs` covers the pure routing, the store round-trip, and the
//! inject/summarize/dead-session paths against an in-process test daemon (via the
//! `CommandExecutor` backend); `daemon::managed_routes::proxy` and
//! `tests/proxy_routes.rs` cover the SAME state machine reached through the
//! direct in-process backend the daemon's local HTTP surface uses.
use HashMap;
use Arc;
use async_trait;
use CommandExecutor;
use ;
/// A resolved focused session: its canonical id plus a display name.
///
/// Why: the proxy keeps the resolved id (so later inject/summarize skip
/// re-resolution and are unambiguous) AND the friendly name (so a channel can
/// name the session in replies without another daemon round-trip).
/// What: the canonical managed-session `id` and its human-readable `name`, both
/// captured at focus time from the authoritative resolution the backend performs.
/// Test: `set_get_clear_round_trip` in `proxy/tests.rs`.
/// A lightweight digest of a managed session's current activity.
///
/// Why: [`SessionProxy::summarize`] needs just enough to answer "what is my
/// focused session doing?" without forcing every [`ManagedBackend`] to speak the
/// full, heavier `ManagedActivity` wire shape (token counts, cache-hit flags,
/// etc. — those stay on the richer `GET .../activity` endpoint UIs can call
/// directly when they want the full picture).
/// What: the session's lifecycle state, a short human-readable summary, and any
/// pending decision it is blocked on.
/// Test: exercised via each `ManagedBackend` impl's tests.
/// Backend abstraction the proxy resolves/sends/digests through.
///
/// Why: this is the seam that lets [`SessionProxy`] be the SAME struct and the
/// SAME state machine for every surface, while each surface reaches a managed
/// session differently — an external channel (Telegram, Slack) goes over HTTP
/// via [`CommandExecutor`]; the daemon's own local proxy routes go in-process
/// via `SessionManager` directly (see `daemon::managed_routes::proxy`), with no
/// network hop. Neither implementation duplicates the focus/inject/summarize
/// decision logic — only the three primitive operations below differ.
/// What: `resolve` maps a fuzzy target (id, friendly name, or prefix) to its
/// canonical `(id, name)`; `send` injects text into a resolved session; `activity`
/// fetches a lightweight digest. All three return `Err(String)` on failure — a
/// message a resolver-style "not found" error must phrase as containing the
/// literal substring `"not found"` so [`is_missing_session`] can distinguish a
/// vanished session from a transient transport failure (see that function's doc).
/// Test: `ManagedBackend for CommandExecutor` is exercised by `proxy/tests.rs`;
/// the daemon's direct backend by `daemon::managed_routes::proxy::tests`.
/// [`ManagedBackend`] over the shared HTTP [`CommandExecutor`] — the backend
/// every EXTERNAL channel (Telegram, Slack) uses.
///
/// Why: external channels are separate OS processes from the daemon; they can
/// only reach a managed session over the daemon's existing HTTP API, which is
/// exactly what [`CommandExecutor`] already does via [`TrustyCommand::ManagedGet`],
/// [`TrustyCommand::ManagedSend`], and [`TrustyCommand::ManagedActivity`].
/// What: maps each [`ManagedBackend`] method onto the corresponding
/// [`TrustyCommand`] and unwraps the resulting [`CommandResult`].
/// Test: `proxy/tests.rs` (via `SessionProxy` built over this backend against an
/// in-process test daemon).
/// The routing decision for one free-text (non-command) message.
///
/// Why: the single seam between "channel received a non-command message" and
/// "which subsystem handles it"; modelling the two outcomes keeps each channel's
/// handler branch trivial and the decision itself pure and unit-testable, shared
/// across channels.
/// What: `Inject` routes the text to the focused session (proxy INJECT
/// direction); `Coordinator` routes it to the action-capable coordinator (the
/// default when nothing is focused).
/// Test: the `route_free_text_*` tests in `proxy/tests.rs`.
/// Outcome of a [`SessionProxy::focus`] request, for the channel to render.
///
/// Why: focusing is a validating operation with three genuinely different
/// results a channel must render differently — successfully focused, a
/// read-only query of the current focus (empty target), or a target that could
/// not be resolved. Modelling them as one enum keeps every binding's render
/// function exhaustive instead of guessing from a boolean + optional error.
/// What: `Focused` on a successful resolve-and-set; `Current` when the caller
/// passed an empty target (a read-only "what's focused right now?" query, never
/// touching the backend); `NotFound` when the backend could not resolve the
/// target — focus is left unchanged in this case.
/// Test: `focus_empty_reports_current`, `focus_unknown_is_not_found` in
/// `proxy/tests.rs`; the render mapping in `telegram::focus::tests`.
/// Outcome of a [`SessionProxy::inject`] (free text → session send).
///
/// Why: an inject can land in one of four genuinely different states a channel
/// must handle distinctly — sent, the session having vanished (requiring an
/// auto-unfocus so the conversation does not fail forever), a transient failure
/// (which must NOT clear focus, or a network blip would discard the operator's
/// context), or no focus at all (letting the caller fall back to its own
/// coordinator instead of receiving an HTTP error). Modelling all four as one
/// enum keeps that branching explicit and exhaustive at every binding.
/// What: `Sent` on success; `AutoUnfocused` when the backend's resolve/send
/// failed with a "not found"-shaped error (see [`is_missing_session`]) — focus
/// was already cleared by the time this variant is returned; `Failed` on any
/// other backend error — focus is left untouched; `NoFocus` when the
/// conversation had nothing focused.
/// Test: `inject_no_focus`, `inject_auto_unfocuses_dead_session`,
/// `inject_transient_error_keeps_focus` in `proxy/tests.rs`.
/// Outcome of a [`SessionProxy::summarize`] (session activity → channel).
///
/// Why: mirrors [`InjectOutcome`]'s four-way split for exactly the same reason —
/// a summarize call can succeed, discover the session is gone (auto-unfocus),
/// hit a transient failure (focus preserved), or have nothing focused to
/// summarize (letting the caller fall back gracefully).
/// What: `Summary` carries the [`ActivityDigest`] fields inline; `AutoUnfocused`
/// and `Failed` mirror [`InjectOutcome`]'s variants of the same name; `NoFocus`
/// when nothing is focused.
/// Test: `summarize_no_focus`, `summarize_auto_unfocuses_dead_session` in
/// `proxy/tests.rs`.
/// Decide where a free-text message routes, given whether a session is focused.
///
/// Why: the single seam between "channel received a non-command message" and
/// "which subsystem handles it"; pure (no store, no daemon) so every branch is
/// testable and identical across channels. It runs only after a channel has
/// already failed to parse the text as a known command, so a leading `/` here is
/// an UNKNOWN command — never hijacked into the focused session (that would send
/// a mistyped command as a prompt); such lines fall through to the coordinator.
/// What: a `/`-prefixed line always routes to [`FreeTextRoute::Coordinator`];
/// otherwise a focused conversation routes to [`FreeTextRoute::Inject`] and an
/// unfocused one to [`FreeTextRoute::Coordinator`].
/// Test: `route_free_text_focused_injects`, `route_free_text_unfocused_coordinates`,
/// `route_free_text_slash_never_injects`.
/// Channel-agnostic session-manager proxy: per-conversation focus + inject +
/// summarize over a pluggable [`ManagedBackend`].
///
/// Why: one implementation of layer 2 that every surface binds to — Telegram,
/// Slack, and the daemon's own local HTTP proxy routes all construct this SAME
/// struct, differing only in which [`ManagedBackend`] they pass in. The focus
/// state machine (validate-then-set, auto-unfocus-on-missing,
/// preserve-on-transient-error) lives here exactly once.
/// What: holds an `Arc<dyn ManagedBackend>` (the shared reach-a-session seam) and
/// a `Mutex`-guarded map of conversation key → [`FocusTarget`]. [`Self::new`]
/// gives the proxy its own fresh, unshared store (what a long-lived channel
/// process wants — Telegram/Slack construct exactly one proxy for the process
/// lifetime); [`Self::with_focus_store`] lets a caller supply an EXTERNAL shared
/// store instead, which the daemon's local proxy routes use so a fresh
/// [`SessionProxy`] can be constructed per HTTP request while the focus map
/// itself persists across requests (owned by `DaemonState`).
/// Test: `proxy/tests.rs`.
/// Whether a `managed-*` error means the focused session no longer exists.
///
/// Why: the auto-unfocus path must fire ONLY when the session is genuinely gone,
/// not on a transient transport error — unfocusing on a network blip would throw
/// away the operator's context. Every [`ManagedBackend`] impl is contractually
/// required to phrase a resolution failure with the substring `"not found"` (the
/// [`CommandExecutor`] impl inherits this wording verbatim from the executor's
/// managed-session resolver's `"managed session {target} not found"`; the
/// daemon's direct backend mirrors it exactly). This is admittedly substring
/// matching rather than a typed signal —
/// `is_missing_session_matches_live_resolver_not_found_format` (in
/// `proxy/tests.rs`) pins the coupling to the ACTUAL resolver wording so a
/// message-text drift fails a test instead of silently disabling the
/// auto-unfocus safety net.
/// What: returns true when `msg` contains "not found".
/// Test: `is_missing_session_detects_not_found`,
/// `is_missing_session_matches_live_resolver_not_found_format`.