supercode-harness 0.4.77

The optional native Supercode agent and tool harness
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
//! Where supercode-teams lives on this box, and the service unit that keeps
//! its machine daemon up (`docs/plans/teams-server.md` §11).
//!
//! supercode does not implement teams; the `sdk/teams` package does. This
//! module holds the two facts the Rust CLI needs about it:
//!
//! * **where its Node entry is** — [`teams_entry`], resolved exactly the way
//!   [`crate::orchestrator::daemon_entry`] resolves the orchestrator's:
//!   `SUPERCODE_TEAMS_ENTRY` first, then the checkout the running binary sits
//!   in, then the current directory, then the globally installed
//!   `@volter-ai-dev/supercode-teams` package (`npm root -g`).
//! * **what a service unit for its node would say** — [`service_unit`] renders
//!   the launchd plist / systemd unit that runs `node <entry> machine start`,
//!   written under `<home>/service/`;
//!   [`install_service`] and [`uninstall_service`] drive `launchctl` /
//!   `systemctl --user` over it.
//!
//! Everything else about teams — its host key, log, contexts, enrollments — is the Node
//! package's own state, written by its own CLI. There is no second writer of
//! that home in this binary.

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

use crate::orchestrator::{absolute_program, ServiceState, ServiceUnit};

/// The teams CLI entry inside the `sdk/teams` package.
pub const TEAMS_ENTRY: &str = "bin/teams.mjs";

/// The npm name the `sdk/teams` package is published under.
pub const TEAMS_PACKAGE: &str = "@volter-ai-dev/supercode-teams";

/// Directory the rendered service unit is written into, relative to the home.
pub const SERVICE_DIR: &str = "service";

/// launchd label / systemd unit name for this machine's teams daemon.
pub const SERVICE_NAME: &str = "dev.volter.supercode-teams-machine";

/// Stable, context-scoped label for one workspace connector service.
pub fn connector_service_name(server_id: &str, team_id: &str, context: &str) -> String {
    // FNV-1a is sufficient here: this is a stable filesystem/service label,
    // not an authorization decision or secret digest.
    let mut hash = 0xcbf29ce484222325_u64;
    for byte in [server_id, team_id, context].join("\0").bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    format!("dev.volter.supercode-teams-connector-{hash:016x}")
}

