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
//! End-to-end coverage for gate 4b — a session-owned worktree is reclaimed only
//! when its owner is provably gone (#7652).
//!
//! Why: the hole was a chain, not a function. Gate 2 permits a live foreign
//! session's project-root claim over a nested worktree, gate 4 read a `Known`
//! sentinel as "no objection", and gates 5 and 6 then saw a merged, clean tree.
//! So every test here runs the real chain: a real session store behind
//! `workspace_claims`, a real git worktree carrying the owner's sentinel, and
//! the real survey or delete loop.
//! What: each test names one state of the owner's record and of tmux. These
//! tests use only interfaces that predate the fix, so the same file runs
//! against `76ad591ac`, where every refusal case below reclaims.
//! Test: this file IS the test module.

use std::cell::Cell;
use std::path::{Path, PathBuf};

use chrono::Utc;
use tempfile::TempDir;

use crate::session_manager::decommission::WORKTREE_SENTINEL_FILE;
use crate::session_manager::manager::SessionManager;
use crate::session_manager::record::{ManagedSessionId, ManagedSessionState, SessionRecord};
use crate::session_manager::tests::FakeTmuxDriver;
use crate::session_manager::worktree_git_fixture::GitWorktreeFixture;
use crate::session_manager::worktree_ownership::{
    AgentDelegationState, AgentWorktreeOwner, sentinel_payload_bytes,
};
use crate::session_manager::worktree_reclaim::{
    KeepList, LiveClaims, PrIndex, ReclaimMode, ReclaimVerdict,
};
use crate::session_manager::worktree_reclaim_sweep::{
    FreshProbes, SurveyBudget, reclaim_scoped, survey_with_index,
};

/// The owning session's record in the store.
#[derive(Clone, Copy)]
enum OwnerRecord {
    /// A record whose `workspace_path` is the project root (#7652's shape).
    ProjectRoot,
    /// A record with no `workspace_path` at all.
    NoWorkspace,
    /// No record names the owner.
    Absent,
}

/// What the tmux probe says about the owner's session.
#[derive(Clone, Copy)]
enum Tmux {
    /// tmux answers and lists the owner's session.
    ListsOwner,
    /// tmux answers and does not list it.
    OwnerGone,
    /// `tmux list-sessions` errors.
    Errors,
}

/// One scene: a landed worktree nested in the project, owned by a session.
struct Scene {
    fx: GitWorktreeFixture,
    wt: PathBuf,
    branch: String,
    owner: ManagedSessionId,
}

fn record(tmux_name: &str, workspace: Option<&Path>) -> SessionRecord {
    SessionRecord {
        id: ManagedSessionId::for_adopted_tmux_name(tmux_name),
        tmux_name: tmux_name.to_owned(),
        cwd: workspace.map(Path::to_path_buf).unwrap_or_default(),
        task: "owns a nested worktree".into(),
        // #2919: the state field is never the liveness test, so it is terminal
        // here in every scene, live ones included.
        state: ManagedSessionState::Deleted,
        created_at: Utc::now(),
        last_activity_at: None,
        workspace_path: workspace.map(Path::to_path_buf),
        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(),
    }
}

/// A merged, clean worktree at `<repo>/.worktrees/<name>` owned by `tm-<name>`.
fn scene(name: &str) -> Scene {
    let fx = GitWorktreeFixture::new();
    let wt = fx.add_worktree(name);
    std::fs::write(wt.join("landed.rs"), "// landed\n").expect("write landed file");
    GitWorktreeFixture::commit_all_and_push(&wt, "landed");
    let owner = ManagedSessionId::for_adopted_tmux_name(&format!("tm-{name}"));
    std::fs::write(
        wt.join(WORKTREE_SENTINEL_FILE),
        sentinel_payload_bytes(owner),
    )
    .expect("write the owner's sentinel");
    Scene {
        branch: format!("session/{name}"),
        fx,
        wt,
        owner,
    }
}

