supercode-harness 0.4.17

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
//! The orchestrator's home, its daemon lease, and the service unit the
//! operator verbs print (ORC-7).
//!
//! supercode does not perform orchestration; the `supercode-orchestrator`
//! package does (`docs/ORCHESTRATOR-IR.md` §0.1). This module holds the three
//! facts supercode's own surfaces need about it:
//!
//! * **where its state lives** — `SUPERCODE_ORCHESTRATOR_HOME`, default
//!   `~/.supercode/orchestrator`, resolved once in
//!   [`crate::HarnessHomes::orchestrator`]; the root folder IS the `default`
//!   profile and `profiles/<name>/` are the named ones
//!   (`docs/ORCHESTRATOR-IR.md` §6).
//! * **whether the daemon is up** — the lease file `<home>/orchestrator.lock`,
//!   plus a liveness signal on the pid it names. A lock whose process is gone
//!   is stale, never "up".
//! * **what a service unit for it would say, and whether it is installed** —
//!   [`service_unit`] renders the launchd plist / systemd unit `setup` writes
//!   under `<home>/service/`; [`install_service`], [`uninstall_service`] and
//!   [`service_status`] drive `launchctl` / `systemctl --user` over it.
//!
//! The lease FILE is written by the daemon itself (`bin/orchestrator.mjs`), not
//! by this crate: one writer means a service-managed daemon reports the same
//! lease a foreground one does, and a lock left by a process that is gone is
//! the daemon's own signal to replay (§4.7).
//!
//! Reading the folder is every existing ORCH reader's job: `jobs`, `runs`,
//! `routes`, `channels`, `triggers`, `profiles` and session discovery point
//! their Hermes-shaped code paths at these same profile folders.

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

use serde::{Deserialize, Serialize};

/// Lease file the daemon writes while it serves a home, relative to the home.
pub const LOCK_FILE: &str = "orchestrator.lock";

/// Directory `setup` writes the rendered service unit into.
pub const SERVICE_DIR: &str = "service";

/// The daemon entry inside the `sdk/orchestrator` package.
pub const DAEMON_ENTRY: &str = "bin/orchestrator.mjs";

/// launchd label / systemd unit name for the orchestrator daemon.
pub const SERVICE_NAME: &str = "ai.volter.supercode.orchestrator";

/// The lease `<home>/orchestrator.lock` holds: which process is serving this
/// home, and since when.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Lease {
    /// Daemon process id.
    pub pid: u32,
    /// RFC3339 instant the daemon recorded at startup.
    pub started_at: String,
    /// The home the daemon was started against.
    pub root: PathBuf,
}

/// Why an operator verb could not do its work.
#[derive(Debug, thiserror::Error)]
pub enum OrchestratorError {
    /// No lease file, or one that no longer names a live process.
    #[error("the orchestrator is not running for `{0}` (no live lease at `{1}`)", root.display(), lock.display())]
    NotRunning {
        /// The home that was asked about.
        root: PathBuf,
        /// Where its lease would be.
        lock: PathBuf,
    },
    /// A lease exists and its process is alive.
    #[error("the orchestrator is already running for `{}` (pid {pid})", root.display())]
    AlreadyRunning {
        /// The home that was asked about.
        root: PathBuf,
        /// The live daemon's pid.
        pid: u32,
    },
    /// The Node daemon entry could not be located.
    #[error("no orchestrator daemon entry found (looked for `{DAEMON_ENTRY}` under: {searched})")]
    NoDaemonEntry {
        /// The candidate roots that were searched, joined.
        searched: String,
    },
    /// The lease file could not be read or written.
    #[error("orchestrator lease `{}`: {source}", path.display())]
    Lease {
        /// The lease path.
        path: PathBuf,
        /// The underlying I/O failure.
        source: std::io::Error,
    },
    /// A service manager refused, or there is none on this platform.
    #[error("orchestrator 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,
    },
}

/// The lease path for one home.
pub fn lock_path(root: &Path) -> PathBuf {
    root.join(LOCK_FILE)
}

/// Read the lease, whether or not its process is still alive.
pub fn read_lease(root: &Path) -> Option<Lease> {
    let text = std::fs::read_to_string(lock_path(root)).ok()?;
    serde_json::from_str(&text).ok()
}