fn plist_text(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

fn service_text(value: &str) -> Result<&str, TeamsError> {
    if value.chars().any(char::is_control) {
        return Err(TeamsError::Service {
            action: "render",
            detail: "service parameters cannot contain control characters".into(),
        });
    }
    Ok(value)
}

fn systemd_arg(value: &str) -> String {
    format!(
        "\"{}\"",
        value
            .replace('\\', "\\\\")
            .replace('"', "\\\"")
            .replace('%', "%%")
            .replace('$', "$$")
    )
}

/// Render the persistent foreground connector command for one saved context.
pub fn connector_service_unit(
    teams_home: &Path,
    supercode_home: &Path,
    entry: &Path,
    node: &str,
    supercode: &Path,
    context: &str,
    cwd: &Path,
    server_id: &str,
    team_id: &str,
) -> Result<ServiceUnit, TeamsError> {
    let teams_home_text = teams_home.display().to_string();
    let supercode_home_text = supercode_home.display().to_string();
    let entry_text = entry.display().to_string();
    let supercode_text = supercode.display().to_string();
    let workspace_text = cwd.display().to_string();
    for value in [
        teams_home_text.as_str(),
        supercode_home_text.as_str(),
        entry_text.as_str(),
        node,
        supercode_text.as_str(),
        context,
        workspace_text.as_str(),
        server_id,
        team_id,
    ] {
        service_text(value)?;
    }
    let label = connector_service_name(server_id, team_id, context);
    let suffix = if cfg!(target_os = "macos") {
        "plist"
    } else {
        "service"
    };
    let path = teams_home
        .join(SERVICE_DIR)
        .join(format!("{label}.{suffix}"));
    let node = absolute_program(node);
    let entry = entry_text;
    let workspace = workspace_text;
    let home = supercode_home_text;
    let supercode = supercode_text;
    if cfg!(target_os = "macos") {
        let node = plist_text(&node);
        let entry = plist_text(&entry);
        let workspace = plist_text(&workspace);
        let home = plist_text(&home);
        let supercode = plist_text(&supercode);
        let context = plist_text(context);
        let text = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>{label}</string>
  <key>ProgramArguments</key><array><string>{node}</string><string>{entry}</string><string>teams</string><string>connect</string><string>--context</string><string>{context}</string><string>--cwd</string><string>{workspace}</string></array>
  <key>EnvironmentVariables</key><dict><key>SUPERCODE_HOME</key><string>{home}</string><key>SUPERCODE_BIN</key><string>{supercode}</string></dict>
  <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>{}/service/{label}.out.log</string>
  <key>StandardErrorPath</key><string>{}/service/{label}.err.log</string>
</dict></plist>
"#,
            plist_text(&teams_home_text),
            plist_text(&teams_home_text)
        );
        Ok(ServiceUnit {
            kind: "launchd",
            path: path.clone(),
            text,
            install_command: format!("launchctl bootstrap gui/$(id -u) {}", path.display()),
        })
    } else {
        let environment_home = systemd_arg(&format!("SUPERCODE_HOME={home}"));
        let environment_bin = systemd_arg(&format!("SUPERCODE_BIN={supercode}"));
        let node = systemd_arg(&node);
        let entry = systemd_arg(&entry);
        let workspace = systemd_arg(&workspace);
        let context_description = context.replace('%', "%%").replace('$', "$$");
        let context = systemd_arg(context);
        let text = format!("[Unit]\nDescription=supercode Teams connector ({context_description})\nAfter=network.target\n\n[Service]\nEnvironment={environment_home}\nEnvironment={environment_bin}\nExecStart={node} {entry} teams connect --context {context} --cwd {workspace}\nRestart=on-failure\nKillSignal=SIGTERM\n\n[Install]\nWantedBy=default.target\n");
        Ok(ServiceUnit {
            kind: "systemd",
            path: path.clone(),
            text,
            install_command: format!(
                "systemctl --user link {} && systemctl --user enable --now {label}",
                path.display()
            ),
        })
    }
}

/// Why a teams verb could not do its work.
#[derive(Debug, thiserror::Error)]
pub enum TeamsError {
    /// The Node teams entry could not be located.
    #[error("no teams entry found (looked for `sdk/teams/{TEAMS_ENTRY}` under: {searched}); install it with `npm install -g {TEAMS_PACKAGE}`")]
    NoEntry {
        /// The candidate paths that were searched, joined.
        searched: String,
    },
    /// A service manager refused, or there is none on this platform.
    #[error("teams service: {action} failed: {detail}")]
    Service {
        /// What was attempted (`install`, `uninstall`).
        action: &'static str,
        /// What the service manager (or this module) said about it.
        detail: String,
    },
    /// A file under the teams home could not be written or removed.
    #[error("teams file `{}`: {source}", path.display())]
    File {
        /// The path involved.
        path: PathBuf,
        /// The underlying I/O failure.
        source: std::io::Error,
    },
}

/// The teams home: `SUPERCODE_TEAMS_HOME`, else `<SUPERCODE_HOME>/teams`.
///
/// The same precedence `sdk/teams/home.mjs` uses, so a unit installed from
/// here serves the home the Node CLI reads.
pub fn teams_home() -> PathBuf {
    if let Ok(home) = std::env::var("SUPERCODE_TEAMS_HOME") {
        if !home.is_empty() {
            return PathBuf::from(home);
        }
    }
    crate::agent::global_instructions_dir().join("teams")
}

