trusty-mpm 1.5.2

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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Launch-time `ws/<session-name>` workstream-activity label ensure (issue
//! #3726, PM-brief decision).
//!
//! Why: workstream activity is tracked on GitHub via a `ws/<session-name>`
//! label — explicitly NOT milestones, which stay reserved for epics/releases
//! (a GitHub repo allows only ONE milestone per issue, a slot epics/releases
//! already need; milestones are also a heavyweight lifecycle object, while a
//! workstream is ephemeral and freely renamable; labels, by contrast, are
//! multi-valued, cheap to create, and filterable exactly like the existing
//! `trusty-mpm` convention label). For the PM brief's `--label ws/<name>`
//! convention to work on the FIRST issue/PR a session ever files, the label
//! must already exist in the repo — `gh issue edit --add-label` fails on an
//! unknown label. This module makes label creation part of session launch
//! itself, so no PM ever hits that failure.
//! What: [`ensure_workstream_label`] is the launch-time entry point — given
//! the (optional) `repo_url` a session was spawned from, its workspace
//! directory, and its tmux session name, it derives the target
//! `<owner>/<repo>` (preferring the passed `repo_url`, falling back to the
//! workspace's own `git remote get-url origin`), and idempotently creates
//! `ws/<session-name>` via `gh label create --force` with a name-derived
//! stable color (see [`label_color_for`]). Every non-GitHub-remote case (no
//! origin, non-GitHub host, `gh` missing/unauthenticated/timed-out) is a
//! logged, non-fatal skip — [`LabelOutcome`] is returned for callers/tests
//! that want to observe the branch taken, but production call sites (session
//! launch) MUST treat every variant as fire-and-forget: this must NEVER block
//! or fail a session launch.
//! The same launch hook also ensures the two issue-lifecycle labels
//! ([`LIFECYCLE_LABELS`]) `tm-ticketing`'s Lifecycle section applies, for the
//! same first-use reason — see that constant for why they are created without
//! `--force`.
//! Test: `owner_repo_from_ssh_origin`, `owner_repo_from_https_origin`,
//! `owner_repo_rejects_non_github_host`, `label_color_is_stable_and_valid_hex`,
//! `label_color_differs_across_names`, `label_name_short_is_verbatim`,
//! `label_name_stays_within_github_cap`,
//! `label_name_long_is_truncated_with_hash_suffix`,
//! `label_name_distinct_long_names_get_distinct_labels`,
//! `ensure_skips_when_no_origin`, `ensure_skips_when_non_github`,
//! `ensure_skips_when_name_blank`, `ensure_creates_label_via_runner`,
//! `ensure_reports_runner_failure` drive the pure derivation + a scripted
//! [`GhLabelRunner`] fake — no live `gh`/network. The lifecycle-label half and
//! the launch-path failure contract are covered by
//! `lifecycle_label_table_is_valid`,
//! `lifecycle_labels_are_created_without_force`,
//! `lifecycle_labels_attempt_every_label_when_gh_fails`,
//! `launch_labels_ensure_all_three`,
//! `lifecycle_labels_run_even_when_workstream_label_fails`,
//! `workstream_label_runs_even_when_lifecycle_labels_fail`,
//! `launch_labels_survive_total_gh_failure`,
//! `launch_labels_skip_cleanly_on_non_github_remote`,
//! `launch_labels_ensure_lifecycle_labels_when_session_name_is_blank`.

use std::path::Path;
use std::time::Duration;

use trusty_common::github_path::GithubPath;

use crate::core::gh_account::run_bounded;

/// Bound for the `gh label create` call this module makes at session launch.
///
/// Why: a launch must never hang on a wedged/slow `gh` (stuck credential
/// helper, offline network). 5s mirrors `gh_account`'s `GH_ENFORCE_TIMEOUT` —
/// generous enough for a real call, short enough to never meaningfully delay
/// a launch that already performs a git clone and multiple deploy steps.
const GH_LABEL_TIMEOUT: Duration = Duration::from_secs(5);

/// Outcome of one [`ensure_workstream_label`] call.
///
/// Why: production call sites only log this, but the unit tests (and any
/// future `tm doctor` surfacing) need a typed way to assert which branch was
/// taken instead of scraping log text.
/// What: one variant per skip reason, plus `Ensured` (the `gh` call
/// succeeded) and `GhFailed` (a `gh` call was attempted and failed/timed out).
/// Test: every variant is asserted by name in this module's tests.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LabelOutcome {
    /// The label was created/updated via `gh label create --force`.
    Ensured,
    /// `session_name` was empty/whitespace — nothing to label with.
    SkippedBlankName,
    /// Neither the supplied `repo_url` nor the workspace's own git origin
    /// resolved to a remote URL.
    SkippedNoOrigin,
    /// The resolved origin is not a `github.com` remote.
    SkippedNonGithub,
    /// A `gh` call was attempted but failed (non-zero exit, spawn error, or
    /// timed out past [`GH_LABEL_TIMEOUT`]) — covers "gh missing",
    /// "unauthenticated", and "offline" alike, since all three surface as an
    /// unsuccessful `gh` invocation.
    GhFailed,
}

