trusty-mpm 0.19.26

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
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
//! Project registry: lifecycle management and auto-registration.
//!
//! Why: the registry is the single authoritative source for known projects.
//! It seeds from `config.yaml`'s `projects:` list on startup, auto-registers
//! projects implied by session history, and exposes typed register/get/list ops
//! for the MCP tools and CLI.
//! What: [`ProjectRegistry`] wraps a [`ProjectStore`] in an async `RwLock`,
//! exposes `register` (idempotent upsert), `get`, and `list`; `seed_from_config`
//! upserts statically-declared entries; `auto_register_from_sessions` derives
//! implicit entries from existing session records. [`update_with`](ProjectRegistry::update_with)
//! is the atomic read-mutate-persist seam a PATCH handler MUST use (#2481 review
//! HIGH): it holds ONE write-lock guard across the whole fetch→mutate→persist
//! sequence, mirroring [`crate::deliverable::manager::DeliverableManager::update_deliverable_with`]
//! (#2395) — `get` followed later by a separate `register` call (two distinct
//! lock acquisitions) leaves a window where a concurrent caller's own
//! get-then-register can land in between, and whichever `register` runs last
//! silently discards the other's update because each call persists a FULL
//! record built from its own (by-then-stale) snapshot.
//! Test: `registry_register_idempotent`, `registry_list`, `registry_get`,
//! `registry_seed_from_config`, `registry_auto_register_from_sessions`,
//! `registry_derive_name_skips_missing_url`,
//! `get_then_register_pattern_reproduces_lost_update_pre_fix`,
//! `update_with_serializes_concurrent_field_edits`,
//! `update_with_unknown_project_errors`.

use std::path::Path;
use std::sync::Arc;

use tokio::sync::RwLock;
use tracing::{debug, info, warn};

use super::record::{Project, derive_name_from_url};
use super::store::{ProjectStore, ProjectStoreError};
use crate::core::trusty_tools_config::ProjectConfig;
use crate::session_manager::record::SessionRecord;

/// Async project registry backed by an on-disk JSON store.
///
/// Why: the daemon and MCP tools need a single shared, thread-safe view of all
/// known projects. Wrapping the store in an `Arc<RwLock<…>>` follows the same
/// pattern as the session manager.
/// What: wraps a `ProjectStore` with async shared-mutable access; all mutating
/// ops (register, seed, auto-register) take a write lock; reads take a read
/// lock by re-reading through the store.
/// Test: `registry_register_idempotent`, `registry_list`, `registry_get`.
#[derive(Debug, Clone)]
pub struct ProjectRegistry {
    store: Arc<RwLock<ProjectStore>>,
}

impl ProjectRegistry {
    /// Load (or create) the project registry at the given data directory.
    ///
    /// Why: on startup the daemon restores the registry from the previous run;
    /// an absent `projects.json` starts a fresh, empty registry.
    /// What: constructs a `ProjectStore` from `<data_dir>/projects.json` and
    /// wraps it in an `Arc<RwLock>`.
    /// Test: `registry_register_idempotent`.
    pub async fn load(data_dir: &Path) -> Result<Self, ProjectStoreError> {
        let store = ProjectStore::load(data_dir).await?;
        Ok(Self {
            store: Arc::new(RwLock::new(store)),
        })
    }

    /// Idempotent upsert: register or update a project by name.
    ///
    /// Why: registration must be safe to call multiple times — re-registering
    /// with updated fields updates rather than duplicates the entry.
    /// What: acquires a write lock and calls `ProjectStore::upsert`.
    /// Test: `registry_register_idempotent`.
    pub async fn register(&self, project: Project) -> Result<(), ProjectStoreError> {
        let mut guard = self.store.write().await;
        guard.upsert(project).await
    }

    /// Look up a project by name.
    ///
    /// Why: MCP `project_get` and session spawning need a point-lookup by name.
    /// What: acquires a write lock (required by store reload semantics) and
    /// returns a clone of the matching project or `ProjectStoreError::NotFound`.
    /// Test: `registry_get`.
    pub async fn get(&self, name: &str) -> Result<Project, ProjectStoreError> {
        let mut guard = self.store.write().await;
        guard.get(name).await
    }