/// Locate the Node teams entry (`sdk/teams/bin/teams.mjs`).
///
/// Candidates, in order: `SUPERCODE_TEAMS_ENTRY` (an explicit override, which
/// is also how a test points at a fake), the repo checkout the running binary
/// sits in, the current directory, the workspace this crate was built from,
/// and the globally installed npm package — an installed binary has no
/// checkout, so `npm install -g @volter-ai-dev/supercode-teams` is how a
/// Machine gets its node.
pub fn teams_entry() -> Result<PathBuf, TeamsError> {
    let mut searched = Vec::new();
    if let Some(explicit) = std::env::var_os("SUPERCODE_TEAMS_ENTRY") {
        let path = PathBuf::from(explicit);
        if path.is_file() {
            return Ok(path);
        }
        searched.push(path.display().to_string());
    }
    let mut roots: Vec<PathBuf> = Vec::new();
    if let Ok(exe) = std::env::current_exe() {
        // target/<profile>/supercode → the workspace root is two levels up.
        roots.extend(exe.ancestors().skip(1).take(4).map(Path::to_path_buf));
    }
    if let Ok(cwd) = std::env::current_dir() {
        roots.push(cwd);
    }
    // A locally built binary's target directory can live anywhere (a shared
    // cargo build dir, another volume), so the checkout it was built from is
    // the last candidate. On an installed binary this path simply does not
    // exist and is skipped like any other miss.
    if let Some(workspace) = Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2) {
        roots.push(workspace.to_path_buf());
    }
    for root in roots {
        let candidate = root.join("sdk/teams").join(TEAMS_ENTRY);
        if candidate.is_file() {
            return Ok(candidate);
        }
        searched.push(candidate.display().to_string());
    }
    if let Some(global) = global_npm_root() {
        let candidate = global.join(TEAMS_PACKAGE).join(TEAMS_ENTRY);
        if candidate.is_file() {
            return Ok(candidate);
        }
        searched.push(candidate.display().to_string());
    }
    Err(TeamsError::NoEntry {
        searched: searched.join(", "),
    })
}

/// Where npm installs global packages (`npm root -g`), when npm is present.
fn global_npm_root() -> Option<PathBuf> {
    let output = std::process::Command::new("npm")
        .args(["root", "-g"])
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let root = text.trim();
    if root.is_empty() {
        return None;
    }
    Some(PathBuf::from(root))
}

/// Render the per-platform service unit for this machine's teams daemon.
///
/// The node takes no `--root`: it serves the home its own environment
/// resolves (`SUPERCODE_TEAMS_HOME`, else `<SUPERCODE_HOME>/teams`), so the
/// unit names the listen address and nothing else. A port of `0` means the
/// node picks one and publishes it in `<home>/node.json`.
pub fn service_unit(home: &Path, entry: &Path, node: &str) -> ServiceUnit {
    let home_display = home.display().to_string();
    let entry_display = entry.display().to_string();
    if cfg!(target_os = "macos") {
        let path = home.join(SERVICE_DIR).join(format!("{SERVICE_NAME}.plist"));
        let text = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>{SERVICE_NAME}</string>
  <key>ProgramArguments</key>
  <array>
    <string>{node}</string>
    <string>{entry_display}</string>
    <string>machine</string>
    <string>start</string>
  </array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>SUPERCODE_TEAMS_HOME</key><string>{home_display}</string>
  </dict>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>{home_display}/service/teams-machine.out.log</string>
  <key>StandardErrorPath</key><string>{home_display}/service/teams-machine.err.log</string>
</dict>
</plist>
"#
        );
        let install = format!("launchctl bootstrap gui/$(id -u) {}", path.display());
        ServiceUnit {
            kind: "launchd",
            path,
            text,
            install_command: install,
        }
    } else {
        let path = home
            .join(SERVICE_DIR)
            .join(format!("{SERVICE_NAME}.service"));
        let text = format!(
            "[Unit]\n\
             Description=supercode teams machine daemon ({home_display})\n\
             After=network.target\n\
             \n\
             [Service]\n\
             Environment=SUPERCODE_TEAMS_HOME={home_display}\n\
             ExecStart={node} {entry_display} machine start\n\
             Restart=on-failure\n\
             KillSignal=SIGTERM\n\
             \n\
             [Install]\n\
             WantedBy=default.target\n"
        );
        let install = format!(
            "systemctl --user link {} && systemctl --user enable --now {SERVICE_NAME}",
            path.display()
        );
        ServiceUnit {
            kind: "systemd",
            path,
            text,
            install_command: install,
        }
    }
}