/// Ensure the `ws/<session_name>` label exists on the session's GitHub repo.
///
/// Why: see the module docs — this is the launch-time hook that makes the PM
/// brief's `--label ws/<name>` convention usable from a session's very first
/// issue/PR.
/// What: derives `<owner>/<repo>` (via [`owner_repo_from_origin`] on
/// `repo_url` when present, else by reading `workspace_dir`'s
/// `remote.origin.url`), then runs `gh label create ws/<session_name> --repo
/// <owner>/<repo> --color <hex> --description "trusty-mpm workstream
/// <session_name>" --force` through [`RealGhRunner`], bounded by
/// [`GH_LABEL_TIMEOUT`]. Every failure path is a logged, non-fatal skip — see
/// [`LabelOutcome`].
/// Test: `ensure_creates_label_via_runner`, `ensure_skips_when_no_origin`,
/// `ensure_skips_when_non_github`, `ensure_skips_when_name_blank`.
pub fn ensure_workstream_label(
    repo_url: Option<&str>,
    workspace_dir: &Path,
    session_name: &str,
) -> LabelOutcome {
    ensure_workstream_label_with(&RealGhRunner, repo_url, workspace_dir, session_name)
}

/// [`ensure_workstream_label`] with the `gh` invocation seam injected, so
/// tests can drive it with a scripted [`GhLabelRunner`] instead of a live
/// `gh`.
fn ensure_workstream_label_with<R: GhLabelRunner>(
    runner: &R,
    repo_url: Option<&str>,
    workspace_dir: &Path,
    session_name: &str,
) -> LabelOutcome {
    let name = session_name.trim();
    if name.is_empty() {
        tracing::debug!("workstream label: blank session name — skipping");
        return LabelOutcome::SkippedBlankName;
    }

    let gh_path = match resolve_github_repo(repo_url, workspace_dir) {
        Ok(gh_path) => gh_path,
        Err(skip) => {
            tracing::debug!(session = %name, ?skip, "workstream label: repo not resolvable — skipping");
            return skip;
        }
    };

    let label = label_name_for(name);
    let color = label_color_for(name);
    let description = format!("trusty-mpm workstream {name}");
    let repo = gh_path.rel_path();

    if runner.create_label(&repo, &label, &color, &description, true) {
        tracing::info!(session = %name, repo = %repo, label = %label, "workstream label ensured");
        LabelOutcome::Ensured
    } else {
        tracing::debug!(
            session = %name,
            repo = %repo,
            label = %label,
            "workstream label: `gh label create` failed/unavailable — skipping (non-fatal)"
        );
        LabelOutcome::GhFailed
    }
}

/// The issue-lifecycle labels the PM's ticketing lifecycle applies, as
/// `(name, color, description)`.
///
/// Why: a GitHub issue is only ever open or closed, so `tm-ticketing`'s
/// Lifecycle section expresses progress with an `in-progress` / `blocked`
/// label plus comments. `gh issue edit --add-label` fails on a label the repo
/// has never seen, so the rule cannot fire on first use unless launch creates
/// them — the same reason [`ensure_workstream_label`] exists.
/// What: colors are ones this workspace's repo already uses (`0E8A16` from
/// `tga`, `B60205` from `blocked-on-mvp`), so the two labels read as native
/// rather than framework-branded.
/// Test: `lifecycle_labels_are_created_without_force`,
/// `lifecycle_label_table_is_valid`.
const LIFECYCLE_LABELS: [(&str, &str, &str); 2] = [
    (
        "in-progress",
        "0E8A16",
        "Work has started; a session or agent is on it",
    ),
    (
        "blocked",
        "B60205",
        "Blocked on a prerequisite; not scheduled",
    ),
];