    /// Return all registered projects.
    ///
    /// Why: MCP `project_list` needs the full set; the auto-registration pass
    /// uses it to avoid re-registering existing entries.
    /// What: acquires a write lock (required by store reload semantics) and
    /// returns all project records.
    /// Test: `registry_list`.
    pub async fn list(&self) -> Result<Vec<Project>, ProjectStoreError> {
        let mut guard = self.store.write().await;
        guard.all().await
    }

    /// Atomically read-mutate-persist a project under ONE lock.
    ///
    /// Why (fixes the #2481 review HIGH): `PATCH /api/v1/projects/{name}`
    /// originally called [`get`](Self::get) (one write-lock acquisition),
    /// released the lock, mutated a CLONE in the caller, then separately
    /// called [`register`](Self::register) (a SECOND, later acquisition) to
    /// persist the FULL replacement record. Two concurrent PATCHes to the
    /// SAME project — even ones editing completely DIFFERENT fields — can
    /// both fetch the same stale snapshot in the gap between those two calls;
    /// each then persists a full record built from that stale snapshot, so
    /// whichever `register` lands last silently overwrites the other's
    /// already-"successful" field edit with no error ever surfacing to that
    /// caller. This is the exact lost-update hazard #2395 already fixed for
    /// `DeliverableManager::update_deliverable_with`.
    /// What: acquires `self.store.write().await` ONCE and holds the guard for
    /// the ENTIRE fetch→mutate→persist sequence. Fetches the CURRENT on-disk
    /// record via the store's own reload-on-read `get` (`NotFound` propagates
    /// unchanged), calls `f` with that freshly-reloaded record, persists `f`'s
    /// (infallible — Project PATCH has no state-machine rejection path, unlike
    /// Deliverable's §10.3 transitions) result, and returns it — all before
    /// releasing the lock, so no other task can observe or clobber the
    /// intermediate state.
    /// Test: `update_with_serializes_concurrent_field_edits` (the concurrency
    /// regression test — proves two concurrent edits to DIFFERENT fields are
    /// both present in the final persisted record, never one lost), and
    /// `update_with_unknown_project_errors`.
    pub async fn update_with<F>(&self, name: &str, f: F) -> Result<Project, ProjectStoreError>
    where
        F: FnOnce(Project) -> Project,
    {
        let mut guard = self.store.write().await;
        let current = guard.get(name).await?;
        let updated = f(current);
        guard.upsert(updated.clone()).await?;
        Ok(updated)
    }

    /// Seed the registry from statically-declared `projects:` config entries.
    ///
    /// Why: #1519 MR-1 — operators can declare projects in
    /// `~/.trusty-tools/trusty-mpm/config.yaml` under a `projects:` key so the
    /// registry is pre-populated without manual MCP calls.
    /// What: upserts each `ProjectConfig` entry into the store. Errors on
    /// individual entries are logged and skipped so a bad entry does not abort
    /// the whole seed pass.
    /// Test: `registry_seed_from_config`.
    pub async fn seed_from_config(&self, config_projects: &[ProjectConfig]) {
        for entry in config_projects {
            let project = Project {
                name: entry.name.clone(),
                repo_url: entry.repo_url.clone(),
                default_branch: entry
                    .default_branch
                    .clone()
                    .unwrap_or_else(|| "main".to_string()),
                stack_hint: entry.stack_hint.clone(),
                tags: entry.tags.clone().unwrap_or_default(),
                description: entry.description.clone(),
                gh_user: entry.gh_user.clone(),
                // #3025: mirror the pinned spawn-time gh account the same way.
                gh_account: entry.gh_account.clone(),
                // #2184: mirror the per-project gh identity + commit identity
                // onto the registry record so `project_get`/`project_list`
                // surface it without a separate config-file read.
                github: entry.github.clone(),
                commit_name: entry.commit_name.clone(),
                commit_email: entry.commit_email.clone(),
            };
            let name = project.name.clone();
            if let Err(e) = self.register(project).await {
                warn!(name = %name, "seed_from_config: failed to register project: {e}");
            } else {
                debug!(name = %name, "seed_from_config: registered project");
            }
        }
    }

