supercode-harness 0.5.13

The optional native Volter Harness 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
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
//! 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 checkout it was built from, then the globally installed
//!   `@volter/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, resolve_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/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 path = teams_home
        .join(SERVICE_DIR)
        .join(format!("{label}.{}", connector_unit_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!(windows) {
        // A scheduled task sets no environment and keeps no output, so node reads both from a file beside the
        // task (`--env-file`); the user's own PATH is the task's. `conhost --headless` runs it without a window,
        // and hides node's exit code too, so restart-on-failure never sees one fail: a trigger every minute
        // starts the connector again instead, and while it runs the task's IgnoreNew makes that tick a no-op.
        // The trigger's fixed past start keeps the rendered unit the same on every install.
        let env_path = connector_env_path(teams_home, &label);
        let log_path = teams_home
            .join(SERVICE_DIR)
            .join(format!("{label}.log"))
            .display()
            .to_string();
        let env_text = [
            ("SUPERCODE_HOME", home.as_str()),
            ("SUPERCODE_BIN", supercode.as_str()),
            ("SUPERCODE_TEAMS_LOG", log_path.as_str()),
        ]
        .iter()
        .map(|(key, value)| env_file_value(value).map(|value| format!("{key}={value}\n")))
        .collect::<Result<String, _>>()?;
        // Task Scheduler expands `%NAME%` in a task's arguments, and there is no escape for it.
        for value in [&node, &entry, &workspace, &env_path.display().to_string()] {
            if value.contains('%') {
                return Err(TeamsError::Service {
                    action: "render",
                    detail: format!("a Windows task cannot carry a path containing `%`: {value}"),
                });
            }
        }
        let arguments = [
            node.as_str(),
            &format!("--env-file={}", env_path.display()),
            entry.as_str(),
            "teams",
            "connect",
            "--foreground",
            "--context",
            context,
            "--cwd",
            workspace.as_str(),
        ]
        .iter()
        .map(|argument| windows_arg(argument))
        .collect::<Vec<_>>()
        .join(" ");
        let user = windows_user();
        let conhost =
            Path::new(&std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()))
                .join(r"System32\conhost.exe")
                .display()
                .to_string();
        let text = format!(
            r#"<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo><Description>supercode Teams connector ({})</Description></RegistrationInfo>
  <Triggers><LogonTrigger><Enabled>true</Enabled><UserId>{}</UserId></LogonTrigger><TimeTrigger><StartBoundary>2000-01-01T00:00:00</StartBoundary><Enabled>true</Enabled><Repetition><Interval>PT1M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition></TimeTrigger></Triggers>
  <Principals><Principal id="Author"><UserId>{}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
  <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>999</Count></RestartOnFailure><StartWhenAvailable>true</StartWhenAvailable></Settings>
  <Actions Context="Author"><Exec><Command>{}</Command><Arguments>--headless {}</Arguments><WorkingDirectory>{}</WorkingDirectory></Exec></Actions>
</Task>
"#,
            xml_text(context),
            xml_text(&user),
            xml_text(&user),
            xml_text(&conhost),
            xml_text(&arguments),
            xml_text(&workspace),
        );
        return Ok(ServiceUnit {
            kind: "schtasks",
            path: path.clone(),
            text,
            install_command: format!("schtasks /Create /TN {label} /XML {} /F", path.display()),
            files: vec![(env_path, env_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 search_path = plist_text(&service_path());
        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><key>PATH</key><string>{search_path}</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()),
            files: Vec::new(),
        })
    } else {
        let environment_home = systemd_arg(&format!("SUPERCODE_HOME={home}"));
        let environment_bin = systemd_arg(&format!("SUPERCODE_BIN={supercode}"));
        let environment_path = systemd_arg(&format!("PATH={}", service_path()));
        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}\nEnvironment={environment_path}\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()
            ),
            files: Vec::new(),
        })
    }
}

/// The connector unit's file suffix on this platform.
fn connector_unit_suffix() -> &'static str {
    if cfg!(windows) {
        "xml"
    } else if cfg!(target_os = "macos") {
        "plist"
    } else {
        "service"
    }
}

/// The environment file a Windows connector task hands to node (`--env-file`).
fn connector_env_path(teams_home: &Path, label: &str) -> PathBuf {
    teams_home.join(SERVICE_DIR).join(format!("{label}.env"))
}

