orchestratectl 0.1.7

Rust CLI for orchestrating AI-agent workflows on a developer's machine.
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
//! `skill.sync.<name>` — every bundled companion skill's on-disk
//! `cli_version` matches the running binary (AGENTS-AI-FIRST-CLI §17/§18
//! "skill sync").
//!
//! Drift matters because the skill *is* the agent's operating manual for
//! the binary: an out-of-date skill describes commands that may have
//! moved. Classification:
//!
//! - on-disk **older** than the binary → `WARN` + safe `--fix`
//!   (`skill install <name> --force`).
//! - on-disk **newer** than the binary → `WARN`, suggest a binary
//!   upgrade (no autonomous fix — the agent installed ahead of the
//!   binary on purpose, perhaps).
//! - **not installed** → `WARN` (info-as-warn), suggest install; not an
//!   autonomous fix (the §18 safe subset is drift-only).
//! - on-disk version **unreadable / unparseable** → `WARN`, suggest a
//!   forced re-install (no autonomous fix; we refuse to guess).
//! - **in sync** → `OK`.

use std::cmp::Ordering;

use crate::doctor::check::{CheckResult, FixAction};
use crate::skill;

use super::Ctx;

pub fn check(_ctx: &Ctx) -> Vec<CheckResult> {
    let binary = skill::binary_cli_version();
    let mut out = Vec::new();

    for name in skill::bundled_skill_names() {
        let id = format!("skill.sync.{name}");
        let suggest_install = format!("orchestratectl skill install {name} --force");

        let Some(path) = skill::claude_default_path(name) else {
            // HOME unset: cannot locate any install. config.home already
            // reports the root cause as a FAIL — emit a single consolidated
            // skill.sync WARN rather than one noisy duplicate per skill.
            out.push(CheckResult::warn(
                "skill.sync",
                "cannot locate skill installs (HOME unset)",
                "set HOME so the default skill path resolves",
            ));
            break;
        };

        if !path.exists() {
            out.push(CheckResult::warn(
                id,
                format!("skill '{name}' is not installed at {}", path.display()),
                suggest_install,
            ));
            continue;
        }

        let on_disk = skill::read_on_disk_cli_version(&path);
        match on_disk
            .as_deref()
            .and_then(|v| compare(v, binary).map(|o| (v, o)))
        {
            Some((_, Ordering::Equal)) => {
                out.push(CheckResult::ok(
                    id,
                    format!("skill '{name}' in sync at cli_version {binary}"),
                ));
            }
            Some((v, Ordering::Less)) => {
                out.push(
                    CheckResult::warn(
                        id,
                        format!("skill '{name}' is cli_version {v}, binary is {binary}"),
                        suggest_install,
                    )
                    .with_safe_fix(FixAction::InstallSkill(name.to_string())),
                );
            }
            Some((v, Ordering::Greater)) => {
                out.push(CheckResult::warn(
                    id,
                    format!(
                        "skill '{name}' on disk is cli_version {v}, newer than binary {binary}"
                    ),
                    "upgrade the orchestratectl binary to match the installed skill",
                ));
            }
            None => {
                out.push(CheckResult::warn(
                    id,
                    format!(
                        "skill '{name}' has an unreadable/unparseable cli_version at {}",
                        path.display()
                    ),
                    suggest_install,
                ));
            }
        }

        // Companion resource files shipped alongside this skill's SKILL.md
        // (e.g. `stint-start/AGENTS-EXECUTION-DAG.md`). Each installs as a
        // sibling of SKILL.md; a missing, stale, or user-edited companion
        // leaves the skill's in-body link dangling while SKILL.md itself
        // still looks in sync, so audit each one under its own id. Only
        // reached when SKILL.md exists (the not-installed arm above
        // `continue`s — the skill-not-installed WARN already covers the
        // companions a re-install would restore).
        if let Some(skill_dir) = path.parent() {
            for companion in skill::companion_sources(name) {
                let companion_path = skill_dir.join(companion.filename);
                out.push(check_companion(name, &companion, &companion_path, binary));
            }

            // `skill.orphan.<name>.<file>` — a companion the skill's
            // provenance marker records as orchestratectl-managed but the
            // current binary no longer bundles: installed by a prior binary,
            // dropped by this one, lingering as a stale sibling. Distinct from
            // the `skill.sync.<name>.<file>` cases above (those audit
            // companions this binary DOES ship). The fix is a forced
            // re-install, whose prune loop removes the orphan file; we surface
            // it as a WARN rather than fixing autonomously (deletion stays with
            // the explicit install path, symmetric with `skill.orphan.<name>`).
            for filename in skill::orphan_companions(name, skill_dir) {
                let orphan_path = skill_dir.join(&filename);
                out.push(CheckResult::warn(
                    format!("skill.orphan.{name}.{filename}"),
                    format!(
                        "companion '{filename}' for skill '{name}' at {} is orchestratectl-managed but the current binary no longer bundles it (de-registered)",
                        orphan_path.display()
                    ),
                    format!("orchestratectl skill install {name} --force"),
                ));
            }
        }
    }

    // `skill.orphan.<name>` — a claude-layout skill directory that
    // orchestratectl installed (carries the provenance marker) but the
    // running binary no longer ships. This is a renamed/removed bundled
    // skill left stranded as a stale slash-command. `skill install`
    // auto-prunes these on its next full-catalog run, so the fix is a
    // forced re-install; we surface it as a WARN rather than fixing
    // autonomously (deletion stays with the explicit install path).
    for (name, dir) in skill::managed_orphans() {
        out.push(CheckResult::warn(
            format!("skill.orphan.{name}"),
            format!(
                "skill '{name}' at {} is orchestratectl-managed but no longer in the catalog (de-registered)",
                dir.display()
            ),
            "orchestratectl skill install --force",
        ));
    }

    check_codex(binary, &mut out);

    out
}