/// Ensure both [`LIFECYCLE_LABELS`] exist on `repo`, best-effort.
///
/// Why: see [`LIFECYCLE_LABELS`].
/// What: one plain `gh label create` per label — deliberately WITHOUT
/// `--force`, unlike the `ws/<session>` label. `ws/` is trusty-mpm's own
/// namespace, but `in-progress`/`blocked` are ordinary repo labels a project
/// may already own and have styled; `--force` would silently rewrite that
/// project's color and description on every session launch. A create that
/// fails because the label already exists is therefore the expected steady
/// state, indistinguishable here from a real `gh` failure and equally
/// harmless — both are debug-logged and neither is returned, because every
/// caller is fire-and-forget. Both labels are always attempted: a failure on
/// the first must not suppress the second.
/// Test: `lifecycle_labels_are_created_without_force`,
/// `lifecycle_labels_attempt_every_label_when_gh_fails`.
fn ensure_lifecycle_labels_with<R: GhLabelRunner>(runner: &R, repo: &str) {
    for (name, color, description) in LIFECYCLE_LABELS {
        if runner.create_label(repo, name, color, description, false) {
            tracing::info!(repo = %repo, label = %name, "issue lifecycle label created");
        } else {
            tracing::debug!(
                repo = %repo,
                label = %name,
                "issue lifecycle label not created (already exists, or `gh` unavailable) — non-fatal"
            );
        }
    }
}

/// Every launch-time label ensure, in one call: the session's `ws/<name>`
/// label plus the two [`LIFECYCLE_LABELS`].
///
/// Why: the daemon's spawn paths need a single fire-and-forget entry point,
/// and the two ensures must be independent — a `gh` failure on either one must
/// leave the other attempted and must never propagate to the launch.
/// What: runs [`ensure_workstream_label_with`], discards its outcome (already
/// logged), then resolves the repo again for
/// [`ensure_lifecycle_labels_with`]. Nothing here returns or panics on a
/// failed `gh` call.
/// Test: `launch_labels_ensure_all_three`,
/// `lifecycle_labels_run_even_when_workstream_label_fails`,
/// `launch_labels_survive_total_gh_failure`.
fn ensure_launch_labels_with<R: GhLabelRunner>(
    runner: &R,
    repo_url: Option<&str>,
    workspace_dir: &Path,
    session_name: &str,
) {
    let _ = ensure_workstream_label_with(runner, repo_url, workspace_dir, session_name);
    if let Ok(gh_path) = resolve_github_repo(repo_url, workspace_dir) {
        ensure_lifecycle_labels_with(runner, &gh_path.rel_path());
    }
}

/// Resolve the `<owner>/<repo>` a session's labels belong to.
///
/// Why: both launch-time ensures need the same target, derived the same way —
/// one implementation, so the github.com-only rule cannot drift between them.
/// What: prefers a non-blank `repo_url`, falling back to `workspace_dir`'s own
/// `remote.origin.url`. `Err` carries the [`LabelOutcome`] skip the caller
/// should report.
/// Test: `ensure_skips_when_no_origin`, `ensure_skips_when_non_github`.
fn resolve_github_repo(
    repo_url: Option<&str>,
    workspace_dir: &Path,
) -> Result<GithubPath, LabelOutcome> {
    let origin = repo_url
        .map(str::to_string)
        .filter(|s| !s.trim().is_empty())
        .or_else(|| origin_url_from_workspace(workspace_dir))
        .ok_or(LabelOutcome::SkippedNoOrigin)?;
    owner_repo_from_origin(&origin).ok_or(LabelOutcome::SkippedNonGithub)
}

/// Fire-and-forget [`ensure_launch_labels_with`] on the blocking thread pool —
/// the session's `ws/<name>` label plus the two [`LIFECYCLE_LABELS`].
///
/// Why: the ensures shell out to `gh` (bounded by
/// [`GH_LABEL_TIMEOUT`], but still up to a few seconds on a slow/offline
/// host); the daemon's `spawn_managed_*` branches call this at the identical
/// point (right before launching the runtime) across all three spawn shapes
/// (cloned, in-project, local-path-redirected). Detaching via
/// `tokio::task::spawn` + `spawn_blocking` — rather than `.await`ing inline —
/// guarantees it adds ZERO latency to the launch critical path, matching
/// `daemon::managed_routes::lifecycle`'s existing convention for blocking
/// `gh` calls made from async handlers (see that module's `resolve_gh_env`
/// doc comment).
/// What: clones the three owned inputs, spawns a detached task that runs
/// [`ensure_launch_labels_with`] on the blocking thread pool, and logs (at
/// debug) if the spawned task itself could not be joined — the ensure calls
/// already log their own outcomes internally. Must be called from inside a
/// tokio runtime (every call site is an async `spawn_managed_*` handler).
/// Test: [`ensure_launch_labels_with`]'s own unit tests cover the pure logic
/// this wraps; this wrapper is a thin, side-effect-only dispatch with
/// nothing pure to assert beyond "doesn't block", which the
/// `handler_spawn_*`/`resume_managed_*` integration tests already exercise
/// by not timing out.
pub fn spawn_workstream_label_ensure(
    repo_url: Option<String>,
    workspace_dir: std::path::PathBuf,
    session_name: String,
) {
    tokio::task::spawn(async move {
        if let Err(e) = tokio::task::spawn_blocking(move || {
            ensure_launch_labels_with(
                &RealGhRunner,
                repo_url.as_deref(),
                &workspace_dir,
                &session_name,
            )
        })
        .await
        {
            tracing::debug!("workstream label ensure task failed to join: {e}");
        }
    });
}