/// Text inside a Task Scheduler XML element or attribute.
fn xml_text(value: &str) -> String {
    plist_text(value).replace('"', "&quot;")
}

/// One argument of a Windows command line, quoted so the C runtime (node.exe's) splits it back out whole:
/// backslashes are literal except before a quote, where they and the quote are escaped.
fn windows_arg(value: &str) -> String {
    if !value.is_empty() && !value.contains([' ', '\t', '"']) {
        return value.to_string();
    }
    let mut quoted = String::from("\"");
    let mut backslashes = 0;
    for character in value.chars() {
        match character {
            '\\' => backslashes += 1,
            '"' => {
                quoted.push_str(&"\\".repeat(backslashes * 2 + 1));
                quoted.push('"');
                backslashes = 0;
            }
            other => {
                quoted.push_str(&"\\".repeat(backslashes));
                quoted.push(other);
                backslashes = 0;
            }
        }
    }
    quoted.push_str(&"\\".repeat(backslashes * 2));
    quoted.push('"');
    quoted
}

/// A value in a node `--env-file`, quoted with a quote character the value does not contain. Single and backtick
/// quotes are literal; double quotes would turn a path's `\n` into a newline, so they are the last choice.
fn env_file_value(value: &str) -> Result<String, TeamsError> {
    ['\'', '`']
        .into_iter()
        .find(|quote| !value.contains(*quote))
        .map(|quote| format!("{quote}{value}{quote}"))
        .or_else(|| (!value.contains(['"', '\\'])).then(|| format!("\"{value}\"")))
        .ok_or_else(|| TeamsError::Service {
            action: "render",
            detail: format!("cannot write `{value}` into the connector's environment file"),
        })
}

/// The Windows account a task runs as: `DOMAIN\user`, the one installing it.
fn windows_user() -> String {
    let user = std::env::var("USERNAME").unwrap_or_default();
    match std::env::var("USERDOMAIN") {
        Ok(domain) if !domain.is_empty() => format!("{domain}\\{user}"),
        _ => user,
    }
}

/// 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 search path a service runs with: the installing shell's own, so a
/// service finds the same `tmux`, `node` and harness CLIs its installer did
/// (a launchd or systemd default path has none of them).
fn service_path() -> String {
    std::env::var("PATH")
        .ok()
        .filter(|path| !path.trim().is_empty())
        .unwrap_or_else(|| "/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin".into())
}

/// The teams home: `SUPERCODE_TEAMS_HOME`, else `<SUPERCODE_HOME>/teams`.
///
/// The same precedence `sdk/volter-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 workspace this crate was built from,
/// and the globally installed npm package — an installed binary has no
/// checkout, so `npm install -g @volter/supercode-teams` is how a
/// Machine gets its node. The current directory is never a candidate: the
/// code a binary runs does not change with where it is run.
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));
    }
    // 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());
    }
    // Installed from npm, this binary sits inside the global node_modules that
    // also holds the Teams package, so that directory is found from the
    // binary's own path first (`npm root -g` masks path segments it takes for
    // secrets, a UUID among them).
    if let Ok(exe) = std::env::current_exe() {
        for modules in exe
            .ancestors()
            .filter(|dir| dir.file_name().is_some_and(|name| name == "node_modules"))
        {
            let candidate = modules.join(TEAMS_PACKAGE).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(resolve_program("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,
            files: Vec::new(),
        }
    } 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,
            files: Vec::new(),
        }
    }
}

/// 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,
    })?;
    for (path, text) in &unit.files {
        std::fs::write(path, text).map_err(|source| TeamsError::File {
            path: path.clone(),
            source,
        })?;
    }
    Ok(())
}

/// 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 in this home's own service folder is
/// this home's connector with new parameters (a new build, PATH or folder), so
/// it is replaced and restarted; a label the manager holds with no unit here
/// belongs to another home and 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,
        })?;
        // A Windows unit's environment lives in its companion file, so that is compared too.
        let same = old == unit.text
            && unit
                .files
                .iter()
                .all(|(path, text)| std::fs::read_to_string(path).is_ok_and(|old| &old == text));
        if same && existing.installed {
            return Ok(existing);
        }
        if !same && existing.installed {
            named_platform_uninstall(label)?;
        }
    } 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))
}