/// Codex flat-layout coverage — the `skill.sync.codex.*` /
/// `skill.orphan.codex.*` mirror of the claude checks above, keyed to the
/// codex paths (`~/.codex/prompts/<name>.md` and the shared companions in
/// `~/.codex/prompts/_shared/<file>`).
///
/// The whole section is GATED on orchestratectl actually managing codex on
/// this host: the shared provenance marker records which prompts +
/// companions we installed, so an absent marker (e.g. a claude-only
/// install, where codex is a secondary export the user never targeted)
/// yields no codex checks and keeps a claude-primary tree 0-warn. The
/// marker's recorded set is also the source of truth for what "should" be
/// present, so a bundled skill the user simply chose not to install to
/// codex is never flagged.
///
/// Codex drift carries NO autonomous `--fix`: the `FixAction::InstallSkill`
/// applier re-runs `skill install <name> --force`, which targets the claude
/// (+ pi) layout, not codex. A codex re-install needs `--agent codex`/`all`,
/// so we surface the suggestion and leave the deletion/reinstall to the
/// explicit install path (symmetric with the claude orphan checks, which are
/// advisory too).
fn check_codex(binary: &str, out: &mut Vec<CheckResult>) {
    let managed_prompts = skill::codex_managed_prompts();
    let managed_companions = skill::codex_managed_companions();
    if managed_prompts.is_empty() && managed_companions.is_empty() {
        return;
    }

    let catalog: std::collections::HashSet<&str> =
        skill::bundled_skill_names().into_iter().collect();

    // Codex skill sync (recorded ∩ catalog) + orphan (recorded ∖ catalog).
    for name in &managed_prompts {
        let Some(path) = skill::codex_default_path(name) else {
            continue;
        };
        if catalog.contains(name.as_str()) {
            let id = format!("skill.sync.codex.{name}");
            let suggest = format!("orchestratectl skill install {name} --agent codex --force");
            if !path.exists() {
                out.push(CheckResult::warn(
                    id,
                    format!(
                        "codex skill '{name}' is not installed at {}",
                        path.display()
                    ),
                    suggest,
                ));
                continue;
            }
            match skill::read_on_disk_cli_version(&path)
                .as_deref()
                .and_then(|v| compare(v, binary).map(|o| (v, o)))
            {
                Some((_, Ordering::Equal)) => out.push(CheckResult::ok(
                    id,
                    format!("codex skill '{name}' in sync at cli_version {binary}"),
                )),
                Some((v, Ordering::Less)) => out.push(CheckResult::warn(
                    id,
                    format!("codex skill '{name}' is cli_version {v}, binary is {binary}"),
                    suggest,
                )),
                Some((v, Ordering::Greater)) => out.push(CheckResult::warn(
                    id,
                    format!(
                        "codex skill '{name}' on disk is cli_version {v}, newer than binary {binary}"
                    ),
                    "upgrade the orchestratectl binary to match the installed skill",
                )),
                None => out.push(CheckResult::warn(
                    id,
                    format!(
                        "codex skill '{name}' has an unreadable/unparseable cli_version at {}",
                        path.display()
                    ),
                    suggest,
                )),
            }
        } else {
            // Recorded but de-registered: an orphan, but only if the flat
            // prompt file is still on disk (a marker record whose file was
            // already removed is nothing to flag).
            if std::fs::symlink_metadata(&path).is_ok() {
                out.push(CheckResult::warn(
                    format!("skill.orphan.codex.{name}"),
                    format!(
                        "codex skill '{name}' at {} is orchestratectl-managed but no longer in the catalog (de-registered)",
                        path.display()
                    ),
                    "orchestratectl skill install --agent codex --force",
                ));
            }
        }
    }

    // Codex companion sync + orphan, resolved against the shared `_shared/`
    // dir. Companions are byte-identical to the bundled source (only skill
    // bodies get the codex link rewrite), so the same content-identity check
    // the claude companions use applies.
    let Some(shared_root) = skill::codex_shared_root() else {
        return;
    };
    let bundled: std::collections::HashSet<&str> = skill::all_companion_sources()
        .iter()
        .map(|c| c.filename)
        .collect();
    for companion in skill::all_companion_sources() {
        if !managed_companions.iter().any(|c| c == companion.filename) {
            continue; // codex does not manage this companion here
        }
        let path = shared_root.join(companion.filename);
        out.push(check_codex_companion(&companion, &path, binary));
    }
    for filename in &managed_companions {
        if bundled.contains(filename.as_str()) {
            continue; // still bundled → audited by the sync check above
        }
        let path = shared_root.join(filename);
        if std::fs::symlink_metadata(&path).is_ok() {
            out.push(CheckResult::warn(
                format!("skill.orphan.codex._shared.{filename}"),
                format!(
                    "codex companion '_shared/{filename}' at {} is orchestratectl-managed but no bundled skill references it any more (de-registered)",
                    path.display()
                ),
                "orchestratectl skill install --agent codex --force",
            ));
        }
    }
}

