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
//! Explicit adoption of an EXISTING, unmanaged tmux session (#1433).
//!
//! Why: the session-manager normally only drives sessions it `create`d, but an
//! operator often already has a live tmux pane (a hand-started Claude Code, a
//! session created outside trusty-mpm, or one whose record was lost) that they
//! want to connect to and drive through the full managed surface. This is the
//! EXPLICIT counterpart to [`SessionManager::reconcile_on_boot`]'s automatic
//! adoption. It lives in its own module so [`manager`](super::manager) stays under
//! the 500-SLOC production cap.
//! What: an inherent `impl SessionManager` block adding
//! [`SessionManager::adopt_existing`]; a free helper
//! [`derive_source_id_for_record`] used by the reconcile backfill (#1780).
//! Test: `manager_adopt_existing_*` in `super::tests`;
//! `derive_source_id_*` unit tests at the bottom of this module.
use std::path::{Path, PathBuf};
use std::time::Duration;
use chrono::Utc;
use tracing::{debug, info, warn};
use super::driver::ManagedTmuxDriver;
use super::manager::{ManagedError, SessionManager};
use super::record::{ManagedSessionId, ManagedSessionState, SessionRecord, StopCause};
/// Backoff between the boot-adopt path's working-directory probes; its length
/// plus one is how many times [`resolve_adoptable_cwd`] asks.
const CWD_PROBE_BACKOFF: [Duration; 2] = [Duration::from_millis(50), Duration::from_millis(150)];
/// Resolve the working directory boot reconciliation will adopt a pane under,
/// retrying a failed probe before reporting the pane unresolvable.
///
/// Why: declining a pane (#6118) leaves it untracked, and untracked is exactly
/// what `daemon::orphan_gc` reaps — an idle-shell pane with no live child is
/// killed after two 60-second sweeps. So the probe that decides this is now a
/// kill decision, and a single false `None` costs a live pane within about two
/// minutes. `TmuxDriver::pane_current_path` collapses spawn failure, a non-zero
/// exit and empty output into one `None` with no retry, and
/// [`SessionManager::reconcile_on_boot`] runs ONCE per daemon process (a
/// `OnceCell` in `daemon::state::core`), so without a retry that one flaky
/// answer is the pane's only hearing until the daemon next restarts.
///
/// Retrying inside the call, rather than declining only on a second boot
/// observation, is what actually protects the pane. A cross-boot debounce
/// cannot: the pane is untracked from the moment of the first decline, so the
/// orphan-GC reaches it in 60-120 seconds while the second observation waits on
/// a daemon restart that may be days away — and holding the observation by
/// adopting provisionally just recreates the #6118 ghost.
///
/// What: asks `get_pane_cwd` up to `CWD_PROBE_BACKOFF.len() + 1` times, sleeping
/// the matching backoff between attempts, and returns the first answer that
/// names an existing directory. Only a probe that returns NO answer is retried.
///
/// # A stale path is an answer, not a flake (#6414)
///
/// `.filter(|p| p.is_dir())` used to fold both negatives into the retry, so a
/// pane whose `pane_current_path` names a directory that has since been deleted
/// — a reaped agent worktree — cost the full 200 ms backoff before being
/// declined. tmux keeps reporting that recorded path, so the second and third
/// probes read the same bytes and reach the same verdict; the sleep between
/// them buys nothing. On a host with 276 such panes that was 55 s of pure sleep
/// inside `reconcile_on_boot`, which `DaemonState::session_manager()` awaits
/// before it hands the manager to its first caller — and the first caller is
/// often the SessionEnd worktree sweep, which then reached its first gate a
/// minute late (#6391 raised its budget to 300 s as containment).
///
/// The #6118 protection is unchanged in the case it was written for: `None`
/// means tmux did not answer at all (spawn failure, non-zero exit, empty
/// output), which a retry genuinely can turn into an answer, and that arm still
/// gets every attempt. No pane's verdict changes — only how long a determinate
/// negative takes to reach.
/// Test: `flaky_cwd_probe_still_adopts_within_one_reconcile`,
/// `unresolvable_cwd_probe_is_retried_a_bounded_number_of_times`,
/// `a_stale_pane_path_is_declined_on_the_first_probe` in `naming_tests.rs`.
pub(super) async fn resolve_adoptable_cwd(
tmux: &dyn ManagedTmuxDriver,
name: &str,
) -> Option<PathBuf> {
for attempt in 0..=CWD_PROBE_BACKOFF.len() {
match tmux.get_pane_cwd(name) {
Some(cwd) if cwd.is_dir() => {
if attempt > 0 {
warn!(
name = %name,
attempt = attempt + 1,
"reconcile: pane working directory resolved only on retry — the first \
probe was a transient failure, and declining on it would have exposed a \
live pane to the orphan-GC (#6118)"
);
}
return Some(cwd);
}
// #6414: tmux answered; the answer just names a directory that is
// gone. Re-reading it returns the same path, so decide now.
Some(stale) => {
debug!(
name = %name,
path = %stale.display(),
"reconcile: pane working directory no longer exists — declining without \
retry, which cannot change a path tmux keeps reporting (#6414)"
);
return None;
}
None => {}
}
if let Some(backoff) = CWD_PROBE_BACKOFF.get(attempt) {
tokio::time::sleep(*backoff).await;
}
}
None
}
/// Derive the `source_id` (`"owner/repo"`) for a session record from its workspace git remote.
///
/// Why (#1780): the reconcile backfill needs to populate `source_id` for records
/// that were stored before the field existed or that were auto-adopted without one.
/// Centralising the derivation here keeps `manager.rs` under its 500-SLOC cap and
/// makes the logic independently unit-testable.
/// What: tries `workspace_path` first (if the directory exists); falls back to
/// `cwd` when it is not the sentinel `/unknown` and still exists on disk.
/// Calls `trusty_common::github_path::derive_github_path`, which shells to
/// `git config --get remote.origin.url` — no network. Returns `None` when no
/// usable path is available, the directory is not a git repo, or the remote URL
/// is not parseable as a `owner/repo` identity; callers skip gracefully in that case.
/// Test: `derive_source_id_ssh_remote`, `derive_source_id_https_remote`,
/// `derive_source_id_none_for_no_remote`, `derive_source_id_none_for_unknown_path`.
pub(super) fn derive_source_id_for_record(record: &SessionRecord) -> Option<String> {
let path: &Path = record
.workspace_path
.as_deref()
.filter(|p| p.is_dir())
.or_else(|| {
let c = record.cwd.as_path();
// #6118: one spelling of the sentinel, shared with every other
// reader of it.
(c != Path::new(super::record::UNRESOLVED_PATH_SENTINEL) && c.is_dir()).then_some(c)
})?;
let gh = trusty_common::github_path::derive_github_path(path)?;
Some(format!("{}/{}", gh.owner, gh.repo))
}
/// Batch-derive `source_id` for all records missing it in one `spawn_blocking`.
///
/// Why (#1780): shelling to `git config --get remote.origin.url` inside an
/// async loop would block the tokio executor for every null-source_id record
/// at daemon boot time (136 sessions observed in the fleet). A single
/// `spawn_blocking` call batches all N derivations on one thread-pool thread,
/// freeing the async executor immediately.
/// What: collects `(index, path)` pairs for non-Decommissioned records with
/// `source_id == None`, derives all in one `spawn_blocking`, then writes
/// results back in-place by index. Records where derivation fails (no git,
/// no remote, non-GitHub URL, `/unknown`) are left unchanged — one bad record
/// never aborts the pass.
/// Test: `backfill_tests::reconcile_backfills_source_id_from_workspace_git_remote`
/// (Active path) and `backfill_tests::reconcile_backfills_source_id_for_stopped_record`
/// (Stopped path).
pub(super) async fn backfill_source_ids(records: &mut [SessionRecord]) {
// Collect (record_index, cloned_record) for records that need derivation.
// The clone is cheap (SessionRecord is a small owned-data struct) and lets
// derive_source_id_for_record run inside the spawn_blocking closure.
let to_derive: Vec<(usize, SessionRecord)> = records
.iter()
.enumerate()
.filter(|(_, r)| {
r.source_id.is_none() && !matches!(r.state, ManagedSessionState::Decommissioned)
})
.map(|(i, r)| (i, r.clone()))
.collect();
if to_derive.is_empty() {
return;
}
let derived: Vec<(usize, Option<String>)> = tokio::task::spawn_blocking(move || {
to_derive
.into_iter()
.map(|(idx, record)| (idx, derive_source_id_for_record(&record)))
.collect()
})
.await
.unwrap_or_default();
for (idx, sid) in derived {
if let Some(s) = sid {
info!(name = %records[idx].tmux_name, source_id = %s, "reconcile: backfilled source_id");
records[idx].source_id = Some(s);
}
}
}
impl SessionManager {
/// Adopt an EXISTING, unmanaged tmux session into the durable store (#1433).
///
/// Why: connect the managed surface to a live pane the operator already has so
/// it can be driven through observe/send/stop/resume, rather than spawning a
/// new one. This is the EXPLICIT counterpart to
/// [`reconcile_on_boot`](SessionManager::reconcile_on_boot)'s automatic
/// adoption — it synthesises a durable `Active` record for a pane that already
/// exists.
///
/// Design decisions (DOC-20 / DOC-14; collision handling updated #3692):
/// - **Collision check is INVERTED vs. `create`.** `create` fails when the name
/// already exists; `adopt_existing` fails with
/// [`ManagedError::TmuxSessionMissing`] when the pane does NOT exist (you
/// cannot adopt what is not there).
/// - **A name held by a NON-TERMINAL record is auto-suffixed, never rejected —
/// UNLESS it is provably the SAME pane** (owner decision, issue #3692: two
/// distinct managed sessions were found sharing one name). tmux enforces
/// session-name uniqueness on one server, so a live tmux name a NON-terminal
/// record already tracks can only mean one of two things: (a) it is the
/// identical pane being adopted again (compared via `pane_id` — the stable
/// tmux pane identifier, #2453), in which case [`ManagedError::AlreadyAdopted`]
/// is still returned (auto-suffixing would fork ONE real pane into two
/// mismatched records — the exact hazard this guard exists to prevent); or
/// (b) the name was RECYCLED — the colliding record's pane has since died and
/// a genuinely different pane now answers to the same name — in which case the
/// new adoption is auto-suffixed (smallest free `-N` ordinal) and the LIVE tmux
/// session is physically renamed to match, so the record and its pane never
/// drift apart; a stale collider still CLAIMING liveness
/// (`Active`/`Provisioning`) is additionally converged to `Stopped` in the
/// same guard scope (its pane is provably dead — this is what
/// `reconcile_on_boot` would do at the next pass, done eagerly). When
/// `pane_id` is unknown on either side, (a) is assumed (the safe default). A
/// TERMINAL (`Decommissioned`/`Deleted`) record's name never blocks — this
/// method filters to non-terminal records only, matching `rename`'s
/// long-standing rule.
/// - **The collision check and the no-collision upsert run under ONE held
/// write lock; tmux subprocesses NEVER run under it** (#3698 round-2
/// HIGH-A). Reading the store to test for the name and then upserting must
/// be atomic — otherwise two concurrent `adopt_existing` calls for the same
/// `tmux_name` could both observe "absent" before either writes, producing
/// duplicate `Active` records (TOCTOU). But `store.write()` gates every
/// session-manager mutation daemon-wide and tmux calls are blocking
/// fork/exec/waits, so the `session_exists`/`get_pane_id`/`list_sessions`
/// preconditions all run BEFORE the guard, and the recycled-name branch
/// RELEASES the guard around its `rename_session`, then re-acquires and
/// RE-VERIFIES (deduped name still free) before persisting — rolling the
/// tmux rename back on any failure after it (#3698 round-2 HIGH-B), since
/// a live renamed session tracked by no record is the untracked-session
/// defect class #3692 exists to prevent.
/// - **No `create_session` call.** The pane already exists; the driver is only
/// consulted via `session_exists` to verify presence (and `rename_session` in
/// the recycled-name case above).
/// - **`cwd` is REQUIRED** (a plain `PathBuf`): the pane's provenance is unknown
/// to the daemon, so the operator supplies the working directory rather than
/// have it stubbed to `/unknown` (as auto-boot adoption does). `task` may be
/// empty. `runtime` is caller-supplied; call sites that do not care pass
/// [`crate::runtime::RuntimeKind::default`].
/// - **Non-managed names are ALLOWED.** Unlike `reconcile_on_boot` (which filters
/// to [`crate::core::names::is_managed_session_name`] — `tm-`/`tmpm-`/
/// `trusty-mpm-` — for SAFE automatic adoption), this explicit path
/// adopts ANY name the operator names. The reconcile filter is left untouched.
///
/// What: verifies the pane exists, resolves a collision-free name (auto-suffixing
/// a recycled name, rejecting only a genuine duplicate of the same pane), then
/// upserts an `Active` [`SessionRecord`] carrying the supplied `cwd`/`task`/
/// `runtime`/`ephemeral` (a fresh id, no workspace/repo/branch — provenance is
/// unknown). `ephemeral` (#1508) tags a throwaway adoption (e.g. an e2e test
/// pane) so the auto-reap paths may decommission it; operator adoptions pass
/// `false`. Returns the new record (its `tmux_name` may differ from the
/// requested `tmux_name` if it was auto-suffixed).
/// Test: `manager_adopt_existing_registers_active` (also asserts the returned
/// record's `cwd` matches the adopted cwd),
/// `manager_adopt_existing_missing_tmux_errors`,
/// `manager_adopt_existing_double_adopt_errors` (the single-locked path still
/// rejects a second adopt of the identical, already-tracked pane),
/// `manager_adopt_existing_allows_non_tmpm_name`,
/// `manager_adopt_existing_reuses_name_freed_by_decommissioned_record`,
/// `manager_adopt_existing_suffixes_recycled_name` in `super::tests`.
pub async fn adopt_existing(
&self,
tmux_name: &str,
cwd: PathBuf,
task: String,
runtime: crate::runtime::RuntimeKind,
ephemeral: bool,
) -> Result<SessionRecord, ManagedError> {
// The pane MUST already exist — adoption connects, it does not spawn.
// `tmux_driver()` is the public accessor over the shared driver Arc. This
// liveness check touches tmux (not the store), so it stays OUTSIDE the
// store write lock taken below.
if !self.tmux_driver().session_exists(tmux_name) {
return Err(ManagedError::TmuxSessionMissing(tmux_name.to_string()));
}
// Capture the pre-existing pane's stable tmux `pane_id` (#2453 review
// finding 1, round 2) — best-effort, `None` if the driver cannot
// resolve one. Adoption connects to an ALREADY-LIVE pane, so this is
// available immediately, unlike a fresh spawn. Also doubles (#3692) as
// the signal that tells a same-name collision below apart from a
// recycled one.
// #9004: with the server it was read on, or the record never owns it.
let (pane_id, tmux_server) =
super::pane_identity::capture(self.tmux_driver().as_ref(), tmux_name);
// Live-tmux snapshot BEFORE the guard (#3698 round-2 HIGH-A):
// `list_sessions` is a blocking tmux subprocess and must never run
// under the store write lock that gates every other mutation.
let live_names = self
.tmux
.list_sessions()
.map_err(|e| ManagedError::TmuxUnavailable(e.to_string()))?;
// One construction site for the adopted record, so the no-collision
// and recycled-name arms below cannot drift apart on any field.
let build_record = |final_name: String| SessionRecord {
id: ManagedSessionId::new(),
tmux_name: final_name,
cwd: cwd.clone(),
task: task.clone(),
state: ManagedSessionState::Active,
created_at: Utc::now(),
last_activity_at: None,
workspace_path: None,
repo_url: None,
branch: None,
pending_decision: None,
proposed_default: None,
correlation: Default::default(),
runtime,
ephemeral,
// Adopted sessions point at a pre-existing pane: the SM did NOT
// create the workspace, so decommission must never delete it (#1511).
workspace_owned: false,
// Adopted sessions have no tracked source project.
source_id: None,
claude_session_id: None,
scrollback_path: None,
last_cwd: None,
deliverable_id: None,
pane_id: pane_id.clone(),
tmux_server: tmux_server.clone(),
injection_status: Default::default(),
worktree_owner: None,
terminal_at: None,
stop_cause: None,
kind: super::SessionKind::Ordinary,
};
// ── Guard 1: collision check (+ the no-collision persist) — the
// existence scan and the upsert stay atomic under one held write
// guard, so two concurrent adopts of the same `tmux_name` cannot both
// pass the "absent" test and create duplicate `Active` records (the
// TOCTOU the pre-#2468 read-then-write split exposed). `all()`
// requires `&mut self` and reloads-on-read, so a record another
// process registered is also seen through this same guard. NO tmux
// subprocess runs while this guard is held (#3698 round-2 HIGH-A).
let mut store = self.store.write().await;
let existing = store.all().await?;
// A NON-terminal record already tracking this literal name (#3692):
// terminal (Decommissioned/Deleted) tombstones never block — their name
// is gone for good and reusable as-is.
let colliding = existing
.iter()
.find(|r| r.tmux_name == tmux_name && !r.state.is_terminal())
.cloned();
let record = match colliding {
None => {
let record = build_record(tmux_name.to_string());
store.upsert(record.clone()).await?;
drop(store);
record
}
Some(existing_record) => {
let same_pane = match (existing_record.pane_id.as_deref(), pane_id.as_deref()) {
(Some(a), Some(b)) => a == b,
// Pane identity unknown on at least one side: assume the
// same pane (safe default) — a second record for one real
// pane is exactly the hazard `AlreadyAdopted` guards against.
_ => true,
};
if same_pane {
return Err(ManagedError::AlreadyAdopted(tmux_name.to_string()));
}
// The name was RECYCLED — tmux now answers to it with a
// genuinely different pane than the stale record tracks.
// Auto-suffix (never reject, #3692) and physically rename the
// live tmux session so the new record and its pane stay in
// lock-step. The tmux rename runs OUTSIDE the guard (#3698
// round-2 HIGH-A), so the guard is dropped here and
// RE-ACQUIRED below with a re-verify before anything persists;
// every failure after the tmux rename rolls it back (#3698
// round-2 HIGH-B) — a live renamed session tracked by NO
// record is the untracked-session defect class #3692 exists
// to prevent.
let taken = Self::taken_name_set(&live_names, &existing, None);
let deduped = Self::dedupe_name_against(tmux_name, &taken);
drop(store);
self.tmux.rename_session(tmux_name, &deduped)?;
// ── Guard 2: re-verify, then persist; roll the tmux rename
// back on ANY failure from here on.
let mut store = self.store.write().await;
let records = match store.all().await {
Ok(r) => r,
Err(e) => {
drop(store);
return Err(self.rollback_adopt_rename(
&deduped,
tmux_name,
&format!("store reload failed: {e}"),
));
}
};
// Nobody may have claimed the deduped name while the lock was
// released across the tmux call.
if records
.iter()
.any(|r| r.tmux_name == deduped && !r.state.is_terminal())
{
drop(store);
return Err(self.rollback_adopt_rename(
&deduped,
tmux_name,
&format!("'{deduped}' was claimed concurrently — retry the adopt"),
));
}
// #3692 review MEDIUM: the pane-id mismatch above is proof the
// stale record's own pane is DEAD (tmux enforces name
// uniqueness — a different pane answering to its name means
// its pane is gone). If that record still CLAIMS to be live
// (Active/Provisioning), converge it to `Stopped` now, in this
// same guard scope, instead of leaving a live-looking record
// whose name points at somebody else's pane until the next
// reconcile pass. `Stopped` (not a terminal state) is
// deliberate: it matches what `reconcile_on_boot` would do on
// discovering the dead pane, and keeps the record resumable —
// its name stays reserved for it (non-terminal ⇒ taken), which
// is exactly why THIS adoption takes the suffix instead.
// (Converging first, adopting second: if the second write
// fails, a converged-but-unadopted Stopped record is still
// CORRECT — its pane really is dead — so only the tmux rename
// needs compensating.)
if let Some(stale) = records.iter().find(|r| {
r.id == existing_record.id
&& matches!(
r.state,
ManagedSessionState::Active | ManagedSessionState::Provisioning
)
}) {
let mut stale = stale.clone();
stale.state = ManagedSessionState::Stopped;
// #6194: every transition into Stopped records why. This
// one converges a record whose pane is simply dead —
// nobody asked for it — which is what the record already
// read as before the field existed, so this is a
// behavior-preserving write that keeps the invariant
// total. `get_or_insert` so an earlier Deliberate stands.
stale.stop_cause.get_or_insert(StopCause::Unexpected);
stale.last_activity_at = Some(Utc::now());
if let Err(e) = store.upsert(stale).await {
drop(store);
return Err(self.rollback_adopt_rename(
&deduped,
tmux_name,
&format!("store write failed: {e}"),
));
}
}
let record = build_record(deduped.clone());
if let Err(e) = store.upsert(record.clone()).await {
drop(store);
return Err(self.rollback_adopt_rename(
&deduped,
tmux_name,
&format!("store write failed: {e}"),
));
}
drop(store);
record
}
};
// #7087: an adopted session can join the active-project set.
self.bump_residency_generation();
info!(
id = %record.id,
name = %record.tmux_name,
runtime = %runtime.as_str(),
"adopted existing tmux session into the managed store"
);
Ok(record)
}
/// Roll a half-applied recycled-name tmux rename back (`deduped` →
/// `original`) and build the error `adopt_existing` should surface
/// (#3698 round-2 HIGH-B).
///
/// Why: once the live tmux session has been renamed OUTSIDE the store
/// guard, any later failure — reload error, lost re-verify race, failed
/// upsert — would otherwise leave a live RENAMED session tracked by NO
/// record: exactly the untracked-session defect class #3692 exists to
/// prevent, and one this path alone could mint (pre-#3692 adopt never
/// mutated tmux). Mirrors `rename.rs`'s `rollback_rename`.
/// What: renames tmux back; on success returns a retryable
/// [`ManagedError::InvalidState`] carrying `cause`; on rollback failure
/// returns the explicit manual-recovery error naming the exact
/// `tmux rename-session` command to run.
/// Test: `manager_adopt_existing_rolls_back_tmux_rename_when_store_write_fails`
/// in `super::adopt_existing_tests`.
fn rollback_adopt_rename(&self, deduped: &str, original: &str, cause: &str) -> ManagedError {
match self.tmux.rename_session(deduped, original) {
Ok(()) => ManagedError::InvalidState(
original.to_string(),
format!("adopt aborted and rolled back ({cause})"),
),
Err(rollback) => ManagedError::InvalidState(
original.to_string(),
format!(
"adopt half-applied: the live tmux session was renamed to '{deduped}' but \
nothing was persisted ({cause}), and the rollback failed ({rollback}) — \
manually run `tmux rename-session -t {} {original}`",
crate::core::tmux::shell_exact_session_target(deduped)
),
),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Utc;
use std::process::Command;
fn make_record_with_workspace(workspace: PathBuf) -> SessionRecord {
SessionRecord {
id: ManagedSessionId::new(),
tmux_name: "tmpm-test".into(),
cwd: workspace.clone(),
task: "test".into(),
state: crate::session_manager::ManagedSessionState::Active,
created_at: Utc::now(),
last_activity_at: None,
workspace_path: Some(workspace),
repo_url: None,
branch: None,
pending_decision: None,
proposed_default: None,
correlation: Default::default(),
runtime: Default::default(),
ephemeral: false,
workspace_owned: false,
source_id: None,
claude_session_id: None,
scrollback_path: None,
last_cwd: None,
deliverable_id: None,
pane_id: None,
tmux_server: None,
injection_status: Default::default(),
worktree_owner: None,
terminal_at: None,
stop_cause: None,
kind: Default::default(),
}
}
fn make_record_unknown_cwd() -> SessionRecord {
SessionRecord {
id: ManagedSessionId::new(),
tmux_name: "tmpm-external".into(),
cwd: PathBuf::from("/unknown"),
task: "adopted session".into(),
state: crate::session_manager::ManagedSessionState::Active,
created_at: Utc::now(),
last_activity_at: None,
workspace_path: None,
repo_url: None,
branch: None,
pending_decision: None,
proposed_default: None,
correlation: Default::default(),
runtime: Default::default(),
ephemeral: false,
workspace_owned: false,
source_id: None,
claude_session_id: None,
scrollback_path: None,
last_cwd: None,
deliverable_id: None,
pane_id: None,
tmux_server: None,
injection_status: Default::default(),
worktree_owner: None,
terminal_at: None,
stop_cause: None,
kind: Default::default(),
}
}
/// Why: SSH scp-style remotes must yield a slugified owner/repo.
/// Test: itself.
#[test]
fn derive_source_id_ssh_remote() {
let tmp = crate::test_support::hermetic_temp_dir();
let dir = tmp.path();
let git = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.map(|o| o.status.success())
.unwrap_or(false)
};
if !git(&["init"]) {
return; // no git on runner
}
git(&[
"remote",
"add",
"origin",
"git@github.com:test-owner/my-repo.git",
]);
let record = make_record_with_workspace(dir.to_path_buf());
let sid = derive_source_id_for_record(&record).expect("should derive");
assert_eq!(sid, "test-owner/my-repo");
}
/// Why: HTTPS remotes must also yield a parseable owner/repo.
/// Test: itself.
#[test]
fn derive_source_id_https_remote() {
let tmp = crate::test_support::hermetic_temp_dir();
let dir = tmp.path();
let git = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.map(|o| o.status.success())
.unwrap_or(false)
};
if !git(&["init"]) {
return;
}
git(&[
"remote",
"add",
"origin",
"https://github.com/acme-org/my-project.git",
]);
let record = make_record_with_workspace(dir.to_path_buf());
let sid = derive_source_id_for_record(&record).expect("should derive");
assert_eq!(sid, "acme-org/my-project");
}
/// Why: a workspace with no git remote must return None gracefully.
/// Test: itself.
#[test]
fn derive_source_id_none_for_no_remote() {
let tmp = crate::test_support::hermetic_temp_dir();
let dir = tmp.path();
Command::new("git")
.arg("-C")
.arg(dir)
.arg("init")
.output()
.ok();
let record = make_record_with_workspace(dir.to_path_buf());
// No remote configured → derive must return None (never panic).
assert!(derive_source_id_for_record(&record).is_none());
}
/// Why: externally-adopted sessions with cwd="/unknown" and no workspace_path
/// must return None gracefully — never error the reconcile loop.
/// Test: itself.
#[test]
fn derive_source_id_none_for_unknown_path() {
let record = make_record_unknown_cwd();
assert!(derive_source_id_for_record(&record).is_none());
}
}