/// Write a rendered unit under `<home>/service/`.
pub fn write_unit(unit: &ServiceUnit) -> Result<(), TeamsError> {
    if let Some(parent) = unit.path.parent() {
        std::fs::create_dir_all(parent).map_err(|source| TeamsError::File {
            path: unit.path.clone(),
            source,
        })?;
    }
    std::fs::write(&unit.path, &unit.text).map_err(|source| TeamsError::File {
        path: unit.path.clone(),
        source,
    })
}

/// Run a service-manager command and return (success, stdout+stderr).
fn run_tool(program: &str, args: &[&str]) -> Result<(bool, String), std::io::Error> {
    let output = std::process::Command::new(program).args(args).output()?;
    let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
    text.push_str(&String::from_utf8_lossy(&output.stderr));
    Ok((output.status.success(), text.trim().to_string()))
}

#[cfg(target_os = "macos")]
fn gui_domain() -> String {
    // SAFETY: `getuid` reads this process's own real user id and cannot fail.
    format!("gui/{}", unsafe { libc::getuid() })
}

/// What the platform's service manager says about the teams daemon unit.
///
/// Never starts or installs anything.
pub fn service_status() -> ServiceState {
    platform_status()
}

#[cfg(target_os = "macos")]
fn platform_status() -> ServiceState {
    let label = SERVICE_NAME.to_string();
    let target = format!("{}/{SERVICE_NAME}", gui_domain());
    match run_tool("launchctl", &["print", &target]) {
        Ok((true, text)) => ServiceState {
            kind: "launchd",
            label,
            installed: true,
            pid: field_of(&text, "pid = ").and_then(|value| value.parse().ok()),
            detail: field_of(&text, "state = ").unwrap_or_else(|| "loaded".into()),
        },
        Ok((false, _)) => ServiceState {
            kind: "launchd",
            label,
            installed: false,
            pid: None,
            detail: format!("not bootstrapped in {}", gui_domain()),
        },
        Err(error) => ServiceState {
            kind: "launchd",
            label,
            installed: false,
            pid: None,
            detail: format!("launchctl unavailable: {error}"),
        },
    }
}

#[cfg(all(unix, not(target_os = "macos")))]
fn platform_status() -> ServiceState {
    let label = SERVICE_NAME.to_string();
    match run_tool("systemctl", &["--user", "is-active", SERVICE_NAME]) {
        Ok((active, text)) => {
            let known = run_tool("systemctl", &["--user", "is-enabled", SERVICE_NAME])
                .map(|(ok, _)| ok)
                .unwrap_or(false);
            ServiceState {
                kind: "systemd",
                label,
                installed: active || known,
                pid: None,
                detail: if text.is_empty() {
                    "unknown".into()
                } else {
                    text
                },
            }
        }
        Err(error) => ServiceState {
            kind: "systemd",
            label,
            installed: false,
            pid: None,
            detail: format!("systemctl unavailable: {error}"),
        },
    }
}

#[cfg(not(unix))]
fn platform_status() -> ServiceState {
    ServiceState {
        kind: "none",
        label: SERVICE_NAME.to_string(),
        installed: false,
        pid: None,
        detail: "no service manager on this platform".into(),
    }
}

/// `key = value` out of a service manager's block output.
#[cfg(target_os = "macos")]
fn field_of(text: &str, key: &str) -> Option<String> {
    text.lines()
        .find_map(|line| line.trim().strip_prefix(key))
        .map(|value| value.trim().to_string())
}

/// The file name the unit takes on this platform.
fn unit_file_name() -> String {
    if cfg!(target_os = "macos") {
        format!("{SERVICE_NAME}.plist")
    } else {
        format!("{SERVICE_NAME}.service")
    }
}

