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
//! Opt-in deny-by-default persona-confirmation gate for delegated (sub-agent)
//! edit-tool dispatches under `tm hook --pm-guard` (issue #2231).
//!
//! Why: `pm_guard`'s Guard 4 (see `super::pm_guard::pm_guard`) unconditionally
//! exempts a native Task/Agent-tool sub-agent dispatch from every deny rule —
//! correct by default (issue #2014: the PM legitimately delegates edits to
//! rust-engineer and friends), but it means a managed session whose persona
//! deployment *positively, provably* failed would still let a delegated
//! Edit/Write through unchallenged. Some operators want a stricter posture:
//! refuse delegated edits too until the session's persona is confirmed. That
//! must be strictly OPT-IN — issue #2172 is the standing lesson here: a
//! fail-closed persona/spawn gate previously aborted real managed-session
//! launches because it could not positively confirm success, even for
//! perfectly healthy ad-hoc/`tm connect`/vanilla sessions that were never
//! managed in the first place. This module repeats none of that: the new
//! check is (a) OFF unless [`DENY_BY_DEFAULT_ENV`] is explicitly truthy, and
//! (b) even when on, it only ever denies on POSITIVE evidence of failure
//! (`state == "errored"`, the daemon's own definitive terminal-failure
//! record); every ambiguous or unmanaged case allows, exactly like the
//! pre-#2231 default.
//! What: [`deny_by_default_enabled`] reads the opt-in env var (default:
//! off — see [`is_truthy`] for the accepted spellings, shared with this
//! crate's other boolean env-var parsers). [`persona_status`] resolves a
//! [`PersonaStatus`] for the CURRENT pane by reading the `TM_MANAGED_SESSION_ID`
//! pane env var (exported by `runtime::claude_code::session_id_export_prefix`
//! into every managed session's shell — absent for ad-hoc/`tm connect`/vanilla
//! sessions) and, only when present, querying the daemon's
//! `GET /api/v1/sessions/managed/{id}` endpoint (via [`trusty_mpm::client::DaemonClient`],
//! the same typed call `guided.rs`'s `nested_session_guard` already uses) with a
//! tight connect+total timeout so an unreachable/slow daemon degrades to
//! `Ambiguous` (allow) rather than hanging the hook. Issue #3600: that env var
//! is tmux SESSION-scoped, not pane-scoped, so a sibling pane can inherit an
//! identical value and this lookup would otherwise resolve a DIFFERENT
//! session's state as if it were this pane's own; [`persona_status_for_session`]
//! now cross-checks the resolved record's own `pane_id` against this
//! process's current tmux pane (via the shared
//! [`crate::commands::pane_identity::EnvSessionIdentity`] check `guided.rs`
//! already uses) before ever trusting the resolved `state` — a mismatch OR an
//! unresolvable pane id both discard the resolved state entirely and fall
//! back to [`PersonaStatus::Ambiguous`], never [`PersonaStatus::ExplicitlyFailed`]
//! (this is NOT "trust the env var": the state is simply never treated as
//! evidence when identity isn't confirmed, consistent with the existing
//! #2172 permissive-default doctrine below). [`classify_persona_status`]
//! is the pure decision core: no session id at all is [`PersonaStatus::NotManaged`];
//! a resolved `state == "errored"` is [`PersonaStatus::ExplicitlyFailed`]; any
//! other resolved state is [`PersonaStatus::Confirmed`]; a lookup that could not
//! be resolved (daemon unreachable, id unknown, malformed id, OR an
//! unconfirmed pane identity) is [`PersonaStatus::Ambiguous`].
//! [`PersonaStatus::should_deny`] is the ONLY place that maps a status to a
//! gating decision — `true` solely for `ExplicitlyFailed`, so every other
//! branch (including every error path) resolves to allow.
//! Test: `is_truthy_*`, `classify_persona_status_*`,
//! `persona_status_for_session_not_managed_when_session_id_absent`,
//! `persona_status_for_session_ambiguous_when_daemon_unreachable`,
//! `persona_status_for_session_ambiguous_when_pane_mismatch`,
//! `persona_status_for_session_ambiguous_when_pane_unavailable`,
//! `persona_status_should_deny_only_for_explicitly_failed`.
use crateEnvSessionIdentity;
use DaemonClient;
/// Opt-in env var (issue #2231): when truthy (see [`is_truthy`]), a native
/// sub-agent dispatch of an otherwise-guarded tool (Edit/Write/MultiEdit/
/// NotebookEdit, or a guarded Bash verb — i.e. anything
/// `super::pm_guard::evaluate_tool` would deny for the top-level PM) is
/// DENIED unless [`persona_status`] resolves to [`PersonaStatus::Confirmed`],
/// [`PersonaStatus::NotManaged`], or [`PersonaStatus::Ambiguous`]. Unset (the
/// default) leaves Guard 4's unconditional sub-agent exemption completely
/// unchanged.
pub const DENY_BY_DEFAULT_ENV: &str = "TRUSTY_MPM_PM_DENY_BY_DEFAULT";
/// The pane env var a managed session's launcher exports (see
/// `runtime::claude_code::session_id_export_prefix`), naming the managed
/// session this pane belongs to. Absent for ad-hoc/`tm connect`/vanilla
/// `claude` invocations — there was never a launcher to export it.
const MANAGED_SESSION_ID_ENV: &str = "TM_MANAGED_SESSION_ID";
/// Deny reason surfaced when the persona gate denies a delegated dispatch.
pub const PERSONA_DENY_REASON: &str = "PM session persona deployment explicitly failed \
(TRUSTY_MPM_PM_DENY_BY_DEFAULT strict mode). Delegated edit blocked until the managed \
session's persona is repaired (see `tm doctor`) or the session is restarted.";
/// Parse a truthy token, shared spelling with this crate's other boolean env
/// parsers (`core::auto_resume::parse_truthy`, `supervisor::config::env_bool`).
///
/// Why: one accepted-spellings list keeps every opt-in boolean flag in this
/// crate consistent instead of each guard inventing its own.
/// What: case-insensitive match against `1`/`true`/`yes`/`on`; `None` or any
/// other value is not truthy.
/// Test: `is_truthy_accepts_known_tokens`, `is_truthy_rejects_unknown_or_absent`.
pub
/// Whether the [`DENY_BY_DEFAULT_ENV`] opt-in is active for this process.
///
/// Why: split out so every call site shares one definition of "on".
/// What: `true` iff [`DENY_BY_DEFAULT_ENV`] is set to a truthy token.
/// Test: covered via `is_truthy_*` (this is a one-line env wrapper around it).
pub
/// Resolved persona-confirmation status for the current pane (issue #2231).
///
/// Why: the deny-by-default gate must distinguish "nothing to confirm" (not a
/// managed session), "confirmed good", "positively confirmed bad", and
/// "cannot tell" — collapsing the first three into "allow" and the fourth
/// bucket into "allow" too is the entire #2172-lesson safeguard; see
/// [`Self::should_deny`].
/// What: one variant per resolvable state; see [`classify_persona_status`] for
/// the pure mapping from raw inputs to this type.
/// Test: `classify_persona_status_*`.
pub
/// Pure decision core: map (session-id presence, resolved daemon state) to a
/// [`PersonaStatus`].
///
/// Why: isolating the decision from the env-read and the HTTP call makes the
/// actual policy exhaustively unit-testable without a daemon or process env
/// mutation — the same "pure predicate, thin I/O wrapper" split already used
/// by `guided::nested_managed_match` / `nested_session_guard` in this crate.
/// What: no session id at all is [`PersonaStatus::NotManaged`]; a resolved
/// state string equal to `"errored"` (the exact `ManagedSessionState::Errored`
/// `Display` spelling — see `daemon::managed_routes::mod::` `SessionSummary`
/// construction, `state: record.state.to_string()`) is
/// [`PersonaStatus::ExplicitlyFailed`]; any other resolved state is
/// [`PersonaStatus::Confirmed`]; `None` (lookup failed/unresolved) with a
/// session id present is [`PersonaStatus::Ambiguous`].
/// Test: `classify_persona_status_not_managed_without_session_id`,
/// `classify_persona_status_confirmed_for_non_errored_state`,
/// `classify_persona_status_explicitly_failed_for_errored_state`,
/// `classify_persona_status_ambiguous_when_state_unresolved`.
/// Best-effort daemon lookup of a managed session's lifecycle-state word AND
/// its own captured `pane_id` (issue #3600: the latter is required to
/// cross-check pane identity before the former is trusted as evidence).
///
/// Why: the daemon's `sessions.json`-backed `SessionRecord::state` is the
/// only place a genuine `Errored` verdict is recorded; this hook process must
/// not read that file directly (it may not share the daemon's resolved
/// framework root) nor block on a slow/down daemon, so it reuses the same
/// typed HTTP call `guided.rs`'s `nested_session_guard` already makes,
/// with its own short-lived, tightly-timed client (mirrors
/// `pm_guard::audit_denied_tool`'s connect/total timeout budget).
/// What: `Some((state, pane_id))` (e.g. `("active", Some("%5"))`) on a
/// successful `GET /api/v1/sessions/managed/{id}`; `None` on ANY failure —
/// client-build error, connect/timeout, non-2xx, or malformed body — so a
/// down daemon degrades to [`PersonaStatus::Ambiguous`], never a hang or a
/// deny.
/// Test: exercised end to end (unreachable daemon → `None`) via
/// `persona_status_for_session_ambiguous_when_daemon_unreachable`.
async
/// Resolve [`PersonaStatus`] given an explicit (test-injectable) session id
/// AND this process's current tmux pane id (issue #3600).
///
/// Why: separating the session-id/pane-id SOURCE from the resolution logic
/// lets tests drive every branch (present/absent, reachable/unreachable
/// daemon, pane confirmed/mismatched/unresolvable) without mutating
/// process-global env state or a live tmux server.
/// What: `None`/empty `raw_session_id` short-circuits to
/// [`classify_persona_status`]`(false, None)` (= `NotManaged`) with no network
/// call at all. Otherwise awaits [`lookup_session_state_and_pane`]; on lookup
/// failure, classifies `(true, None)` (= `Ambiguous`) same as before. On a
/// successful lookup, cross-checks `current_pane_id` against the resolved
/// record's own `pane_id` via [`EnvSessionIdentity::evaluate`] — only a
/// CONFIRMED match lets the resolved `state` be classified at all; a
/// `Mismatch` or `Unavailable` outcome discards the resolved state entirely
/// (classifies `(true, None)` = `Ambiguous`) rather than treating it as
/// evidence of either `Confirmed` or `ExplicitlyFailed` for a session this
/// pane cannot prove it owns.
/// Test: `persona_status_for_session_not_managed_when_session_id_absent`,
/// `persona_status_for_session_ambiguous_when_daemon_unreachable`,
/// `persona_status_for_session_confirmed_for_active_state`,
/// `persona_status_for_session_explicitly_failed_for_errored_state`,
/// `persona_status_for_session_ambiguous_when_pane_mismatch`,
/// `persona_status_for_session_ambiguous_when_pane_unavailable`.
pub async
/// Resolve [`PersonaStatus`] for the CURRENT pane by reading
/// [`MANAGED_SESSION_ID_ENV`] and this process's own tmux `pane_id` from the
/// live environment.
///
/// Why: this is the production entry point `pm_guard`'s Guard 4 calls; the
/// pane-env and tmux-pane reads are the ONLY places this module touches
/// live process/tmux state, keeping [`persona_status_for_session`] fully
/// test-injectable.
/// What: thin wrapper delegating to [`persona_status_for_session`], with
/// `current_pane_id` resolved via [`super::tmux_attach::current_tmux_pane_id`]
/// (issue #3600) — the same primitive `guided.rs`'s nested-session guard
/// uses.
/// Test: covered by the `persona_status_for_session_*` tests (this adds only
/// the env/tmux reads, which mirror the well-established
/// `TM_MANAGED_SESSION_ID`/pane-id reads in `guided.rs::nested_session_guard`).
pub async