/// Write the lease for a running daemon.
pub fn write_lease(root: &Path, lease: &Lease) -> Result<(), OrchestratorError> {
    let path = lock_path(root);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|source| OrchestratorError::Lease {
            path: path.clone(),
            source,
        })?;
    }
    let text = serde_json::to_string_pretty(lease).unwrap_or_default();
    std::fs::write(&path, format!("{text}\n")).map_err(|source| OrchestratorError::Lease {
        path: path.clone(),
        source,
    })
}

/// Remove the lease file. A missing file is not an error — `stop` is
/// idempotent by design.
pub fn clear_lease(root: &Path) -> Result<(), OrchestratorError> {
    let path = lock_path(root);
    match std::fs::remove_file(&path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(source) => Err(OrchestratorError::Lease { path, source }),
    }
}

/// Whether `pid` is a live process this user can signal.
///
/// `kill(pid, 0)` is the liveness question POSIX answers without touching the
/// process. On a non-unix target there is no equivalent that does not start
/// something, so the lease alone is the answer.
pub fn pid_is_live(pid: u32) -> bool {
    #[cfg(unix)]
    {
        if pid == 0 {
            return false;
        }
        // SAFETY: signal 0 performs error checking only; it delivers nothing.
        unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
        true
    }
}

/// The lease of a daemon that is actually alive right now.
pub fn live_lease(root: &Path) -> Option<Lease> {
    read_lease(root).filter(|lease| pid_is_live(lease.pid))
}

/// Ask the daemon to stop: SIGTERM to the leased pid, then clear the lease.
///
/// The daemon's own SIGTERM handler is what closes its adapters; this never
/// escalates to SIGKILL and never signals anything but the pid the lease
/// names.
pub fn stop(root: &Path) -> Result<Lease, OrchestratorError> {
    let Some(lease) = live_lease(root) else {
        return Err(OrchestratorError::NotRunning {
            root: root.to_path_buf(),
            lock: lock_path(root),
        });
    };
    #[cfg(unix)]
    // SAFETY: the pid comes from this home's own lease and is known live.
    unsafe {
        libc::kill(lease.pid as libc::pid_t, libc::SIGTERM);
    }
    clear_lease(root)?;
    Ok(lease)
}

/// Locate the Node daemon entry (`sdk/orchestrator/bin/orchestrator.mjs`).
///
/// Candidates, in order: `SUPERCODE_ORCHESTRATOR_ENTRY` (an explicit
/// override, which is also how a test points at a fake), the repo checkout the
/// running binary sits in, and the current directory's `sdk/orchestrator`.
pub fn daemon_entry() -> Result<PathBuf, OrchestratorError> {
    let mut searched = Vec::new();
    if let Some(explicit) = std::env::var_os("SUPERCODE_ORCHESTRATOR_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/orchestrator").join(DAEMON_ENTRY);
        if candidate.is_file() {
            return Ok(candidate);
        }
        searched.push(candidate.display().to_string());
    }
    Err(OrchestratorError::NoDaemonEntry {
        searched: searched.join(", "),
    })
}

/// A rendered service unit: what `setup` prints and writes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ServiceUnit {
    /// `launchd` or `systemd`.
    pub kind: &'static str,
    /// Where `setup` writes the rendered text under `<home>/service/`.
    pub path: PathBuf,
    /// The unit text itself.
    pub text: String,
    /// The command an operator (or ORC-10) runs to install it.
    pub install_command: String,
}

/// Render the per-platform service unit for one home.
///
/// Nothing is installed here: ORC-10 owns installation. `setup` writes this
/// text under `<home>/service/` so the operator can read exactly what would
/// be installed before anything registers a daemon.
pub fn service_unit(root: &Path, entry: &Path, node: &str) -> ServiceUnit {
    let root_display = root.display().to_string();
    let entry_display = entry.display().to_string();
    if cfg!(target_os = "macos") {
        let path = root.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>--root</string>
    <string>{root_display}</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>{root_display}/service/orchestrator.out.log</string>
  <key>StandardErrorPath</key><string>{root_display}/service/orchestrator.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 = root
            .join(SERVICE_DIR)
            .join(format!("{SERVICE_NAME}.service"));
        let text = format!(
            "[Unit]\n\
             Description=supercode orchestrator ({root_display})\n\
             After=network.target\n\
             \n\
             [Service]\n\
             ExecStart={node} {entry_display} --root {root_display}\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,
        }
    }
}