/// Render the unit, hand it to the platform's service manager, and start it.
///
/// Refuses a label the manager already holds rather than replacing it: two
/// homes share one label, so an install that silently took it over would point
/// a running node at a different folder.
pub fn install_service(
    home: &Path,
    entry: &Path,
    node: &str,
) -> Result<(ServiceUnit, ServiceState), TeamsError> {
    let existing = service_status();
    if existing.installed {
        return Err(TeamsError::Service {
            action: "install",
            detail: format!(
                "`{}` is already installed ({}); `supercode teams machine uninstall` first",
                existing.label, existing.detail
            ),
        });
    }
    let unit = service_unit(home, entry, &absolute_program(node));
    write_unit(&unit)?;
    platform_install(&unit)?;
    Ok((unit, service_status()))
}

/// Install a rendered context connector. An identical installed unit is an
/// idempotent success; a different unit under the same label is refused.
pub fn install_connector_service(
    unit: &ServiceUnit,
    label: &str,
) -> Result<ServiceState, TeamsError> {
    let existing = named_service_status(label);
    if unit.path.exists() {
        let old = std::fs::read_to_string(&unit.path).map_err(|source| TeamsError::File {
            path: unit.path.clone(),
            source,
        })?;
        if old != unit.text {
            return Err(TeamsError::Service { action: "install", detail: format!("`{label}` exists with different context or service parameters; disconnect it first") });
        }
        if existing.installed {
            return Ok(existing);
        }
    } else if existing.installed {
        return Err(TeamsError::Service {
            action: "install",
            detail: format!(
                "service manager already owns `{label}` without its expected unit file"
            ),
        });
    }
    write_unit(unit)?;
    named_platform_install(unit, label)?;
    Ok(named_service_status(label))
}

/// Stop and remove exactly one context connector service.
pub fn uninstall_connector_service(
    teams_home: &Path,
    label: &str,
) -> Result<ServiceState, TeamsError> {
    named_platform_uninstall(label)?;
    let suffix = if cfg!(target_os = "macos") {
        "plist"
    } else {
        "service"
    };
    let path = teams_home
        .join(SERVICE_DIR)
        .join(format!("{label}.{suffix}"));
    match std::fs::remove_file(&path) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(source) => return Err(TeamsError::File { path, source }),
    }
    Ok(named_service_status(label))
}

/// Read-only service-manager status for one context connector.
pub fn connector_service_status(label: &str) -> ServiceState {
    named_service_status(label)
}

#[cfg(target_os = "macos")]
fn named_service_status(label: &str) -> ServiceState {
    let target = format!("{}/{label}", gui_domain());
    match run_tool("launchctl", &["print", &target]) {
        Ok((true, text)) => ServiceState {
            kind: "launchd",
            label: label.into(),
            installed: true,
            pid: field_of(&text, "pid = ").and_then(|value| value.parse().ok()),
            detail: field_of(&text, "state = ").unwrap_or_else(|| "loaded".into()),
        },
        Ok((false, _)) => ServiceState {
            kind: "launchd",
            label: label.into(),
            installed: false,
            pid: None,
            detail: format!("not bootstrapped in {}", gui_domain()),
        },
        Err(error) => ServiceState {
            kind: "launchd",
            label: label.into(),
            installed: false,
            pid: None,
            detail: format!("launchctl unavailable: {error}"),
        },
    }
}

#[cfg(all(unix, not(target_os = "macos")))]
fn named_service_status(label: &str) -> ServiceState {
    match run_tool("systemctl", &["--user", "is-active", label]) {
        Ok((active, text)) => {
            let known = run_tool("systemctl", &["--user", "is-enabled", label])
                .map(|(ok, _)| ok)
                .unwrap_or(false);
            ServiceState {
                kind: "systemd",
                label: label.into(),
                installed: active || known,
                pid: None,
                detail: if text.is_empty() {
                    "unknown".into()
                } else {
                    text
                },
            }
        }
        Err(error) => ServiceState {
            kind: "systemd",
            label: label.into(),
            installed: false,
            pid: None,
            detail: format!("systemctl unavailable: {error}"),
        },
    }
}