/// Audit one codex `_shared/<file>` companion against the binary's bundled
/// copy. Content identity is the in-sync signal (a freshly installed
/// companion is byte-identical); on a difference, classify by the declared
/// `cli_version` with the same drift model as the claude companion check.
/// No autonomous fix (see [`check_codex`]).
fn check_codex_companion(
    companion: &skill::CompanionSource,
    path: &std::path::Path,
    binary: &str,
) -> CheckResult {
    let filename = companion.filename;
    let id = format!("skill.sync.codex._shared.{filename}");
    let suggest = "orchestratectl skill install --agent codex --force".to_string();

    let on_disk = match std::fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return CheckResult::warn(
                id,
                format!(
                    "codex companion '_shared/{filename}' is not installed at {}",
                    path.display()
                ),
                suggest,
            );
        }
        Err(e) => {
            return CheckResult::warn(
                id,
                format!(
                    "codex companion '_shared/{filename}' is unreadable at {}: {e}",
                    path.display()
                ),
                suggest,
            );
        }
    };

    if on_disk == companion.bundled_body {
        return CheckResult::ok(
            id,
            format!(
                "codex companion '_shared/{filename}' matches the bundled content for binary {binary}"
            ),
        );
    }

    match skill::cli_version_of(&on_disk)
        .as_deref()
        .and_then(|v| compare(v, binary).map(|o| (v, o)))
    {
        Some((v, Ordering::Less)) => CheckResult::warn(
            id,
            format!(
                "codex companion '_shared/{filename}' is cli_version {v}, binary is {binary}"
            ),
            suggest,
        ),
        Some((v, Ordering::Greater)) => CheckResult::warn(
            id,
            format!(
                "codex companion '_shared/{filename}' differs from the bundled copy and declares cli_version {v}, newer than binary {binary}"
            ),
            "upgrade the orchestratectl binary, or reinstall with --agent codex --force to restore the bundled companion",
        ),
        Some((_, Ordering::Equal)) => CheckResult::warn(
            id,
            format!(
                "codex companion '_shared/{filename}' differs from the bundled copy while its cli_version matches binary {binary} (possible local edits)"
            ),
            suggest,
        ),
        None => CheckResult::warn(
            id,
            format!(
                "codex companion '_shared/{filename}' differs from the bundled copy and declares no parseable cli_version at {}",
                path.display()
            ),
            suggest,
        ),
    }
}