/// Give every installed harness supercode's messaging tools: register
/// `<supercode> message mcp` as a user-scope MCP server named `supercode`
/// through each harness's own `mcp add`. A harness whose CLI is absent, or
/// that already has the entry, is left as it is. One line per harness says
/// what happened.
pub fn register_message_tools(supercode: &Path) -> Vec<String> {
    let program = supercode.display().to_string();
    let mut report = Vec::new();
    for (harness, get, add) in [
        (
            "claude",
            vec!["mcp", "get", "supercode"],
            vec![
                "mcp",
                "add",
                "--scope",
                "user",
                "supercode",
                "--",
                &program,
                "message",
                "mcp",
            ],
        ),
        (
            "codex",
            vec!["mcp", "get", "supercode"],
            vec!["mcp", "add", "supercode", "--", &program, "message", "mcp"],
        ),
    ] {
        let run = |args: &[&str]| {
            std::process::Command::new(resolve_program(harness))
                .args(args)
                .stdin(std::process::Stdio::null())
                .output()
        };
        match run(&get) {
            Err(_) => report.push(format!("{harness}: not installed")),
            Ok(found) if found.status.success() => {
                report.push(format!("{harness}: already has supercode's tools"))
            }
            Ok(_) => match run(&add) {
                Ok(added) if added.status.success() => report.push(format!(
                    "{harness}: supercode's tools added (new sessions load them)"
                )),
                Ok(added) => report.push(format!(
                    "{harness}: could not add supercode's tools: {}",
                    String::from_utf8_lossy(&added.stderr).trim()
                )),
                Err(error) => report.push(format!(
                    "{harness}: could not add supercode's tools: {error}"
                )),
            },
        }
    }
    report
}

/// 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 unit = teams_home
        .join(SERVICE_DIR)
        .join(format!("{label}.{}", connector_unit_suffix()));
    for path in [unit, connector_env_path(teams_home, label)] {
        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 {
    match run_tool("schtasks", &["/Query", "/TN", label, "/FO", "CSV", "/NH"]) {
        // `"TaskName","Next Run Time","Status"`: the last field is the task's state, in the system's language.
        Ok((true, text)) => ServiceState {
            kind: "schtasks",
            label: label.into(),
            installed: true,
            pid: None,
            detail: text
                .lines()
                .next()
                .and_then(|line| line.rsplit(',').next())
                .map(|state| state.trim_matches('"').to_string())
                .filter(|state| !state.is_empty())
                .unwrap_or_else(|| "registered".into()),
        },
        Ok((false, _)) => ServiceState {
            kind: "schtasks",
            label: label.into(),
            installed: false,
            pid: None,
            detail: "no scheduled task".into(),
        },
        Err(error) => ServiceState {
            kind: "schtasks",
            label: label.into(),
            installed: false,
            pid: None,
            detail: format!("schtasks unavailable: {error}"),
        },
    }
}

#[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> {
    // Task Scheduler reads task XML only as UTF-16; the unit itself stays UTF-8 so an install can compare it.
    let task = unit.path.with_extension("utf16.xml");
    let bytes: Vec<u8> = [0xFF, 0xFE]
        .into_iter()
        .chain(unit.text.encode_utf16().flat_map(u16::to_le_bytes))
        .collect();
    std::fs::write(&task, bytes).map_err(|source| TeamsError::File {
        path: task.clone(),
        source,
    })?;
    let task_path = task.display().to_string();
    let result = [
        vec!["/Create", "/TN", label, "/XML", task_path.as_str(), "/F"],
        vec!["/Run", "/TN", label],
    ]
    .iter()
    .try_for_each(|args| {
        let (ok, text) = run_tool("schtasks", args).map_err(|error| TeamsError::Service {
            action: "install",
            detail: format!("schtasks: {error}"),
        })?;
        if ok {
            Ok(())
        } else {
            Err(TeamsError::Service {
                action: "install",
                detail: format!("schtasks {}: {text}", args[0]),
            })
        }
    });
    let _ = std::fs::remove_file(&task);
    result
}