/// What the platform's service manager says about the orchestrator unit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ServiceState {
    /// `launchd`, `systemd`, or `none` where neither is available.
    pub kind: &'static str,
    /// The label / unit name asked about.
    pub label: String,
    /// Whether the service manager holds the unit at all.
    pub installed: bool,
    /// The daemon's pid, where the service manager knows it.
    pub pid: Option<u32>,
    /// The manager's own words, or why the question could not be asked.
    pub detail: String,
}

/// launchd and systemd start a unit with a minimal `PATH`, so the unit names
/// the interpreter absolutely wherever one can be resolved.
pub fn absolute_program(program: &str) -> String {
    if program.contains('/') {
        return program.to_string();
    }
    if let Some(path) = std::env::var_os("PATH") {
        for dir in std::env::split_paths(&path) {
            let candidate = dir.join(program);
            if candidate.is_file() {
                return candidate.display().to_string();
            }
        }
    }
    program.to_string()
}

/// 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() })
}

/// Ask the platform's service manager about the orchestrator unit.
///
/// Never starts or installs anything: `status` calls this on every run.
pub fn service_status(root: &Path) -> ServiceState {
    platform_status(root)
}

#[cfg(target_os = "macos")]
fn platform_status(_root: &Path) -> 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(_root: &Path) -> 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(_root: &Path) -> 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())
}

/// 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 service at a different folder.
pub fn install_service(
    root: &Path,
    entry: &Path,
    node: &str,
) -> Result<(ServiceUnit, ServiceState), OrchestratorError> {
    let existing = service_status(root);
    if existing.installed {
        return Err(OrchestratorError::Service {
            action: "install",
            detail: format!(
                "`{}` is already installed ({}); `supercode orchestrator setup --uninstall` first",
                existing.label, existing.detail
            ),
        });
    }
    let unit = service_unit(root, entry, &absolute_program(node));
    write_unit(&unit)?;
    platform_install(&unit)?;
    Ok((unit, service_status(root)))
}