/// Audit one companion resource against the binary's bundled copy. Content
/// identity is the primary in-sync signal — a freshly installed companion
/// is byte-identical to the embedded source (both rendered through the same
/// `{{CLI_VERSION}}` substitution), so any byte difference means it is
/// stale, ahead of the binary, or edited. When it differs, classify by the
/// declared `cli_version` using the same semver drift model as SKILL.md so
/// the message names which way it drifted. The id embeds the filename so the
/// offending companion is unambiguous.
///
/// Note: this audits only companions the *current* binary bundles (the
/// forward direction). A companion a prior binary installed but this one no
/// longer ships is an ORPHAN, detected separately by the
/// `skill.orphan.<name>.<file>` pass in [`check`] (backed by the provenance
/// marker's `companion:` records + `skill::orphan_companions`).
fn check_companion(
    skill_name: &str,
    companion: &skill::CompanionSource,
    path: &std::path::Path,
    binary: &str,
) -> CheckResult {
    let filename = companion.filename;
    let id = format!("skill.sync.{skill_name}.{filename}");
    let suggest_install = format!("orchestratectl skill install {skill_name} --force");

    // One read serves both existence and content: `read_to_string` returns
    // `NotFound` for a missing companion (never installed) and a distinct
    // error otherwise, so we classify precisely and avoid the
    // exists()-then-read TOCTOU (and its symlink following).
    let on_disk = match std::fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return CheckResult::warn(
                id,
                format!(
                    "companion '{filename}' for skill '{skill_name}' is not installed at {}",
                    path.display()
                ),
                suggest_install,
            );
        }
        Err(e) => {
            return CheckResult::warn(
                id,
                format!(
                    "companion '{filename}' for skill '{skill_name}' is unreadable at {}: {e}",
                    path.display()
                ),
                suggest_install,
            );
        }
    };

    // Content identity is the primary in-sync signal: a freshly installed
    // companion is byte-identical to the embedded source. We deliberately
    // report what was checked (a content match) rather than asserting a
    // parsed version, since a companion need not carry `cli_version`
    // frontmatter.
    if on_disk == companion.bundled_body {
        return CheckResult::ok(
            id,
            format!(
                "companion '{filename}' for skill '{skill_name}' matches the bundled content for binary {binary}"
            ),
        );
    }

    // Content differs — classify by the declared `cli_version` (metadata in
    // the differing file, so the message states evidence, not provenance).
    let disk_version = skill::cli_version_of(&on_disk);
    match disk_version
        .as_deref()
        .and_then(|v| compare(v, binary).map(|o| (v, o)))
    {
        Some((v, Ordering::Less)) => CheckResult::warn(
            id,
            format!(
                "companion '{filename}' for skill '{skill_name}' is cli_version {v}, binary is {binary}"
            ),
            suggest_install,
        )
        .with_safe_fix(FixAction::InstallSkill(skill_name.to_string())),
        Some((v, Ordering::Greater)) => CheckResult::warn(
            id,
            format!(
                "companion '{filename}' for skill '{skill_name}' differs from the bundled copy and declares cli_version {v}, newer than binary {binary}"
            ),
            "upgrade the orchestratectl binary, or reinstall with --force to restore the bundled companion",
        ),
        Some((_, Ordering::Equal)) => CheckResult::warn(
            id,
            format!(
                "companion '{filename}' for skill '{skill_name}' differs from the bundled copy while its cli_version matches binary {binary} (possible local edits)"
            ),
            suggest_install,
        ),
        None => CheckResult::warn(
            id,
            format!(
                "companion '{filename}' for skill '{skill_name}' differs from the bundled copy and declares no parseable cli_version at {}",
                path.display()
            ),
            suggest_install,
        ),
    }
}

/// Semver-correct comparison; `None` if either side does not parse (the
/// caller routes that to the "unparseable" arm rather than inventing an
/// ordering).
fn compare(a: &str, b: &str) -> Option<Ordering> {
    let av = semver::Version::parse(a).ok()?;
    let bv = semver::Version::parse(b).ok()?;
    Some(av.cmp(&bv))
}