flodl-cli 0.5.0

libtorch manager and GPU diagnostic tool for Rust deep learning
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
//! Registry of built-in commands. Single source of truth for dispatch,
//! help listing, collision detection, and shell completion.
//!
//! Each leaf sub-command owns a `#[derive(FdlArgs)]` struct that carries
//! the canonical flag set. `BuiltinSpec::schema_fn` returns the
//! `Schema` derived from that struct, so completion rules
//! (`--cuda <TAB>` → `12.6 12.8`, etc.) flow through the same pipeline
//! as project commands rather than a hand-mirrored flag table.

use crate::args::FdlArgsTrait;
use crate::config::Schema;

// ---------------------------------------------------------------------------
// FdlArgs structs (one per leaf sub-command)
//
// These dogfood the derive macro across flodl-cli itself. Each is parsed
// with `parse_or_schema_from(&argv)` from a sliced argv tail; the derive
// handles argv, `--help`, and `--fdl-schema` uniformly.
// ---------------------------------------------------------------------------

/// Interactive guided setup wizard.
#[derive(crate::FdlArgs, Debug)]
pub struct SetupArgs {
    /// Skip all prompts and use auto-detected defaults.
    #[option(short = 'y')]
    pub non_interactive: bool,
    /// Re-download or rebuild even if libtorch exists.
    #[option]
    pub force: bool,
}

/// System and GPU diagnostics.
#[derive(crate::FdlArgs, Debug)]
pub struct DiagnoseArgs {
    /// Emit machine-readable JSON.
    #[option]
    pub json: bool,
}

/// Generate flodl API reference.
#[derive(crate::FdlArgs, Debug)]
pub struct ApiRefArgs {
    /// Emit machine-readable JSON.
    #[option]
    pub json: bool,
    /// Explicit flodl source path (defaults to detected project root).
    #[option]
    pub path: Option<String>,
}

/// Scaffold a new floDl project.
#[derive(crate::FdlArgs, Debug)]
pub struct InitArgs {
    /// New project directory name.
    #[arg]
    pub name: Option<String>,
    /// Generate a Docker-based scaffold (libtorch baked into the image).
    #[option]
    pub docker: bool,
}

/// Install or update fdl globally (~/.local/bin/fdl).
#[derive(crate::FdlArgs, Debug)]
pub struct InstallArgs {
    /// Check for updates without installing.
    #[option]
    pub check: bool,
    /// Symlink to the current binary (tracks local builds).
    #[option]
    pub dev: bool,
}

/// List installed libtorch variants.
#[derive(crate::FdlArgs, Debug)]
pub struct LibtorchListArgs {
    /// Emit machine-readable JSON.
    #[option]
    pub json: bool,
}

/// Activate a libtorch variant.
#[derive(crate::FdlArgs, Debug)]
pub struct LibtorchActivateArgs {
    /// Variant to activate (as shown by `fdl libtorch list`).
    #[arg]
    pub variant: Option<String>,
}

/// Remove a libtorch variant.
#[derive(crate::FdlArgs, Debug)]
pub struct LibtorchRemoveArgs {
    /// Variant to remove (as shown by `fdl libtorch list`).
    #[arg]
    pub variant: Option<String>,
}

/// Download a pre-built libtorch variant.
#[derive(crate::FdlArgs, Debug)]
pub struct LibtorchDownloadArgs {
    /// Force the CPU variant.
    #[option]
    pub cpu: bool,
    /// Pick a specific CUDA version (instead of auto-detect).
    #[option(choices = &["12.6", "12.8"])]
    pub cuda: Option<String>,
    /// Install libtorch to this directory (default: project libtorch/).
    #[option]
    pub path: Option<String>,
    /// Do not activate after download.
    #[option]
    pub no_activate: bool,
    /// Show what would happen without downloading.
    #[option]
    pub dry_run: bool,
}

/// Build libtorch from source.
#[derive(crate::FdlArgs, Debug)]
pub struct LibtorchBuildArgs {
    /// Override CUDA architectures (semicolon-separated, e.g. "6.1;12.0").
    #[option]
    pub archs: Option<String>,
    /// Parallel compilation jobs.
    #[option(default = "6")]
    pub jobs: usize,
    /// Force Docker build (isolated, reproducible).
    #[option]
    pub docker: bool,
    /// Force native build (faster, requires host toolchain).
    #[option]
    pub native: bool,
    /// Show what would happen without building.
    #[option]
    pub dry_run: bool,
}

/// Install AI coding assistant skills.
#[derive(crate::FdlArgs, Debug)]
pub struct SkillInstallArgs {
    /// Target tool (defaults to auto-detect).
    #[option]
    pub tool: Option<String>,
    /// Specific skill name (defaults to all detected skills).
    #[option]
    pub skill: Option<String>,
}