#[cfg(not(unix))]
fn named_service_status(label: &str) -> ServiceState {
    ServiceState {
        kind: "none",
        label: label.into(),
        installed: false,
        pid: None,
        detail: "no service manager on this platform".into(),
    }
}

#[cfg(target_os = "macos")]
fn named_platform_install(unit: &ServiceUnit, _label: &str) -> Result<(), TeamsError> {
    platform_install(unit)
}
#[cfg(all(unix, not(target_os = "macos")))]
fn named_platform_install(unit: &ServiceUnit, label: &str) -> Result<(), TeamsError> {
    let path = unit.path.display().to_string();
    for args in [
        vec!["--user", "link", path.as_str()],
        vec!["--user", "enable", "--now", label],
    ] {
        let (ok, text) = run_tool("systemctl", &args).map_err(|error| TeamsError::Service {
            action: "install",
            detail: format!("systemctl: {error}"),
        })?;
        if !ok {
            return Err(TeamsError::Service {
                action: "install",
                detail: format!("systemctl {}: {text}", args.join(" ")),
            });
        }
    }
    Ok(())
}
#[cfg(not(unix))]
fn named_platform_install(_unit: &ServiceUnit, _label: &str) -> Result<(), TeamsError> {
    Err(TeamsError::Service {
        action: "install",
        detail: "no service manager on this platform".into(),
    })
}

#[cfg(target_os = "macos")]
fn named_platform_uninstall(label: &str) -> Result<(), TeamsError> {
    let target = format!("{}/{label}", gui_domain());
    let (ok, text) =
        run_tool("launchctl", &["bootout", &target]).map_err(|error| TeamsError::Service {
            action: "uninstall",
            detail: format!("launchctl: {error}"),
        })?;
    if !ok && !text.contains("No such process") && !text.contains("not find") {
        return Err(TeamsError::Service {
            action: "uninstall",
            detail: format!("launchctl bootout {target}: {text}"),
        });
    }
    Ok(())
}
#[cfg(all(unix, not(target_os = "macos")))]
fn named_platform_uninstall(label: &str) -> Result<(), TeamsError> {
    let _ = run_tool("systemctl", &["--user", "disable", "--now", label]);
    Ok(())
}
#[cfg(not(unix))]
fn named_platform_uninstall(_label: &str) -> Result<(), TeamsError> {
    Ok(())
}

#[cfg(target_os = "macos")]
fn platform_install(unit: &ServiceUnit) -> Result<(), TeamsError> {
    let path = unit.path.display().to_string();
    let (ok, text) =
        run_tool("launchctl", &["bootstrap", &gui_domain(), &path]).map_err(|error| {
            TeamsError::Service {
                action: "install",
                detail: format!("launchctl: {error}"),
            }
        })?;
    if !ok {
        return Err(TeamsError::Service {
            action: "install",
            detail: format!("launchctl bootstrap {}: {text}", gui_domain()),
        });
    }
    Ok(())
}

/// Untested on this box (the receipt is macOS); these are the commands
/// `service_unit` prints as its `install_command`.
#[cfg(all(unix, not(target_os = "macos")))]
fn platform_install(unit: &ServiceUnit) -> Result<(), TeamsError> {
    let path = unit.path.display().to_string();
    for args in [
        vec!["--user", "link", path.as_str()],
        vec!["--user", "enable", "--now", SERVICE_NAME],
    ] {
        let (ok, text) = run_tool("systemctl", &args).map_err(|error| TeamsError::Service {
            action: "install",
            detail: format!("systemctl: {error}"),
        })?;
        if !ok {
            return Err(TeamsError::Service {
                action: "install",
                detail: format!("systemctl {}: {text}", args.join(" ")),
            });
        }
    }
    Ok(())
}

#[cfg(not(unix))]
fn platform_install(_unit: &ServiceUnit) -> Result<(), TeamsError> {
    Err(TeamsError::Service {
        action: "install",
        detail: "no service manager on this platform".into(),
    })
}