/// GitHub's hard cap on a label name's length (the full `ws/<name>` string).
const GITHUB_LABEL_MAX_LEN: usize = 50;

/// The `ws/<name>` label name for a session, truncated (with a stable
/// disambiguating suffix) to stay within GitHub's label-name length cap.
///
/// Why: GitHub caps a label name at [`GITHUB_LABEL_MAX_LEN`] characters.
/// Auto-derived session names are always well within that, but an OPERATOR
/// rename (`SessionManager::rename`, up to 64 chars) can produce a name
/// whose `ws/<name>` form overflows the cap — `gh label create`/`--add-label`
/// would then fail with a 400, exactly the failure this module exists to
/// prevent. Simple truncation risks two DIFFERENT long names colliding on
/// the same truncated label; an 8-hex FNV-1a suffix — hashed from the FULL
/// untruncated name, not the truncated prefix — keeps them apart.
/// What: `ws/<name>` verbatim when it already fits. Otherwise:
/// `ws/<truncated-name>-<8-hex-hash>`, where `<truncated-name>` is `name`'s
/// leading bytes (trimmed to the nearest earlier `char` boundary so a
/// multi-byte character is never split) shortened just far enough that the
/// full `ws/<truncated>-<hash>` string is at most [`GITHUB_LABEL_MAX_LEN`]
/// characters, and `<hash>` is the lowercase 8-hex encoding of the top 32
/// bits of `name`'s FNV-1a-64 hash.
/// Test: `label_name_short_is_verbatim`,
/// `label_name_long_is_truncated_with_hash_suffix`,
/// `label_name_stays_within_github_cap`,
/// `label_name_distinct_long_names_get_distinct_labels`.
fn label_name_for(session_name: &str) -> String {
    let full = format!("ws/{session_name}");
    if full.len() <= GITHUB_LABEL_MAX_LEN {
        return full;
    }
    // 8 lowercase hex chars from the top 32 bits of the FULL name's hash —
    // stable per name, and keeps two names sharing a truncated prefix apart.
    let suffix = format!("{:08x}", (fnv1a_hash(session_name) >> 32) as u32);
    // Budget: "ws/" (3) + truncated name + "-" (1) + suffix (8) <= cap.
    let prefix_budget = GITHUB_LABEL_MAX_LEN - "ws/".len() - 1 - suffix.len();
    let truncated = truncate_at_char_boundary(session_name, prefix_budget);
    format!("ws/{truncated}-{suffix}")
}