/// List cached `--fdl-schema` outputs.
#[derive(crate::FdlArgs, Debug)]
pub struct SchemaListArgs {
    /// Emit machine-readable JSON.
    #[option]
    pub json: bool,
}

/// Clear cached schemas. No command name clears all.
#[derive(crate::FdlArgs, Debug)]
pub struct SchemaClearArgs {
    /// Command name to clear (defaults to all).
    #[arg]
    pub cmd: Option<String>,
}

/// Re-probe each entry and rewrite the cache.
#[derive(crate::FdlArgs, Debug)]
pub struct SchemaRefreshArgs {
    /// Command name to refresh (defaults to all).
    #[arg]
    pub cmd: Option<String>,
}

// ---------------------------------------------------------------------------
// Registry
// ---------------------------------------------------------------------------

/// One built-in command (or sub-command) slot.
pub struct BuiltinSpec {
    /// Path from the top-level command name. `["install"]`,
    /// `["libtorch", "download"]`.
    pub path: &'static [&'static str],
    /// One-line description for `fdl -h` listing. `None` = hidden
    /// (reserved for collision detection but not shown in help).
    pub description: Option<&'static str>,
    /// Constructor for the command's schema. `None` for parent commands
    /// that only group sub-commands (e.g. `libtorch` itself has no args)
    /// or for leaves whose argv is parsed by hand (`config show`,
    /// `completions`, `autocomplete`).
    pub schema_fn: Option<fn() -> Schema>,
}

/// Ordered registry of every built-in. Order drives `fdl -h` and the
/// top-level completion word list, so it mirrors today's `BUILTINS`
/// const in `main.rs`.
pub fn registry() -> &'static [BuiltinSpec] {
    static REG: &[BuiltinSpec] = &[
        BuiltinSpec {
            path: &["setup"],
            description: Some("Interactive guided setup"),
            schema_fn: Some(SetupArgs::schema),
        },
        BuiltinSpec {
            path: &["libtorch"],
            description: Some("Manage libtorch installations"),
            schema_fn: None,
        },
        BuiltinSpec {
            path: &["libtorch", "download"],
            description: Some("Download pre-built libtorch"),
            schema_fn: Some(LibtorchDownloadArgs::schema),
        },
        BuiltinSpec {
            path: &["libtorch", "build"],
            description: Some("Build libtorch from source"),
            schema_fn: Some(LibtorchBuildArgs::schema),
        },
        BuiltinSpec {
            path: &["libtorch", "list"],
            description: Some("Show installed variants"),
            schema_fn: Some(LibtorchListArgs::schema),
        },
        BuiltinSpec {
            path: &["libtorch", "activate"],
            description: Some("Set active variant"),
            schema_fn: Some(LibtorchActivateArgs::schema),
        },
        BuiltinSpec {
            path: &["libtorch", "remove"],
            description: Some("Remove a variant"),
            schema_fn: Some(LibtorchRemoveArgs::schema),
        },
        BuiltinSpec {
            path: &["libtorch", "info"],
            description: Some("Show active variant details"),
            schema_fn: None,
        },
        BuiltinSpec {
            path: &["init"],
            description: Some("Scaffold a new floDl project"),
            schema_fn: Some(InitArgs::schema),
        },
        BuiltinSpec {
            path: &["diagnose"],
            description: Some("System and GPU diagnostics"),
            schema_fn: Some(DiagnoseArgs::schema),
        },
        BuiltinSpec {
            path: &["install"],
            description: Some("Install or update fdl globally"),
            schema_fn: Some(InstallArgs::schema),
        },
        BuiltinSpec {
            path: &["skill"],
            description: Some("Manage AI coding assistant skills"),
            schema_fn: None,
        },
        BuiltinSpec {
            path: &["skill", "install"],
            description: Some("Install skills for the detected tool"),
            schema_fn: Some(SkillInstallArgs::schema),
        },
        BuiltinSpec {
            path: &["skill", "list"],
            description: Some("Show available skills"),
            schema_fn: None,
        },
        BuiltinSpec {
            path: &["api-ref"],
            description: Some("Generate flodl API reference"),
            schema_fn: Some(ApiRefArgs::schema),
        },
        BuiltinSpec {
            path: &["config"],
            description: Some("Inspect resolved project configuration"),
            schema_fn: None,
        },
        BuiltinSpec {
            path: &["config", "show"],
            description: Some("Print the resolved merged config"),
            schema_fn: None,
        },
        BuiltinSpec {
            path: &["schema"],
            description: Some("Inspect, clear, or refresh cached --fdl-schema outputs"),
            schema_fn: None,
        },
        BuiltinSpec {
            path: &["schema", "list"],
            description: Some("Show every cached schema with status"),
            schema_fn: Some(SchemaListArgs::schema),
        },
        BuiltinSpec {
            path: &["schema", "clear"],
            description: Some("Delete cached schema(s)"),
            schema_fn: Some(SchemaClearArgs::schema),
        },
        BuiltinSpec {
            path: &["schema", "refresh"],
            description: Some("Re-probe each entry and rewrite the cache"),
            schema_fn: Some(SchemaRefreshArgs::schema),
        },
        BuiltinSpec {
            path: &["completions"],
            description: Some("Emit shell completion script (bash|zsh|fish)"),
            schema_fn: None,
        },
        BuiltinSpec {
            path: &["autocomplete"],
            description: Some("Install completions into the detected shell"),
            schema_fn: None,
        },
        // Hidden: `version` is covered by `-V` / `--version` but still
        // reserved so first-arg env detection doesn't hijack it.
        BuiltinSpec {
            path: &["version"],
            description: None,
            schema_fn: None,
        },
    ];
    REG
}