#[cfg(target_os = "macos")]
fn platform_install(unit: &ServiceUnit) -> Result<(), OrchestratorError> {
    let path = unit.path.display().to_string();
    let (ok, text) =
        run_tool("launchctl", &["bootstrap", &gui_domain(), &path]).map_err(|error| {
            OrchestratorError::Service {
                action: "install",
                detail: format!("launchctl: {error}"),
            }
        })?;
    if !ok {
        return Err(OrchestratorError::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` has always printed as its `install_command`.
#[cfg(all(unix, not(target_os = "macos")))]
fn platform_install(unit: &ServiceUnit) -> Result<(), OrchestratorError> {
    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| OrchestratorError::Service {
                action: "install",
                detail: format!("systemctl: {error}"),
            })?;
        if !ok {
            return Err(OrchestratorError::Service {
                action: "install",
                detail: format!("systemctl {}: {text}", args.join(" ")),
            });
        }
    }
    Ok(())
}

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

/// Stop and unregister the unit, and remove the rendered file `setup` wrote.
///
/// 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(root: &Path) -> Result<ServiceState, OrchestratorError> {
    platform_uninstall()?;
    let unit_path = root.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(OrchestratorError::Lease {
                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(root);
    for _ in 0..40 {
        if !state.installed {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
        state = service_status(root);
    }
    Ok(state)
}

#[cfg(target_os = "macos")]
fn platform_uninstall() -> Result<(), OrchestratorError> {
    let target = format!("{}/{SERVICE_NAME}", gui_domain());
    let (ok, text) = run_tool("launchctl", &["bootout", &target]).map_err(|error| {
        OrchestratorError::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(OrchestratorError::Service {
            action: "uninstall",
            detail: format!("launchctl bootout {target}: {text}"),
        });
    }
    Ok(())
}

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

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

/// The file name `service_unit` renders for this platform.
fn unit_file_name() -> String {
    if cfg!(target_os = "macos") {
        format!("{SERVICE_NAME}.plist")
    } else {
        format!("{SERVICE_NAME}.service")
    }
}

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

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

    /// A scratch home for one test, removed by the test that made it.
    fn scratch(label: &str) -> PathBuf {
        let root = std::env::temp_dir().join(format!(
            "supercode-orchestrator-{label}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&root).unwrap();
        root
    }

    #[test]
    fn a_lease_round_trips_and_a_missing_one_is_not_running() {
        let root = &scratch("lease");
        let root = root.as_path();
        assert!(read_lease(root).is_none());
        assert!(live_lease(root).is_none());
        let lease = Lease {
            pid: std::process::id(),
            started_at: "2026-09-04T00:00:00Z".into(),
            root: root.to_path_buf(),
        };
        write_lease(root, &lease).unwrap();
        assert_eq!(read_lease(root).as_ref(), Some(&lease));
        // This process is alive, so its own lease reads as live.
        assert!(live_lease(root).is_some());
        clear_lease(root).unwrap();
        assert!(read_lease(root).is_none());
        // `stop` on a home with no lease refuses by name.
        assert!(matches!(
            stop(root),
            Err(OrchestratorError::NotRunning { .. })
        ));
        std::fs::remove_dir_all(root).ok();
    }

    /// A lease whose process is gone is STALE: `status` must say down, not
    /// inherit the file's claim.
    #[test]
    fn a_stale_lease_is_not_live() {
        let root = &scratch("stale");
        let root = root.as_path();
        write_lease(
            root,
            &Lease {
                // A pid no process can hold (max_pid is far below this).
                pid: 0x7FFF_FFFF,
                started_at: "2026-09-04T00:00:00Z".into(),
                root: root.to_path_buf(),
            },
        )
        .unwrap();
        assert!(read_lease(root).is_some(), "the file is still there");
        assert!(live_lease(root).is_none(), "but nothing is serving it");
        std::fs::remove_dir_all(root).ok();
    }

    #[test]
    fn the_service_unit_names_the_home_the_entry_and_its_install_command() {
        let root = &scratch("unit");
        let root = root.as_path();
        let entry = PathBuf::from("/opt/supercode/sdk/orchestrator/bin/orchestrator.mjs");
        let unit = service_unit(root, &entry, "/usr/bin/node");
        assert!(unit.text.contains(&root.display().to_string()));
        assert!(unit.text.contains("orchestrator.mjs"));
        assert!(unit.text.contains(SERVICE_NAME));
        assert!(unit
            .install_command
            .contains(&unit.path.display().to_string()));
        assert!(unit.path.starts_with(root.join(SERVICE_DIR)));
        assert_eq!(
            unit.kind,
            if cfg!(target_os = "macos") {
                "launchd"
            } else {
                "systemd"
            }
        );
        std::fs::remove_dir_all(root).ok();
    }

    /// Asking the service manager is a READ: `status` calls it on every run,
    /// and must never register or render anything on the way.
    #[test]
    fn service_status_reports_the_label_and_installs_nothing() {
        let root = &scratch("service-status");
        let root = root.as_path();
        let state = service_status(root);
        assert_eq!(state.label, SERVICE_NAME);
        assert!(
            matches!(state.kind, "launchd" | "systemd" | "none"),
            "{state:?}"
        );
        assert!(
            !root.join(SERVICE_DIR).exists(),
            "asking never writes a unit"
        );
        std::fs::remove_dir_all(root).ok();
    }

    /// launchd and systemd start a unit with a minimal PATH, so a bare program
    /// name in the unit would not resolve at boot.
    #[test]
    fn a_program_is_resolved_absolutely_for_the_service_manager() {
        assert_eq!(absolute_program("/usr/bin/env"), "/usr/bin/env");
        let resolved = absolute_program("sh");
        assert!(resolved.starts_with('/'), "{resolved}");
        // an unresolvable name is left as it was, for the manager to refuse
        assert_eq!(
            absolute_program("definitely-not-a-program"),
            "definitely-not-a-program"
        );
    }

    /// The entry resolver must find the package in this checkout — the
    /// `start` verb has nothing to spawn otherwise.
    #[test]
    fn the_daemon_entry_resolves_in_this_checkout() {
        let entry = daemon_entry().expect("sdk/orchestrator/bin/orchestrator.mjs");
        assert!(entry.ends_with(DAEMON_ENTRY));
    }
}