/// Truncate `s` to at most `max_bytes` bytes, backing off to the nearest
/// earlier `char` boundary so a multi-byte UTF-8 character is never split.
fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> &str {
    if s.len() <= max_bytes {
        return s;
    }
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

/// Read `remote.origin.url` from `dir` via `git config`, best-effort.
///
/// Why: the fallback path when no `repo_url` was threaded through the spawn
/// (mirrors [`trusty_common::github_path::derive_github_path`]'s own
/// `git config --get remote.origin.url` call, but this module needs the RAW
/// URL string first so it can apply its own github.com-host check before
/// parsing owner/repo).
/// What: `None` on any git failure (not a repo, no origin, git absent) or an
/// empty result.
fn origin_url_from_workspace(dir: &Path) -> Option<String> {
    let output = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["config", "--get", "remote.origin.url"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    (!url.is_empty()).then_some(url)
}

/// Parse a git remote URL into an `owner/repo` pair, but ONLY when its host is
/// `github.com` — unlike [`trusty_common::github_path::parse_github_path`],
/// which accepts any host.
///
/// Why: the PM-brief convention and `gh label create` both assume a
/// `github.com` repo; a GitLab/Bitbucket/self-hosted origin must skip
/// cleanly rather than have `gh` (silently pointed at the wrong host by its
/// own defaults) fail confusingly.
/// What: extracts the host from either SSH scp-syntax
/// (`git@github.com:owner/repo.git`) or a URL
/// (`https://github.com/owner/repo`, `ssh://git@github.com/owner/repo`),
/// case-insensitively compares it to `github.com`, and on a match delegates
/// owner/repo extraction to [`trusty_common::github_path::parse_github_path`].
/// Returns `None` for any other host or an unparseable input.
/// Test: `owner_repo_from_ssh_origin`, `owner_repo_from_https_origin`,
/// `owner_repo_from_https_origin_without_dot_git`,
/// `owner_repo_rejects_non_github_host`, `owner_repo_rejects_empty`.
fn owner_repo_from_origin(origin: &str) -> Option<GithubPath> {
    let trimmed = origin.trim();
    if trimmed.is_empty() {
        return None;
    }
    let after_scheme = trimmed
        .find("://")
        .map(|i| &trimmed[i + 3..])
        .unwrap_or(trimmed);
    let host_source = after_scheme
        .find('@')
        .map(|i| &after_scheme[i + 1..])
        .unwrap_or(after_scheme);
    let colon = host_source.find(':');
    let slash = host_source.find('/');
    let host = match (colon, slash) {
        (Some(c), s) if s.is_none_or(|s| c < s) => &host_source[..c],
        (_, Some(s)) => &host_source[..s],
        _ => host_source,
    };
    if !host.eq_ignore_ascii_case("github.com") {
        return None;
    }
    trusty_common::github_path::parse_github_path(trimmed)
}

/// Derive a stable, name-specific 6-hex label color.
///
/// Scheme: FNV-1a (64-bit, chosen over `std`'s `DefaultHasher` because its
/// algorithm is explicitly not guaranteed stable across Rust versions — this
/// color must stay identical for a given name across every future rebuild)
/// hashes `session_name`; the hash mod 360 becomes an HSL hue, with fixed
/// saturation (55%) and lightness (45%) chosen to stay readable as GitHub
/// label text on both light and dark repo themes. The hue spread means
/// distinct workstream names get visually distinct, deterministic colors.
/// Test: `label_color_is_stable_and_valid_hex`,
/// `label_color_differs_across_names`.
fn label_color_for(session_name: &str) -> String {
    let hue = (fnv1a_hash(session_name) % 360) as f64;
    hsl_to_hex(hue, 0.55, 0.45)
}

/// FNV-1a 64-bit hash — deterministic across Rust versions/platforms, unlike
/// `std::collections::hash_map::DefaultHasher`.
fn fnv1a_hash(input: &str) -> u64 {
    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
    let mut hash = FNV_OFFSET_BASIS;
    for byte in input.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    hash
}

/// Convert an HSL color (`h` in `[0, 360)`, `s`/`l` in `[0, 1]`) to an
/// uppercase 6-hex RGB string with no leading `#` (matching `gh label
/// create --color`'s expected form).
fn hsl_to_hex(h: f64, s: f64, l: f64) -> String {
    let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
    let h_prime = h / 60.0;
    let x = c * (1.0 - (h_prime % 2.0 - 1.0).abs());
    let m = l - c / 2.0;
    let (r1, g1, b1) = match h_prime as u32 {
        0 => (c, x, 0.0),
        1 => (x, c, 0.0),
        2 => (0.0, c, x),
        3 => (0.0, x, c),
        4 => (x, 0.0, c),
        _ => (c, 0.0, x),
    };
    let to_byte = |v: f64| ((v + m) * 255.0).round().clamp(0.0, 255.0) as u8;
    format!("{:02X}{:02X}{:02X}", to_byte(r1), to_byte(g1), to_byte(b1))
}

/// A seam for the one `gh` invocation this module makes, so tests can script
/// the outcome instead of shelling out to a live `gh`.
///
/// Why: mirrors the `CommandRunner` seam `tm ticket`/`watch` use
/// (`bin/tm/commands/ticket/runner.rs`) — that trait lives in the `tm` binary
/// crate and is not reachable from this library module, so this is a small,
/// purpose-built equivalent scoped to the one call this module needs.
/// What: `create_label` returns whether the `gh` call succeeded; callers never
/// see the raw stdout/stderr since label-create has nothing worth surfacing on
/// success and every failure is already a non-fatal skip.
/// Test: driven by `FakeGhRunner` in this module's tests.
trait GhLabelRunner {
    /// Run `gh label create <name> --repo <repo> --color <color> --description
    /// <description>` (with `--force` when `force`), returning whether it
    /// succeeded.
    fn create_label(
        &self,
        repo: &str,
        name: &str,
        color: &str,
        description: &str,
        force: bool,
    ) -> bool;
}

/// Production [`GhLabelRunner`] — spawns real `gh`, bounded by
/// [`GH_LABEL_TIMEOUT`].
struct RealGhRunner;

impl GhLabelRunner for RealGhRunner {
    fn create_label(
        &self,
        repo: &str,
        name: &str,
        color: &str,
        description: &str,
        force: bool,
    ) -> bool {
        let repo = repo.to_string();
        let name = name.to_string();
        let color = color.to_string();
        let description = description.to_string();
        run_bounded(GH_LABEL_TIMEOUT, move || {
            // #5475: single `gh` entry point.
            let mut argv: Vec<&str> = vec![
                "label",
                "create",
                &name,
                "--repo",
                &repo,
                "--color",
                &color,
                "--description",
                &description,
            ];
            if force {
                argv.push("--force");
            }
            trusty_common::gh::GhCommand::new(argv)
                .output_blocking()
                .ok()
                .map(|out| out.success)
        })
        .unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;

    // ── owner/repo host-scoped derivation ───────────────────────────────

    #[test]
    fn owner_repo_from_ssh_origin() {
        let gp = owner_repo_from_origin("git@github.com:bobmatnyc/trusty-tools.git")
            .expect("github ssh origin parses");
        assert_eq!(gp.owner, "bobmatnyc");
        assert_eq!(gp.repo, "trusty-tools");
    }

    #[test]
    fn owner_repo_from_https_origin() {
        let gp = owner_repo_from_origin("https://github.com/bobmatnyc/trusty-tools.git")
            .expect("github https origin parses");
        assert_eq!(gp.owner, "bobmatnyc");
        assert_eq!(gp.repo, "trusty-tools");
    }

    #[test]
    fn owner_repo_from_https_origin_without_dot_git() {
        let gp = owner_repo_from_origin("https://github.com/bobmatnyc/trusty-tools")
            .expect("github https origin without .git parses");
        assert_eq!(gp.owner, "bobmatnyc");
        assert_eq!(gp.repo, "trusty-tools");
    }

    #[test]
    fn owner_repo_rejects_non_github_host() {
        assert!(owner_repo_from_origin("git@gitlab.com:acme/widget.git").is_none());
        assert!(owner_repo_from_origin("https://bitbucket.org/acme/widget.git").is_none());
    }

    #[test]
    fn owner_repo_rejects_empty() {
        assert!(owner_repo_from_origin("").is_none());
        assert!(owner_repo_from_origin("   ").is_none());
    }

    // ── color derivation ────────────────────────────────────────────────

    #[test]
    fn label_color_is_stable_and_valid_hex() {
        let a = label_color_for("tm-tcode-01");
        let b = label_color_for("tm-tcode-01");
        assert_eq!(a, b, "same name must always derive the same color");
        assert_eq!(a.len(), 6);
        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
        assert_eq!(a, a.to_ascii_uppercase(), "color must be uppercase hex");
    }

    #[test]
    fn label_color_differs_across_names() {
        let a = label_color_for("tm-tcode-01");
        let b = label_color_for("tm-dogfood-relaunch-01");
        assert_ne!(a, b, "distinct names should (overwhelmingly likely) differ");
    }

    // ── label name length cap ───────────────────────────────────────────

    #[test]
    fn label_name_short_is_verbatim() {
        assert_eq!(label_name_for("tm-tcode-01"), "ws/tm-tcode-01");
    }

    #[test]
    fn label_name_stays_within_github_cap() {
        // `SessionManager::rename` allows operator-chosen names up to 64
        // chars — well past the 47-char budget `ws/<name>` has under the
        // 50-char GitHub label cap.
        let long_name = "a".repeat(64);
        let label = label_name_for(&long_name);
        assert!(
            label.len() <= GITHUB_LABEL_MAX_LEN,
            "label {label:?} ({} chars) exceeds the {GITHUB_LABEL_MAX_LEN}-char GitHub cap",
            label.len()
        );
    }

    #[test]
    fn label_name_long_is_truncated_with_hash_suffix() {
        let long_name = "a".repeat(64);
        let label = label_name_for(&long_name);
        assert!(label.starts_with("ws/aaaa"), "got {label:?}");
        // "ws/" + 38-char truncated prefix + "-" + 8-hex suffix == 50.
        assert_eq!(label.len(), GITHUB_LABEL_MAX_LEN);
        let suffix = label.rsplit('-').next().expect("has a suffix segment");
        assert_eq!(suffix.len(), 8, "suffix {suffix:?} must be 8 hex chars");
        assert!(suffix.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn label_name_distinct_long_names_get_distinct_labels() {
        // Share an identical 60-char prefix (well past the ~38-char
        // truncation budget) and differ only in their last 4 chars — the
        // hash suffix (derived from the FULL name) must still tell them
        // apart even though their truncated prefixes are identical.
        let base = "x".repeat(60);
        let name_a = format!("{base}1111");
        let name_b = format!("{base}2222");
        let label_a = label_name_for(&name_a);
        let label_b = label_name_for(&name_b);
        assert_ne!(
            label_a, label_b,
            "two long names differing only past the truncation point must not collide"
        );
        assert!(label_a.len() <= GITHUB_LABEL_MAX_LEN);
        assert!(label_b.len() <= GITHUB_LABEL_MAX_LEN);
    }

    // ── ensure_workstream_label skip-cleanly paths ──────────────────────

    /// One recorded `create_label` call: `(repo, name, color, description,
    /// force)`.
    type RecordedCall = (String, String, String, String, bool);

    struct FakeGhRunner {
        succeed: bool,
        /// Label names this runner fails for regardless of `succeed`.
        fail_for: Vec<&'static str>,
        calls: RefCell<Vec<RecordedCall>>,
    }

    impl FakeGhRunner {
        fn new(succeed: bool) -> Self {
            Self {
                succeed,
                fail_for: Vec::new(),
                calls: RefCell::new(Vec::new()),
            }
        }

        /// A runner that succeeds except for the named labels.
        fn failing_for(names: &[&'static str]) -> Self {
            Self {
                succeed: true,
                fail_for: names.to_vec(),
                calls: RefCell::new(Vec::new()),
            }
        }

        /// The label names passed to `create_label`, in call order.
        fn label_names(&self) -> Vec<String> {
            self.calls
                .borrow()
                .iter()
                .map(|(_, name, ..)| name.clone())
                .collect()
        }
    }

    impl GhLabelRunner for FakeGhRunner {
        fn create_label(
            &self,
            repo: &str,
            name: &str,
            color: &str,
            description: &str,
            force: bool,
        ) -> bool {
            self.calls.borrow_mut().push((
                repo.to_string(),
                name.to_string(),
                color.to_string(),
                description.to_string(),
                force,
            ));
            self.succeed && !self.fail_for.contains(&name)
        }
    }

    #[test]
    fn ensure_skips_when_name_blank() {
        let runner = FakeGhRunner::new(true);
        let outcome = ensure_workstream_label_with(
            &runner,
            Some("https://github.com/bobmatnyc/trusty-tools.git"),
            Path::new("/nonexistent"),
            "   ",
        );
        assert_eq!(outcome, LabelOutcome::SkippedBlankName);
        assert!(runner.calls.borrow().is_empty(), "gh must not be invoked");
    }

    #[test]
    fn ensure_skips_when_no_origin() {
        let runner = FakeGhRunner::new(true);
        // A path that is (almost certainly) not inside any git repo and no
        // repo_url supplied.
        let outcome = ensure_workstream_label_with(&runner, None, Path::new("/"), "tm-tcode-01");
        assert_eq!(outcome, LabelOutcome::SkippedNoOrigin);
        assert!(runner.calls.borrow().is_empty(), "gh must not be invoked");
    }

    #[test]
    fn ensure_skips_when_non_github() {
        let runner = FakeGhRunner::new(true);
        let outcome = ensure_workstream_label_with(
            &runner,
            Some("git@gitlab.com:acme/widget.git"),
            Path::new("/nonexistent"),
            "tm-tcode-01",
        );
        assert_eq!(outcome, LabelOutcome::SkippedNonGithub);
        assert!(runner.calls.borrow().is_empty(), "gh must not be invoked");
    }

    #[test]
    fn ensure_creates_label_via_runner() {
        let runner = FakeGhRunner::new(true);
        let outcome = ensure_workstream_label_with(
            &runner,
            Some("https://github.com/bobmatnyc/trusty-tools.git"),
            Path::new("/nonexistent"),
            "tm-tcode-01",
        );
        assert_eq!(outcome, LabelOutcome::Ensured);
        let calls = runner.calls.borrow();
        assert_eq!(calls.len(), 1);
        let (repo, name, color, description, force) = &calls[0];
        assert_eq!(repo, "bobmatnyc/trusty-tools");
        assert_eq!(name, "ws/tm-tcode-01");
        assert_eq!(color.len(), 6);
        assert_eq!(description, "trusty-mpm workstream tm-tcode-01");
        assert!(
            force,
            "the ws/ label is trusty-mpm's own — force is correct"
        );
    }

    #[test]
    fn ensure_reports_runner_failure() {
        let runner = FakeGhRunner::new(false);
        let outcome = ensure_workstream_label_with(
            &runner,
            Some("https://github.com/bobmatnyc/trusty-tools.git"),
            Path::new("/nonexistent"),
            "tm-tcode-01",
        );
        assert_eq!(outcome, LabelOutcome::GhFailed);
    }

    // ── issue-lifecycle labels ──────────────────────────────────────────

    const REPO_URL: &str = "https://github.com/bobmatnyc/trusty-tools.git";

    #[test]
    fn lifecycle_label_table_is_valid() {
        for (name, color, description) in LIFECYCLE_LABELS {
            assert!(!name.is_empty() && name.len() <= GITHUB_LABEL_MAX_LEN);
            assert_eq!(color.len(), 6, "{name}'s color must be 6 hex chars");
            assert!(color.chars().all(|c| c.is_ascii_hexdigit()));
            assert!(!description.is_empty(), "{name} needs a description");
        }
        let names: Vec<&str> = LIFECYCLE_LABELS.iter().map(|(n, ..)| *n).collect();
        assert_eq!(names, ["in-progress", "blocked"]);
    }

    #[test]
    fn lifecycle_labels_are_created_without_force() {
        let runner = FakeGhRunner::new(true);
        ensure_lifecycle_labels_with(&runner, "bobmatnyc/trusty-tools");
        let calls = runner.calls.borrow();
        assert_eq!(calls.len(), LIFECYCLE_LABELS.len());
        for (repo, name, color, description, force) in calls.iter() {
            assert_eq!(repo, "bobmatnyc/trusty-tools");
            assert!(
                !force,
                "{name} is an ordinary repo label — --force would rewrite a \
                 project's own color/description on every launch"
            );
            let (_, want_color, want_description) = LIFECYCLE_LABELS
                .iter()
                .find(|(n, ..)| n == name)
                .expect("only table labels are created");
            assert_eq!(color, want_color);
            assert_eq!(description, want_description);
        }
    }

    #[test]
    fn lifecycle_labels_attempt_every_label_when_gh_fails() {
        // Every `gh` call fails (missing binary, unauthenticated, offline).
        // Both labels must still be attempted, and nothing may panic.
        let runner = FakeGhRunner::new(false);
        ensure_lifecycle_labels_with(&runner, "bobmatnyc/trusty-tools");
        assert_eq!(runner.label_names(), ["in-progress", "blocked"]);
    }

    // ── launch-time composition (failure paths) ─────────────────────────

    #[test]
    fn launch_labels_ensure_all_three() {
        let runner = FakeGhRunner::new(true);
        ensure_launch_labels_with(
            &runner,
            Some(REPO_URL),
            Path::new("/nonexistent"),
            "tm-tcode-01",
        );
        assert_eq!(
            runner.label_names(),
            ["ws/tm-tcode-01", "in-progress", "blocked"]
        );
    }

    #[test]
    fn lifecycle_labels_run_even_when_workstream_label_fails() {
        // The ws/ label's `gh` call fails; the lifecycle labels are an
        // independent concern and must still be attempted.
        let runner = FakeGhRunner::failing_for(&["ws/tm-tcode-01"]);
        ensure_launch_labels_with(
            &runner,
            Some(REPO_URL),
            Path::new("/nonexistent"),
            "tm-tcode-01",
        );
        assert_eq!(
            runner.label_names(),
            ["ws/tm-tcode-01", "in-progress", "blocked"]
        );
    }

    #[test]
    fn workstream_label_runs_even_when_lifecycle_labels_fail() {
        let runner = FakeGhRunner::failing_for(&["in-progress", "blocked"]);
        ensure_launch_labels_with(
            &runner,
            Some(REPO_URL),
            Path::new("/nonexistent"),
            "tm-tcode-01",
        );
        assert_eq!(
            runner.label_names(),
            ["ws/tm-tcode-01", "in-progress", "blocked"],
            "a lifecycle-label failure must not suppress the ws/ label or the \
             label after it"
        );
    }

    #[test]
    fn launch_labels_survive_total_gh_failure() {
        // The launch-path contract: every `gh` call failing is a logged,
        // non-fatal skip. The call returns normally — no panic, no error to
        // propagate into `spawn_workstream_label_ensure`'s blocking task.
        let runner = FakeGhRunner::new(false);
        ensure_launch_labels_with(
            &runner,
            Some(REPO_URL),
            Path::new("/nonexistent"),
            "tm-tcode-01",
        );
        assert_eq!(
            runner.label_names(),
            ["ws/tm-tcode-01", "in-progress", "blocked"]
        );
    }

    #[test]
    fn launch_labels_skip_cleanly_on_non_github_remote() {
        let runner = FakeGhRunner::new(true);
        ensure_launch_labels_with(
            &runner,
            Some("git@gitlab.com:acme/widget.git"),
            Path::new("/nonexistent"),
            "tm-tcode-01",
        );
        assert!(
            runner.calls.borrow().is_empty(),
            "no gh call belongs on a non-github remote"
        );
    }

    #[test]
    fn launch_labels_ensure_lifecycle_labels_when_session_name_is_blank() {
        // A blank session name skips the ws/ label only — the lifecycle
        // labels do not depend on it.
        let runner = FakeGhRunner::new(true);
        ensure_launch_labels_with(&runner, Some(REPO_URL), Path::new("/nonexistent"), "  ");
        assert_eq!(runner.label_names(), ["in-progress", "blocked"]);
    }
}