/// True when `name` is a reserved top-level built-in (visible or hidden).
/// Drives env-collision detection in first-arg resolution.
pub fn is_builtin_name(name: &str) -> bool {
    registry()
        .iter()
        .any(|s| s.path.len() == 1 && s.path[0] == name)
}

/// Visible top-level built-ins as `(name, description)` pairs, in
/// registry order. Feeds `run::print_project_help` and the fallback
/// `print_usage`.
pub fn visible_top_level() -> Vec<(&'static str, &'static str)> {
    registry()
        .iter()
        .filter(|s| s.path.len() == 1)
        .filter_map(|s| s.description.map(|d| (s.path[0], d)))
        .collect()
}

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



    #[test]
    fn registry_has_no_duplicate_paths() {
        let mut seen = HashSet::new();
        for s in registry() {
            let key = s.path.join(" ");
            assert!(
                seen.insert(key.clone()),
                "duplicate registry path: {key}"
            );
        }
    }

    #[test]
    fn hidden_entries_have_no_description() {
        for s in registry() {
            if s.path == ["version"] {
                assert!(s.description.is_none(),
                    "`version` is hidden but carries a description");
            }
        }
    }

    #[test]
    fn every_parent_has_at_least_one_child() {
        let parents: HashSet<&str> = registry()
            .iter()
            .filter(|s| s.path.len() == 1 && s.schema_fn.is_none()
                && s.description.is_some())
            .map(|s| s.path[0])
            .collect();

        // `completions`, `autocomplete` are leaves with no schema — exclude
        // them by checking that parents have at least one 2-path child.
        for parent in &parents {
            let has_child = registry().iter().any(|s| s.path.len() == 2 && s.path[0] == *parent);
            if !has_child {
                // `completions` / `autocomplete` / `version` end up here by
                // virtue of having no children; they are leaf built-ins.
                continue;
            }
            assert!(has_child, "parent `{parent}` has no child entries");
        }
    }

    #[test]
    fn top_level_dispatched_by_main_is_in_registry() {
        // Compile-time guard: every match arm target in main.rs is listed
        // here. Keeping the list local (rather than introspecting main.rs)
        // documents the coupling explicitly.
        let dispatched = [
            "setup", "libtorch", "diagnose", "api-ref", "init", "install",
            "skill", "schema", "completions", "autocomplete", "config",
            "version",
        ];
        for name in &dispatched {
            assert!(
                is_builtin_name(name),
                "`{name}` dispatched by main.rs but missing from registry"
            );
        }
    }

    #[test]
    fn visible_top_level_matches_help_ordering() {
        let top = visible_top_level();
        let names: Vec<&str> = top.iter().map(|(n, _)| *n).collect();
        // Lock in the order that `fdl -h` depends on.
        assert_eq!(
            names,
            vec![
                "setup", "libtorch", "init", "diagnose", "install", "skill",
                "api-ref", "config", "schema", "completions", "autocomplete",
            ]
        );
    }

    #[test]
    fn libtorch_download_schema_carries_cuda_choices() {
        let spec = registry()
            .iter()
            .find(|s| s.path == ["libtorch", "download"])
            .expect("libtorch download entry present");
        let schema = (spec.schema_fn.expect("download has schema"))();
        let cuda = schema
            .options
            .get("cuda")
            .expect("`--cuda` option declared");
        let choices = cuda.choices.as_ref().expect("--cuda has choices");
        let values: Vec<String> = choices
            .iter()
            .filter_map(|v| v.as_str().map(str::to_string))
            .collect();
        assert_eq!(values, vec!["12.6".to_string(), "12.8".into()]);
    }
}