#[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}"),
        });
    }
    // bootout returns before launchd has let the label go, and a bootstrap
    // in that window fails with an I/O error; wait for it to be released.
    for _ in 0..50 {
        if !named_service_status(label).installed {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    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> {
    // The task goes first, so its minute trigger cannot start the connector again while it is being stopped.
    let (ok, text) = run_tool("schtasks", &["/Delete", "/TN", label, "/F"]).map_err(|error| {
        TeamsError::Service {
            action: "uninstall",
            detail: format!("schtasks: {error}"),
        }
    })?;
    if !ok && named_service_status(label).installed {
        return Err(TeamsError::Service {
            action: "uninstall",
            detail: format!("schtasks /Delete: {text}"),
        });
    }
    // Deleting a task leaves what it started running, so the connector is stopped by the one thing on its command
    // line that is its own: the environment file, on a node or its conhost. The path rides in the environment, not
    // the command line, so this query does not match itself.
    let env_path = connector_env_path(&teams_home(), label);
    let stopped = std::process::Command::new("powershell.exe")
        .args([
            "-NoProfile",
            "-NonInteractive",
            "-Command",
            "Get-CimInstance Win32_Process -Filter \"Name='node.exe' OR Name='conhost.exe'\" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($env:SUPERCODE_SERVICE_ENV_FILE) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }",
        ])
        .env("SUPERCODE_SERVICE_ENV_FILE", env_path.display().to_string())
        .stdin(std::process::Stdio::null())
        .output();
    match stopped {
        Ok(output) if output.status.success() => Ok(()),
        Ok(output) => Err(TeamsError::Service {
            action: "uninstall",
            detail: format!(
                "the task is gone, but its connector may still run: {}",
                String::from_utf8_lossy(&output.stderr).trim()
            ),
        }),
        Err(error) => Err(TeamsError::Service {
            action: "uninstall",
            detail: format!(
                "the task is gone, but its connector may still run: powershell: {error}"
            ),
        }),
    }
}

#[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 render = |entry: &str, cwd: &str| {
            connector_service_unit(
                Path::new("/tmp/teams & logs"),
                Path::new("/tmp/home $x"),
                Path::new(entry),
                "/usr/bin/node",
                Path::new("/tmp/super\"code"),
                "work",
                Path::new(cwd),
                "srv",
                "team",
            )
        };
        if cfg!(windows) {
            // Task Scheduler would expand `%i`; such a path is refused rather than run as something else.
            assert!(render("/tmp/entry %i", "/tmp/a & b $").is_err());
            let unit = render("/tmp/entry", "/tmp/a & b $").unwrap();
            assert!(unit.text.contains("--cwd &quot;/tmp/a &amp; b $&quot;"));
            let (env_path, env_text) = &unit.files[0];
            assert!(env_path.ends_with(format!(
                "{}.env",
                connector_service_name("srv", "team", "work")
            )));
            assert!(env_text.contains("SUPERCODE_BIN='/tmp/super\"code'\n"));
            assert!(!unit.text.contains("super\"code"));
        } else if cfg!(target_os = "macos") {
            let unit = render("/tmp/entry %i", "/tmp/a & b % $").unwrap();
            assert!(unit.text.contains("&amp;"));
        } else {
            let unit = render("/tmp/entry %i", "/tmp/a & b % $").unwrap();
            assert!(unit.text.contains("%%"));
            assert!(unit.text.contains("$$"));
            assert!(unit.text.contains("\\\""));
        }
    }

    #[test]
    fn windows_arguments_split_back_out_whole() {
        assert_eq!(windows_arg("plain"), "plain");
        assert_eq!(windows_arg(""), "\"\"");
        assert_eq!(
            windows_arg(r"C:\Program Files\nodejs\node.exe"),
            r#""C:\Program Files\nodejs\node.exe""#
        );
        assert_eq!(windows_arg(r#"say "hi""#), r#""say \"hi\"""#);
        // Backslashes before a quote, and before the closing quote, are doubled; elsewhere they are literal.
        assert_eq!(windows_arg(r#"a\"b"#), r#""a\\\"b""#);
        assert_eq!(windows_arg(r"C:\my dir\"), r#""C:\my dir\\""#);
    }

    #[test]
    fn env_file_values_are_quoted_literally() {
        assert_eq!(env_file_value(r"C:\new\tab").unwrap(), r"'C:\new\tab'");
        assert_eq!(env_file_value("O'Brien").unwrap(), "`O'Brien`");
        assert_eq!(env_file_value("it's `x`").unwrap(), "\"it's `x`\"");
        assert!(env_file_value(r"it's `x` \n").is_err());
    }
}