/// Stop and unregister the unit, and remove the rendered file.
///
/// Idempotent: a unit the manager does not hold is not an error, because the
/// state the operator asked for is the state they get.
pub fn uninstall_service(home: &Path) -> Result<ServiceState, TeamsError> {
    platform_uninstall()?;
    let unit_path = home.join(SERVICE_DIR).join(unit_file_name());
    match std::fs::remove_file(&unit_path) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(source) => {
            return Err(TeamsError::File {
                path: unit_path,
                source,
            })
        }
    }
    // `launchctl bootout` returns before the job is torn down, so the state
    // this reports is the settled one, not the manager mid-teardown.
    let mut state = service_status();
    for _ in 0..40 {
        if !state.installed {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
        state = service_status();
    }
    Ok(state)
}

#[cfg(target_os = "macos")]
fn platform_uninstall() -> Result<(), TeamsError> {
    let target = format!("{}/{SERVICE_NAME}", gui_domain());
    let (ok, text) =
        run_tool("launchctl", &["bootout", &target]).map_err(|error| TeamsError::Service {
            action: "uninstall",
            detail: format!("launchctl: {error}"),
        })?;
    // `bootout` on a label nobody holds says so and exits non-zero.
    if !ok && !text.contains("No such process") && !text.contains("not find") {
        return Err(TeamsError::Service {
            action: "uninstall",
            detail: format!("launchctl bootout {target}: {text}"),
        });
    }
    Ok(())
}

#[cfg(all(unix, not(target_os = "macos")))]
fn platform_uninstall() -> Result<(), TeamsError> {
    let _ = run_tool("systemctl", &["--user", "disable", "--now", SERVICE_NAME]);
    Ok(())
}

#[cfg(not(unix))]
fn platform_uninstall() -> Result<(), TeamsError> {
    Ok(())
}

#[cfg(test)]
mod connector_service_tests {
    use super::*;

    #[test]
    fn connector_unit_is_context_scoped_and_contains_no_credential() {
        let unit = connector_service_unit(
            Path::new("/tmp/teams home"),
            Path::new("/tmp/supercode home"),
            Path::new("/tmp/sdk/teams/bin/teams.mjs"),
            "/usr/bin/node",
            Path::new("/tmp/bin/supercode"),
            "work",
            Path::new("/tmp/project with spaces"),
            "srv_1",
            "team_1",
        )
        .unwrap();
        assert!(unit.text.contains("teams"));
        assert!(unit.text.contains("connect"));
        assert!(unit.text.contains("work"));
        assert!(!unit.text.contains("credential"));
        assert!(unit
            .path
            .file_name()
            .unwrap()
            .to_string_lossy()
            .contains(&connector_service_name("srv_1", "team_1", "work")));
    }

    #[test]
    fn connector_labels_separate_context_and_team() {
        assert_ne!(
            connector_service_name("srv", "team-a", "work"),
            connector_service_name("srv", "team-b", "work")
        );
        assert_ne!(
            connector_service_name("srv", "team-a", "work"),
            connector_service_name("srv", "team-a", "personal")
        );
    }

    #[test]
    fn connector_unit_rejects_newlines_and_escapes_service_syntax() {
        let unsafe_unit = connector_service_unit(
            Path::new("/tmp/teams"),
            Path::new("/tmp/home"),
            Path::new("/tmp/entry"),
            "/usr/bin/node",
            Path::new("/tmp/supercode"),
            "bad\ncontext",
            Path::new("/tmp/work"),
            "srv",
            "team",
        );
        assert!(unsafe_unit.is_err());
        let unit = connector_service_unit(
            Path::new("/tmp/teams & logs"),
            Path::new("/tmp/home $x"),
            Path::new("/tmp/entry %i"),
            "/usr/bin/node",
            Path::new("/tmp/super\"code"),
            "work",
            Path::new("/tmp/a & b % $"),
            "srv",
            "team",
        )
        .unwrap();
        if cfg!(target_os = "macos") {
            assert!(unit.text.contains("&amp;"));
        } else {
            assert!(unit.text.contains("%%"));
            assert!(unit.text.contains("$$"));
            assert!(unit.text.contains("\\\""));
        }
    }
}