    /// Auto-register projects implied by existing session records.
    ///
    /// Why: #1519 MR-1 boot auto-registration — the daemon's reconcile pass
    /// already has access to all session records; this pass derives `Project`
    /// entries from records that have a `repo_url` but are not yet in the
    /// registry, populating it without operator effort.
    /// What: for each session record with a `repo_url` not already registered,
    /// derives a name from the repo URL basename (stripping `.git`) and upserts
    /// an implicit `Project`. The `default_branch` comes from the record's
    /// `branch` field, falling back to `"main"`.
    /// Test: `registry_auto_register_from_sessions`,
    /// `registry_derive_name_skips_missing_url`.
    pub async fn auto_register_from_sessions(&self, records: &[SessionRecord]) {
        // Collect existing names to avoid overwriting manually-registered entries.
        let existing: std::collections::HashSet<String> = match self.list().await {
            Ok(projects) => projects.into_iter().map(|p| p.name).collect(),
            Err(e) => {
                warn!("auto_register: failed to list existing projects: {e}");
                return;
            }
        };

        for record in records {
            let Some(repo_url) = &record.repo_url else {
                continue;
            };
            let Some(name) = derive_name_from_url(repo_url) else {
                warn!(
                    repo_url = %repo_url,
                    "auto_register: could not derive project name from URL; skipping"
                );
                continue;
            };
            if existing.contains(&name) {
                debug!(name = %name, "auto_register: project already registered; skipping");
                continue;
            }
            let default_branch = record.branch.clone().unwrap_or_else(|| "main".to_string());
            let project = Project {
                name: name.clone(),
                repo_url: repo_url.clone(),
                default_branch,
                stack_hint: None,
                tags: vec![],
                description: None,
                gh_user: None,
                gh_account: None,
                // No source of a gh/commit identity binding for an implicitly
                // auto-registered project (#2184) — the operator declares
                // these explicitly via `config.projects`/`config_write`.
                github: None,
                commit_name: None,
                commit_email: None,
            };
            if let Err(e) = self.register(project).await {
                warn!(name = %name, "auto_register: failed to register: {e}");
            } else {
                info!(name = %name, repo_url = %repo_url, "auto_register: registered project from session history");
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session_manager::record::{ManagedSessionId, ManagedSessionState, SessionRecord};
    use chrono::Utc;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn make_session_with_repo(repo_url: &str, branch: Option<&str>) -> SessionRecord {
        SessionRecord {
            id: ManagedSessionId::new(),
            tmux_name: "tmpm-test".into(),
            cwd: PathBuf::from("/tmp"),
            task: "test".into(),
            state: ManagedSessionState::Active,
            created_at: Utc::now(),
            last_activity_at: None,
            workspace_path: None,
            repo_url: Some(repo_url.to_string()),
            branch: branch.map(String::from),
            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,
            injection_status: Default::default(),
        }
    }

    fn make_session_no_repo() -> SessionRecord {
        SessionRecord {
            id: ManagedSessionId::new(),
            tmux_name: "tmpm-no-repo".into(),
            cwd: PathBuf::from("/tmp"),
            task: "no repo".into(),
            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: 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,
            injection_status: Default::default(),
        }
    }

    #[tokio::test]
    async fn registry_register_idempotent() {
        let dir = TempDir::new().expect("tempdir");
        let registry = ProjectRegistry::load(dir.path()).await.expect("load");

        let p = Project {
            name: "alpha".into(),
            repo_url: "https://github.com/o/alpha".into(),
            default_branch: "main".into(),
            stack_hint: None,
            tags: vec![],
            description: None,
            gh_user: None,
            gh_account: None,
            github: None,
            commit_name: None,
            commit_email: None,
        };
        registry.register(p.clone()).await.expect("register once");
        registry
            .register(p)
            .await
            .expect("register again (idempotent)");

        let all = registry.list().await.expect("list");
        assert_eq!(all.len(), 1, "idempotent registration must not duplicate");
    }

    #[tokio::test]
    async fn registry_get() {
        let dir = TempDir::new().expect("tempdir");
        let registry = ProjectRegistry::load(dir.path()).await.expect("load");

        let p = Project {
            name: "beta".into(),
            repo_url: "https://github.com/o/beta".into(),
            default_branch: "develop".into(),
            stack_hint: Some("rust".into()),
            tags: vec!["backend".into()],
            description: Some("desc".into()),
            gh_user: Some("bob-work".into()),
            gh_account: None,
            github: None,
            commit_name: None,
            commit_email: None,
        };
        registry.register(p.clone()).await.expect("register");

        let got = registry.get("beta").await.expect("get");
        assert_eq!(got.name, "beta");
        assert_eq!(got.default_branch, "develop");
        assert_eq!(got.stack_hint.as_deref(), Some("rust"));
        assert_eq!(got.gh_user.as_deref(), Some("bob-work"));

        let err = registry.get("nonexistent").await;
        assert!(matches!(err, Err(ProjectStoreError::NotFound(_))));
    }

    fn make_project(name: &str) -> Project {
        Project {
            name: name.into(),
            repo_url: format!("https://github.com/o/{name}"),
            default_branch: "main".into(),
            stack_hint: None,
            tags: vec![],
            description: None,
            gh_user: None,
            gh_account: None,
            github: None,
            commit_name: None,
            commit_email: None,
        }
    }

    /// `update_with` propagates `NotFound` for an unregistered project and
    /// never calls the mutation closure (there is nothing to mutate).
    #[tokio::test]
    async fn update_with_unknown_project_errors() {
        let dir = TempDir::new().expect("tempdir");
        let registry = ProjectRegistry::load(dir.path()).await.expect("load");
        let err = registry
            .update_with("nope", |p| p)
            .await
            .expect_err("unknown project must error");
        assert!(matches!(err, ProjectStoreError::NotFound(_)));
    }

    /// Reproduces, using the still-available low-level primitives (`get` +
    /// `register`), the EXACT pre-fix PATCH hazard the #2481 review flagged as
    /// a HIGH: a `get` under one lock followed LATER by a separate `register`
    /// under a second lock leaves a window in which another task's own
    /// get-then-register sequence can run to completion entirely — both tasks
    /// build their full replacement record from the SAME stale snapshot, so
    /// whichever `register` lands last silently discards the other's
    /// already-"successful" field edit. This is the exact two-call shape the
    /// OLD `patch_project_registry_route` used (fetch under one lock, mutate a
    /// clone, then persist under a later, separate lock) — the shape
    /// `update_with` replaces. A `tokio::sync::Notify` gate forces the
    /// deterministic interleave (B's whole get-mutate-register sequence
    /// completes while A is parked between its OWN get and its OWN register),
    /// so the outcome never depends on scheduler luck.
    /// Test: this IS the test (the #2481 HIGH regression guard, negative case).
    #[tokio::test]
    async fn get_then_register_pattern_reproduces_lost_update_pre_fix() {
        let dir = TempDir::new().expect("tempdir");
        let registry = Arc::new(ProjectRegistry::load(dir.path()).await.expect("load"));
        registry
            .register(make_project("widget"))
            .await
            .expect("seed");

        // Gate: task A fetches, then PARKS here — simulating the exact window
        // the two-lock pattern leaves open between its `get` and its
        // `register` — until B has fetched, mutated, AND registered its own
        // (different field) edit.
        let gate = Arc::new(tokio::sync::Notify::new());

        let reg_a = Arc::clone(&registry);
        let gate_a = Arc::clone(&gate);
        let a = tokio::spawn(async move {
            // Lock #1 (fetch), released as soon as `get` returns — exactly the
            // OLD handler's read.
            let mut current = reg_a.get("widget").await.unwrap();
            // Park until B's own get-mutate-register has fully landed.
            gate_a.notified().await;
            current.description = Some("set by A".into());
            // Lock #2 (register) — a SEPARATE, later acquisition than lock #1.
            reg_a.register(current).await.unwrap();
        });

        let reg_b = Arc::clone(&registry);
        let gate_b = Arc::clone(&gate);
        let b = tokio::spawn(async move {
            let mut current = reg_b.get("widget").await.unwrap();
            current.stack_hint = Some("rust".into());
            reg_b.register(current).await.unwrap();
            // B's committed write has landed — release A to clobber it.
            gate_b.notify_one();
        });

        b.await.unwrap();
        a.await.unwrap();

        // The bug: B's committed `stack_hint` edit is silently discarded — A's
        // later `register` persists a full record built from a snapshot taken
        // BEFORE B's write, so A's own field lands but B's is gone, with no
        // error ever surfaced to B's caller (B's own call returned Ok).
        let final_state = registry.get("widget").await.unwrap();
        assert_eq!(final_state.description.as_deref(), Some("set by A"));
        assert_eq!(
            final_state.stack_hint, None,
            "demonstrates the pre-fix hazard: B's committed stack_hint edit is \
             lost — silently clobbered by A's later register() against a \
             stale snapshot, even though B's own call reported success"
        );
    }

    /// Proves the fix: racing two `update_with` calls that edit DIFFERENT
    /// fields of the SAME project can never lose either edit — both are
    /// present in the final persisted record, regardless of which task's
    /// write lands first. Pre-fix (the two-lock pattern exercised by
    /// `get_then_register_pattern_reproduces_lost_update_pre_fix` above), this
    /// same race would silently drop whichever edit lost the race.
    /// Test: this IS the test (the #2481 HIGH regression guard, positive case).
    #[tokio::test]
    async fn update_with_serializes_concurrent_field_edits() {
        let dir = TempDir::new().expect("tempdir");
        let registry = Arc::new(ProjectRegistry::load(dir.path()).await.expect("load"));
        registry
            .register(make_project("widget"))
            .await
            .expect("seed");

        let reg_a = Arc::clone(&registry);
        let a = tokio::spawn(async move {
            reg_a
                .update_with("widget", |mut p| {
                    p.description = Some("set by A".into());
                    p
                })
                .await
        });

        let reg_b = Arc::clone(&registry);
        let b = tokio::spawn(async move {
            reg_b
                .update_with("widget", |mut p| {
                    p.stack_hint = Some("rust".into());
                    p
                })
                .await
        });

        a.await.unwrap().expect("A's update must succeed");
        b.await.unwrap().expect("B's update must succeed");

        // Both concurrent field edits must be present — neither was lost,
        // regardless of which task's write landed first.
        let final_state = registry.get("widget").await.unwrap();
        assert_eq!(final_state.description.as_deref(), Some("set by A"));
        assert_eq!(final_state.stack_hint.as_deref(), Some("rust"));
    }

    #[tokio::test]
    async fn registry_list() {
        let dir = TempDir::new().expect("tempdir");
        let registry = ProjectRegistry::load(dir.path()).await.expect("load");

        for name in ["gamma", "delta", "epsilon"] {
            let p = Project {
                name: name.into(),
                repo_url: format!("https://github.com/o/{name}"),
                default_branch: "main".into(),
                stack_hint: None,
                tags: vec![],
                description: None,
                gh_user: None,
                gh_account: None,
                github: None,
                commit_name: None,
                commit_email: None,
            };
            registry.register(p).await.expect("register");
        }

        let all = registry.list().await.expect("list");
        assert_eq!(all.len(), 3);
    }

    #[tokio::test]
    async fn registry_seed_from_config() {
        let dir = TempDir::new().expect("tempdir");
        let registry = ProjectRegistry::load(dir.path()).await.expect("load");

        let config_entries = vec![
            ProjectConfig {
                name: "from-config-a".into(),
                repo_url: "https://github.com/o/from-config-a".into(),
                default_branch: Some("main".into()),
                stack_hint: Some("python".into()),
                tags: Some(vec!["ml".into()]),
                description: Some("ml project".into()),
                gh_user: Some("bobmatnyc".into()),
                gh_account: Some("bobmatnyc".into()),
                github: Some(crate::core::trusty_tools_config::GithubConfig {
                    config_dir: Some("/home/bob/.config/gh-ml".into()),
                    token_env: None,
                    account: None,
                    host: None,
                }),
                commit_name: Some("ML Bot".into()),
                commit_email: Some("ml-bot@example.com".into()),
                untracked_sync: None,
            },
            ProjectConfig {
                name: "from-config-b".into(),
                repo_url: "https://github.com/o/from-config-b".into(),
                default_branch: None,
                stack_hint: None,
                tags: None,
                description: None,
                gh_user: None,
                gh_account: None,
                github: None,
                commit_name: None,
                commit_email: None,
                untracked_sync: None,
            },
        ];

        registry.seed_from_config(&config_entries).await;

        let all = registry.list().await.expect("list after seed");
        let names: Vec<&str> = all.iter().map(|p| p.name.as_str()).collect();
        assert!(names.contains(&"from-config-a"), "{names:?}");
        assert!(names.contains(&"from-config-b"), "{names:?}");

        let a = registry.get("from-config-a").await.expect("get a");
        assert_eq!(a.stack_hint.as_deref(), Some("python"));
        assert_eq!(a.default_branch, "main");
        assert_eq!(a.gh_user.as_deref(), Some("bobmatnyc"));
        assert_eq!(a.gh_account.as_deref(), Some("bobmatnyc"));
        // #2184: the github/commit-identity binding must be mirrored onto the
        // registry record verbatim.
        assert_eq!(
            a.github.as_ref().and_then(|g| g.config_dir.as_deref()),
            Some(std::path::Path::new("/home/bob/.config/gh-ml"))
        );
        assert_eq!(a.commit_name.as_deref(), Some("ML Bot"));
        assert_eq!(a.commit_email.as_deref(), Some("ml-bot@example.com"));

        // Entry without default_branch must fall back to "main"; gh_user and
        // the #2184 github/commit-identity fields stay unset (no regression
        // for configs that predate #2081/#2184).
        let b = registry.get("from-config-b").await.expect("get b");
        assert_eq!(b.default_branch, "main");
        assert_eq!(b.gh_user, None);
        assert_eq!(b.gh_account, None);
        assert_eq!(b.github, None);
        assert_eq!(b.commit_name, None);
        assert_eq!(b.commit_email, None);
    }

    #[tokio::test]
    async fn registry_auto_register_from_sessions() {
        let dir = TempDir::new().expect("tempdir");
        let registry = ProjectRegistry::load(dir.path()).await.expect("load");

        let sessions = vec![
            make_session_with_repo("https://github.com/owner/trusty-tools.git", Some("main")),
            make_session_with_repo("https://github.com/owner/another-repo", None),
            make_session_no_repo(), // must be silently skipped
        ];
        registry.auto_register_from_sessions(&sessions).await;

        let all = registry.list().await.expect("list after auto-register");
        let names: Vec<&str> = all.iter().map(|p| p.name.as_str()).collect();
        assert!(names.contains(&"trusty-tools"), "{names:?}");
        assert!(names.contains(&"another-repo"), "{names:?}");
        assert_eq!(all.len(), 2, "no-repo session must be skipped");

        let p = registry
            .get("trusty-tools")
            .await
            .expect("get trusty-tools");
        assert_eq!(p.default_branch, "main");
        assert_eq!(p.repo_url, "https://github.com/owner/trusty-tools.git");

        let p2 = registry
            .get("another-repo")
            .await
            .expect("get another-repo");
        assert_eq!(p2.default_branch, "main", "no branch falls back to main");
    }

    #[tokio::test]
    async fn registry_auto_register_skips_already_registered() {
        let dir = TempDir::new().expect("tempdir");
        let registry = ProjectRegistry::load(dir.path()).await.expect("load");

        // Pre-register with explicit description.
        let existing = Project {
            name: "trusty-tools".into(),
            repo_url: "https://github.com/owner/trusty-tools".into(),
            default_branch: "develop".into(),
            stack_hint: Some("rust".into()),
            tags: vec![],
            description: Some("manually registered".into()),
            gh_user: None,
            gh_account: None,
            github: None,
            commit_name: None,
            commit_email: None,
        };
        registry.register(existing).await.expect("pre-register");

        // Auto-register with a different URL for the same name — must not overwrite.
        let sessions = vec![make_session_with_repo(
            "https://github.com/owner/trusty-tools.git",
            Some("feature"),
        )];
        registry.auto_register_from_sessions(&sessions).await;

        let p = registry.get("trusty-tools").await.expect("get");
        assert_eq!(
            p.description.as_deref(),
            Some("manually registered"),
            "auto-register must not overwrite existing entry"
        );
        assert_eq!(p.default_branch, "develop");
    }
}