/// The claim set the daemon's own producer builds for this store and tmux.
async fn claims(scene: &Scene, name: &str, rec: OwnerRecord, tmux: Tmux) -> LiveClaims {
    let tmux_name = format!("tm-{name}");
    let dir = TempDir::new().expect("tempdir");
    let fake = FakeTmuxDriver::new();
    if matches!(tmux, Tmux::ListsOwner) {
        fake.seeded_names
            .lock()
            .expect("lock")
            .push(tmux_name.clone());
    }
    let mgr = SessionManager::new(dir.path(), fake.clone())
        .await
        .expect("manager");
    let workspace = match rec {
        OwnerRecord::ProjectRoot => Some(scene.fx.repo.as_path()),
        OwnerRecord::NoWorkspace | OwnerRecord::Absent => None,
    };
    if !matches!(rec, OwnerRecord::Absent) {
        let mut store = mgr.store.write().await;
        store
            .upsert(record(&tmux_name, workspace))
            .await
            .expect("upsert");
    }
    if matches!(tmux, Tmux::Errors) {
        *fake.list_sessions_should_fail.lock().expect("lock") = true;
    }
    mgr.workspace_claims(Some("tm-caller-7652".to_string()))
        .await
}

fn no_agents(_: &AgentWorktreeOwner) -> AgentDelegationState {
    AgentDelegationState::Unknown
}

fn merged_index(branch: &str) -> PrIndex {
    PrIndex::from_json(
        &format!(r#"[{{"number": 7652, "headRefName": "{branch}", "state": "MERGED"}}]"#),
        400,
    )
}

/// The survey's verdict for the scene's worktree.
fn verdict(scene: &Scene, claims: &LiveClaims) -> ReclaimVerdict {
    let branch = scene.branch.clone();
    let survey = survey_with_index(
        &scene.fx.repos_root,
        claims,
        &|_: &Path| merged_index(&branch),
        &no_agents,
        SurveyBudget::default(),
        false,
        &KeepList::default(),
        &[],
    );
    survey
        .candidates
        .into_iter()
        .find(|c| c.path == scene.wt)
        .unwrap_or_else(|| panic!("the survey must list {}", scene.wt.display()))
        .verdict
}

/// Assert a refusal that names the owner, and return its text.
fn refused(v: &ReclaimVerdict, owner: &ManagedSessionId) -> String {
    let reason = match v {
        ReclaimVerdict::Blocked { reason, .. } | ReclaimVerdict::BlockedByAgent { reason, .. } => {
            reason.clone()
        }
        // #7889: both grant kinds are the same failure here — gate 4b must
        // refuse before either can be reached.
        ReclaimVerdict::Reclaimable { .. } | ReclaimVerdict::ReclaimableLandedContent { .. } => {
            panic!("a session-owned tree whose owner is not proven gone was reclaimable: {v:?}")
        }
    };
    assert!(
        reason.contains(&owner.to_string()),
        "names the owner: {reason}"
    );
    assert!(reason.contains("#7652"), "{reason}");
    reason
}

/// 🔴 #7652 criterion 1: a LIVE owner's own nested worktree — merged PR, clean
/// tree — is refused. Fails on `76ad591ac`, where gate 4 read a `Known`
/// sentinel as no objection and this tree was `Reclaimable`.
#[tokio::test]
async fn worktree_7652_a_live_owners_nested_worktree_is_refused() {
    let s = scene("owner-live-7652");
    let c = claims(
        &s,
        "owner-live-7652",
        OwnerRecord::ProjectRoot,
        Tmux::ListsOwner,
    )
    .await;
    assert!(
        c.claim_state(&s.wt).refusal(false).is_none(),
        "premise: gate 2 permits a project-root claim over a nested worktree"
    );
    let reason = refused(&verdict(&s, &c), &s.owner);
    assert!(reason.contains("tmux still lists"), "{reason}");
}

/// 🔴 #7652 criterion 2: the same tree with an owner tmux no longer lists is
/// reclaimed. A gate that refuses every session-owned tree fails this.
#[tokio::test]
async fn worktree_7652_a_dead_owners_nested_worktree_is_reclaimed() {
    let s = scene("owner-dead-7652");
    let c = claims(
        &s,
        "owner-dead-7652",
        OwnerRecord::ProjectRoot,
        Tmux::OwnerGone,
    )
    .await;
    assert_eq!(verdict(&s, &c), ReclaimVerdict::Reclaimable { pr: 7652 });
}

/// 🔴 #7652 criterion 3: no stored record names the owner. tmux answered, but
/// nothing ties its silence to this session, so unrecorded is not dead.
/// Fails against a version where an unrecorded owner permits.
#[tokio::test]
async fn worktree_7652_an_owner_with_no_record_is_refused() {
    let s = scene("owner-unrecorded-7652");
    let c = claims(
        &s,
        "owner-unrecorded-7652",
        OwnerRecord::Absent,
        Tmux::OwnerGone,
    )
    .await;
    let reason = refused(&verdict(&s, &c), &s.owner);
    assert!(reason.contains("no stored session record"), "{reason}");
    // #7652 critic round 2: `tm sessions prune` compacts tombstones, so this
    // refusal can be permanent — it has to name the way out of it.
    assert!(reason.contains("git worktree remove"), "{reason}");
    assert!(reason.contains("tm sessions prune"), "{reason}");
}

/// 🔴 #7652 criterion 3: a record with no `workspace_path` is still the owner's
/// record. Live in tmux, it refuses — the claim-list-derived map the previous
/// attempt used read it as unrecorded and permitted. Gone from an answering
/// tmux, it reclaims: that is the one evidence of death gate 4b accepts.
#[tokio::test]
async fn worktree_7652_owners_include_a_record_with_no_workspace_path() {
    let live = scene("owner-noworkspace-live-7652");
    let c = claims(
        &live,
        "owner-noworkspace-live-7652",
        OwnerRecord::NoWorkspace,
        Tmux::ListsOwner,
    )
    .await;
    refused(&verdict(&live, &c), &live.owner);

    let dead = scene("owner-noworkspace-dead-7652");
    let c = claims(
        &dead,
        "owner-noworkspace-dead-7652",
        OwnerRecord::NoWorkspace,
        Tmux::OwnerGone,
    )
    .await;
    assert_eq!(verdict(&dead, &c), ReclaimVerdict::Reclaimable { pr: 7652 });
}

/// 🔴 #7652 criterion 3: an errored tmux probe is not an empty tmux (#5856).
/// Fails against a version where the probe's error defaults to "not alive".
#[tokio::test]
async fn worktree_7652_an_errored_tmux_probe_is_refused() {
    let s = scene("owner-tmux-error-7652");
    let c = claims(
        &s,
        "owner-tmux-error-7652",
        OwnerRecord::ProjectRoot,
        Tmux::Errors,
    )
    .await;
    refused(&verdict(&s, &c), &s.owner);
}

/// 🔴 #7652 criterion 3: a claim probe that cannot answer. The delete loop's
/// probe returns `None` — the daemon's does when no tokio runtime handle is
/// available, while `SessionManager::list` falls back to its cached records on a
/// failed reload and never yields `None` — so the survey falls back to an empty
/// claim set. That fallback must refuse the session-owned tree at
/// classification, not merely at the pre-delete re-check. Fails on
/// `76ad591ac`, whose survey reported the tree reclaimable.
#[test]
fn worktree_7652_an_unanswerable_claim_probe_reclaims_nothing() {
    let s = scene("owner-store-unreadable-7652");
    let branch = s.branch.clone();
    let out = reclaim_scoped(
        &s.fx.repos_root,
        &FreshProbes {
            prove: &crate::session_manager::worktree_reclaim_landed::reclaim_landed_proof,
            launched_from: &[],
            cwd_holder: &|_| None,
            keep_list: &KeepList::default,
            agent_state: &no_agents,
            in_use_now: &|| None,
            index_for: &|_: &Path| merged_index(&branch),
        },
        ReclaimMode::Remove,
        &[],
        &crate::session_manager::worktree_scope::WorktreeScope::all(),
    );
    assert!(out.removed.is_empty(), "{out:?}");
    assert!(s.wt.exists(), "the tree must still be on disk");
    let candidate = out
        .survey
        .candidates
        .iter()
        .find(|c| c.path == s.wt)
        .expect("listed");
    refused(&candidate.verdict, &s.owner);
}

/// 🔴 #7652: the pre-delete re-check reads the FRESH owner map. The survey saw
/// the owner gone; by the delete the owner's tmux session is back. Fails if
/// gate 4b lives only in `classify`, and on `76ad591ac`, which deletes.
#[tokio::test]
async fn worktree_7652_the_recheck_refuses_an_owner_that_came_back() {
    let s = scene("owner-came-back-7652");
    let name = "owner-came-back-7652";
    let gone = claims(&s, name, OwnerRecord::ProjectRoot, Tmux::OwnerGone).await;
    let back = claims(&s, name, OwnerRecord::ProjectRoot, Tmux::ListsOwner).await;
    let reads = Cell::new(0usize);
    let branch = s.branch.clone();
    let out = reclaim_scoped(
        &s.fx.repos_root,
        &FreshProbes {
            prove: &crate::session_manager::worktree_reclaim_landed::reclaim_landed_proof,
            launched_from: &[],
            cwd_holder: &|_| None,
            keep_list: &KeepList::default,
            agent_state: &no_agents,
            // First read feeds the survey; every later one is the re-check's.
            in_use_now: &|| {
                reads.set(reads.get() + 1);
                Some(if reads.get() == 1 {
                    gone.clone()
                } else {
                    back.clone()
                })
            },
            index_for: &|_: &Path| merged_index(&branch),
        },
        ReclaimMode::Remove,
        &[],
        &crate::session_manager::worktree_scope::WorktreeScope::all(),
    );
    assert!(out.removed.is_empty(), "{out:?}");
    assert!(s.wt.exists(), "the returning owner's tree must survive");
    assert!(
        out.refused_at_recheck
            .iter()
            .any(|r| r.contains("#7652") && r.contains(&s.owner.to_string())),
        "{:?}",
        out.refused_at_recheck
    );
}

/// 🔴 #7652 critic round: the claim read that decides is the one taken AFTER the
/// pre-delete re-check's dirt probe, immediately before the removal.
///
/// Why: `recheck_before_delete` reads the claims before git, the harness-lock
/// probe and `inspect_dirt`, which takes seconds on a large tree, and `--force`
/// follows. Here the survey and the re-check both see the owner gone, and the
/// owner is back by the third read. Fails on `e21a6ba0b`, which reads the
/// claims twice and deletes the tree.
#[tokio::test]
async fn worktree_7652_an_owner_back_after_the_dirt_check_is_refused() {
    let s = scene("owner-back-late-7652");
    let name = "owner-back-late-7652";
    let gone = claims(&s, name, OwnerRecord::ProjectRoot, Tmux::OwnerGone).await;
    let back = claims(&s, name, OwnerRecord::ProjectRoot, Tmux::ListsOwner).await;
    let reads = Cell::new(0usize);
    let branch = s.branch.clone();
    let out = reclaim_scoped(
        &s.fx.repos_root,
        &FreshProbes {
            prove: &crate::session_manager::worktree_reclaim_landed::reclaim_landed_proof,
            launched_from: &[],
            cwd_holder: &|_| None,
            keep_list: &KeepList::default,
            agent_state: &no_agents,
            // Reads 1 and 2 are the survey's and the re-check's.
            in_use_now: &|| {
                reads.set(reads.get() + 1);
                Some(if reads.get() <= 2 {
                    gone.clone()
                } else {
                    back.clone()
                })
            },
            index_for: &|_: &Path| merged_index(&branch),
        },
        ReclaimMode::Remove,
        &[],
        &crate::session_manager::worktree_scope::WorktreeScope::all(),
    );
    assert!(out.removed.is_empty(), "{out:?}");
    assert!(s.wt.exists(), "the returning owner's tree must survive");
    assert!(
        out.refused_at_recheck
            .iter()
            .any(|r| r.contains("#7652") && r.contains(&s.owner.to_string())),
        "{:?}",
        out.refused_at_recheck
    );
}