agent-first-data 0.40.0

A naming convention that lets AI agents understand your data without being told what it means, plus the afdata CLI and a Rust library for reading Markdown structure and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
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
//! The standard `skill status` / `skill install` / `skill uninstall` commands,
//! ready to mount on a program's own [`CliSpec`](crate::CliSpec).
//!
//! [`run_skill_admin`](crate::skill::run_skill_admin) does the filesystem
//! work, but a CLI also has to register the three verbs, declare which
//! argument mixes are legal, translate the resolved values back into
//! [`SkillOptions`], and turn the report or error into a protocol event. Those
//! rules are the same for every program that ships a skill, and a program that
//! writes its own copy drifts: a new agent missing from its enum, a fallback
//! that silently maps an unknown value to `all`, a generic error code in place
//! of [`SkillErrorKind::code`], a lost `partial_report`. This module owns all
//! of it, so the embedding program supplies only its [`SkillSpec`] and its
//! output contract.
//!
//! ```no_run
//! use agent_first_data::skill::{SKILL_CLI_ACTIONS, SkillCliRequest, SkillSpec, skill_cli_commands};
//! use agent_first_data::{CliHandler, CliMain, CliSpec, CliStop, CommandSpec, OutputSpec, ResolvedInvocation};
//!
//! const SKILL: SkillSpec = SkillSpec {
//!     name: "agent-first-widget",
//!     source: "---\nname: agent-first-widget\ndescription: Widgets.\n---\n",
//!     title: "Agent-First Widget",
//!     marker_slug: "afwidget",
//!     assets: &[],
//! };
//!
//! // The handler is the pure half: it reads the verb before any sink opens.
//! fn skill(invocation: &ResolvedInvocation) -> Result<SkillCliRequest, CliStop> {
//!     SkillCliRequest::from_invocation(invocation)
//! }
//!
//! let output = OutputSpec::protocol_finite(["json"], ["split"], "json", "split");
//! let mut spec = CliSpec::new("afwidget", "1.0.0")
//!     .lifecycle_output(output.clone())
//!     .command(CommandSpec::root());
//! for command in skill_cli_commands(&SKILL, &output) {
//!     spec = spec.command(command);
//! }
//! let handlers = SKILL_CLI_ACTIONS.map(|action| (action, skill as CliHandler<SkillCliRequest>));
//! let main = CliMain::new(spec.build(), |_| handlers);
//! # let _ = || main.run(std::env::args_os(), |request, _, emitter| Ok(request.run(&SKILL, emitter)));
//! ```

use crate::skill::{
    SkillAction, SkillAgentSelection, SkillError, SkillErrorKind, SkillOptions, SkillReport,
    SkillScope, SkillSpec, run_skill_admin,
};
use crate::{
    ArgSpec, CliEmitter, CliStop, Combination, CommandSpec, OutputSpec, ResolvedInvocation,
    cli_invocation_invalid_event, json_error, json_result,
};

/// The action ids [`skill_cli_commands`] registers, in verb order. Bind each
/// to a handler that calls [`SkillCliRequest::from_invocation`].
pub const SKILL_CLI_ACTIONS: [&str; 3] = ["skill_status", "skill_install", "skill_uninstall"];

/// The fan-out `--agent` value, which is not an agent of its own.
const EVERY_AGENT: &str = "all";

/// Every named agent with its `--agent` spelling. The enum, the shape that
/// accepts `--skills-dir`, and the translation back to a selection are all
/// built from this one table, so a new agent is one line here.
const AGENTS: [(&str, SkillAgentSelection); 4] = [
    ("codex", SkillAgentSelection::Codex),
    ("claude-code", SkillAgentSelection::ClaudeCode),
    ("opencode", SkillAgentSelection::Opencode),
    ("hermes", SkillAgentSelection::Hermes),
];

const SCOPES: [(&str, SkillScope); 2] = [
    ("personal", SkillScope::Personal),
    ("workspace", SkillScope::Workspace),
];

#[derive(Clone, Copy)]
struct Verb {
    command: &'static str,
    action: SkillAction,
    takes_force: bool,
}

const VERBS: [Verb; 3] = [
    Verb {
        command: "status",
        action: SkillAction::Status,
        takes_force: false,
    },
    Verb {
        command: "install",
        action: SkillAction::Install,
        takes_force: true,
    },
    Verb {
        command: "uninstall",
        action: SkillAction::Uninstall,
        takes_force: true,
    },
];

/// The `skill` command group and its three verbs, for `spec`'s skill.
///
/// Every combination uses `output`, so the verbs accept exactly the formats
/// and routing the rest of the program does. Each verb has two shapes:
/// `--agent all` (the default), and one named agent — the only shape that
/// accepts `--skills-dir`, since an explicit directory belongs to one agent.
/// The parser rejects the illegal mix, and `--help` shows both.
#[must_use]
pub fn skill_cli_commands(spec: &SkillSpec, output: &OutputSpec) -> Vec<CommandSpec> {
    let mut commands = vec![CommandSpec::new(["skill"]).about(format!(
        "Manage the {} skill for Codex, Claude Code, opencode, and Hermes",
        spec.title
    ))];
    commands.extend(VERBS.iter().map(|verb| verb_command(spec, *verb, output)));
    commands
}

fn verb_command(spec: &SkillSpec, verb: Verb, output: &OutputSpec) -> CommandSpec {
    let (about, shape_verb) = match verb.action {
        SkillAction::Status => (
            format!(
                "Report whether the {} skill is installed, valid, and current",
                spec.title
            ),
            "Report on",
        ),
        SkillAction::Install => (format!("Install the {} skill", spec.title), "Install into"),
        SkillAction::Uninstall => (
            format!(
                "Remove the {} skill that {} installed",
                spec.title, spec.marker_slug
            ),
            "Remove from",
        ),
    };
    let action = action_id(verb.action);
    let mut command = CommandSpec::new(["skill", verb.command])
        .about(about)
        .arg(
            ArgSpec::option_enum(
                "--agent",
                std::iter::once(EVERY_AGENT).chain(AGENTS.iter().map(|(name, _)| *name)),
            )
            .value_name("AGENT")
            .default(EVERY_AGENT)
            .about("Target agent"),
        )
        .arg(
            ArgSpec::option_enum("--scope", SCOPES.iter().map(|(name, _)| *name))
                .value_name("SCOPE")
                .default("personal")
                .about("Skill scope"),
        )
        .arg(
            ArgSpec::option("--skills-dir", "PATH")
                .about("Explicit skills directory; only valid with one named agent"),
        );
    let mut every_optional = vec!["scope"];
    let mut named_optional = vec!["scope", "skills_dir"];
    if verb.takes_force {
        command = command.arg(ArgSpec::flag("--force").about(format!(
            "Overwrite or remove a skill at the target path that {} did not install",
            spec.marker_slug
        )));
        every_optional.push("force");
        named_optional.push("force");
    }
    command
        .combination(
            Combination::new(format!("skill-{}-all", verb.command))
                .action(action)
                .about(format!("{shape_verb} every agent that supports the scope"))
                .fixed("agent", EVERY_AGENT)
                .optional(every_optional)
                .output(output.clone()),
        )
        .combination(
            Combination::new(format!("skill-{}-agent", verb.command))
                .action(action)
                .about(format!(
                    "{shape_verb} one named agent; only this shape accepts --skills-dir"
                ))
                .fixed_one_of("agent", AGENTS.iter().map(|(name, _)| *name))
                .optional(named_optional)
                .output(output.clone()),
        )
}

fn action_id(action: SkillAction) -> &'static str {
    match action {
        SkillAction::Status => SKILL_CLI_ACTIONS[0],
        SkillAction::Install => SKILL_CLI_ACTIONS[1],
        SkillAction::Uninstall => SKILL_CLI_ACTIONS[2],
    }
}

/// A `skill` verb read out of its resolved invocation, ready to run later.
///
/// This is the pure half of a skill command: a program's handler returns it
/// (or carries it inside its own command type) before any output sink opens,
/// and runs it afterwards with the emitter it was handed.
#[derive(Clone, Debug)]
pub struct SkillCliRequest {
    action: SkillAction,
    options: SkillOptions,
}

impl SkillCliRequest {
    /// Read a resolved `skill` verb registered by [`skill_cli_commands`].
    ///
    /// An invocation this module did not register is a defect in the program,
    /// reported as `cli_invocation_invalid` (exit 1).
    pub fn from_invocation(invocation: &ResolvedInvocation) -> Result<Self, CliStop> {
        let action_id = invocation.action_id();
        let verb = VERBS
            .iter()
            .find(|verb| self::action_id(verb.action) == action_id)
            .ok_or_else(|| defect(&format!("action `{action_id}` is not a skill action")))?;
        let action = verb.action;
        let agent_name = invocation.text("agent")?;
        let agent = if agent_name == EVERY_AGENT {
            SkillAgentSelection::All
        } else {
            lookup(&AGENTS, agent_name, "--agent").map_err(|detail| defect(&detail))?
        };
        let scope = lookup(&SCOPES, invocation.text("scope")?, "--scope")
            .map_err(|detail| defect(&detail))?;
        // Only the named-agent shape declares `--skills-dir`, and only verbs
        // that can overwrite declare `--force`; the other shapes have nothing
        // to read.
        let skills_dir = if invocation.declares("skills_dir") {
            invocation.optional_text("skills_dir")?.map(str::to_string)
        } else {
            None
        };
        let force = invocation.declares("force") && invocation.flag("force")?;
        Ok(Self {
            action,
            options: SkillOptions {
                agent,
                scope,
                skills_dir,
                force,
            },
        })
    }

    /// The action this request performs.
    #[must_use]
    pub const fn action(&self) -> SkillAction {
        self.action
    }

    /// The options read from the command line.
    #[must_use]
    pub const fn options(&self) -> &SkillOptions {
        &self.options
    }

    /// Perform the action for `spec` without writing anything.
    ///
    /// For a program with its own work to do once the skill files are in
    /// place, before the command's one terminal event is written. A program
    /// with nothing to add calls [`SkillCliRequest::run`].
    #[must_use]
    pub fn execute(&self, spec: &SkillSpec) -> SkillCliOutcome {
        SkillCliOutcome {
            result: run_skill_admin(spec, self.action, &self.options),
        }
    }

    /// Perform the action for `spec` and emit its outcome: [`execute`] then
    /// [`SkillCliOutcome::emit`].
    ///
    /// [`execute`]: SkillCliRequest::execute
    pub fn run<W: std::io::Write>(&self, spec: &SkillSpec, emitter: &mut CliEmitter<W>) -> u8 {
        self.execute(spec).emit(emitter)
    }
}

/// What a skill verb did, not yet written.
#[derive(Debug)]
pub struct SkillCliOutcome {
    result: Result<SkillReport, SkillError>,
}

impl SkillCliOutcome {
    /// The report, when the action succeeded.
    #[must_use]
    pub fn report(&self) -> Option<&SkillReport> {
        self.result.as_ref().ok()
    }

    /// The skill failure, when the action ran and failed.
    #[must_use]
    pub fn error(&self) -> Option<&SkillError> {
        self.result.as_ref().err()
    }

    /// Write the outcome as the command's one terminal event and return the
    /// exit status, settled by [`CliEmitter::finish`].
    ///
    /// Exit status: `0` with the [`SkillReport`] as the result; `2` for
    /// [`SkillErrorKind::Usage`], decided before any target is touched; `1`
    /// for every other failure, with the error's [`SkillErrorKind::code`] as
    /// `error.code` and any per-target `partial_report`.
    pub fn emit<W: std::io::Write>(self, emitter: &mut CliEmitter<W>) -> u8 {
        match self.result {
            Ok(report) => match serde_json::to_value(&report) {
                Ok(value) => emitter.finish(json_result(value).build(), 0),
                Err(error) => emitter.finish(
                    build_error(json_error(
                        "skill_report_serialization_failed",
                        &format!("failed to serialize the skill report: {error}"),
                    )),
                    1,
                ),
            },
            Err(error) => {
                let status = match error.kind {
                    SkillErrorKind::Usage => 2,
                    _ => 1,
                };
                emitter.finish(skill_error_event(&error), status)
            }
        }
    }
}

fn defect(detail: &str) -> CliStop {
    CliStop::new(cli_invocation_invalid_event(detail), 1)
}

fn lookup<T: Copy>(table: &[(&str, T)], value: &str, flag: &str) -> Result<T, String> {
    table
        .iter()
        .find(|(name, _)| *name == value)
        .map(|(_, item)| *item)
        .ok_or_else(|| format!("{flag} value `{value}` is not registered"))
}

fn skill_error_event(error: &SkillError) -> crate::Event {
    let mut builder =
        json_error(error.kind.code(), &error.message).hint_if_some(error.hint.as_deref());
    if let Some(report) = error.partial_report.as_ref()
        && let Ok(value) = serde_json::to_value(report)
    {
        builder = builder.field("partial_report", value);
    }
    build_error(builder)
}

fn build_error(builder: crate::ErrorBuilder) -> crate::Event {
    builder
        .build()
        .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct the skill error"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CliOutcome, CliSpec, build_afdata_cli};

    const SPEC: SkillSpec = SkillSpec {
        name: "agent-first-widget",
        source: "---\nname: agent-first-widget\ndescription: Widgets.\n---\n",
        title: "Agent-First Widget",
        marker_slug: "afwidget",
        assets: &[],
    };

    fn cli() -> crate::BuiltCliSpec {
        let output = OutputSpec::protocol_finite(["json"], ["split"], "json", "split");
        let mut spec = CliSpec::new("afwidget", "1.0.0")
            .lifecycle_output(output.clone())
            .command(CommandSpec::root());
        for command in skill_cli_commands(&SPEC, &output) {
            spec = spec.command(command);
        }
        match build_afdata_cli(spec) {
            Ok(cli) => cli,
            Err(error) => panic!("skill commands must build: {error}"),
        }
    }

    fn resolve(argv: &[&str]) -> Result<(SkillAction, SkillOptions), String> {
        let mut full = vec!["afwidget"];
        full.extend_from_slice(argv);
        match cli().resolve_from(full) {
            Ok(CliOutcome::Run(invocation)) => SkillCliRequest::from_invocation(&invocation)
                .map(|request| (request.action, request.options))
                .map_err(|stop| format!("{:?}", stop.event())),
            Ok(_) => Err("not a run".to_string()),
            Err(error) => Err(error.rule.code().to_string()),
        }
    }

    #[test]
    fn every_action_is_registered_once() {
        let handlers = SKILL_CLI_ACTIONS.map(|action| {
            (
                action,
                (|_: &ResolvedInvocation| Ok(())) as crate::CliHandler<()>,
            )
        });
        assert!(cli().bind_actions(handlers).is_ok());
    }

    #[test]
    fn defaults_reach_every_personal_agent() {
        match resolve(&["skill", "status"]) {
            Ok((action, options)) => {
                assert_eq!(action, SkillAction::Status);
                assert_eq!(options.agent, SkillAgentSelection::All);
                assert_eq!(options.scope, SkillScope::Personal);
                assert_eq!(options.skills_dir, None);
                assert!(!options.force);
            }
            Err(error) => panic!("status must resolve: {error}"),
        }
    }

    #[test]
    fn every_registered_agent_translates() {
        for (name, selection) in AGENTS {
            match resolve(&["skill", "install", "--agent", name, "--force"]) {
                Ok((action, options)) => {
                    assert_eq!(action, SkillAction::Install);
                    assert_eq!(options.agent, selection);
                    assert!(options.force);
                }
                Err(error) => panic!("--agent {name} must resolve: {error}"),
            }
        }
    }

    #[test]
    fn serialized_names_are_the_cli_values() {
        let every = serde_json::to_value(SkillAgentSelection::All).ok();
        assert_eq!(
            every.as_ref().and_then(|value| value.as_str()),
            Some(EVERY_AGENT)
        );
        for (name, selection) in AGENTS {
            let value = serde_json::to_value(selection).ok();
            assert_eq!(value.as_ref().and_then(|value| value.as_str()), Some(name));
        }
        for (name, scope) in SCOPES {
            let value = serde_json::to_value(scope).ok();
            assert_eq!(value.as_ref().and_then(|value| value.as_str()), Some(name));
        }
        for verb in VERBS {
            let value = serde_json::to_value(verb.action).ok();
            assert_eq!(
                value.as_ref().and_then(|value| value.as_str()),
                Some(verb.command)
            );
        }
    }

    #[test]
    fn skills_dir_needs_one_named_agent() {
        assert!(resolve(&["skill", "install", "--skills-dir", "/tmp/skills"]).is_err());
        match resolve(&[
            "skill",
            "uninstall",
            "--agent",
            "codex",
            "--scope",
            "workspace",
            "--skills-dir",
            "/tmp/skills",
        ]) {
            Ok((action, options)) => {
                assert_eq!(action, SkillAction::Uninstall);
                assert_eq!(options.scope, SkillScope::Workspace);
                assert_eq!(options.skills_dir.as_deref(), Some("/tmp/skills"));
            }
            Err(error) => panic!("one named agent accepts --skills-dir: {error}"),
        }
    }

    fn request(argv: &[&str]) -> SkillCliRequest {
        let mut full = vec!["afwidget"];
        full.extend_from_slice(argv);
        match cli().resolve_from(full) {
            Ok(CliOutcome::Run(invocation)) => {
                match SkillCliRequest::from_invocation(&invocation) {
                    Ok(request) => request,
                    Err(stop) => panic!("{argv:?} did not read: {:?}", stop.event()),
                }
            }
            Ok(_) => panic!("{argv:?} is not a run"),
            Err(error) => panic!("{argv:?} failed to resolve: {}", error.message),
        }
    }

    #[test]
    fn execute_reports_without_emitting() {
        let dir = std::env::temp_dir().join(format!("afdata_skill_cli_{}", std::process::id()));
        let dir_text = dir.to_string_lossy().to_string();
        let install = request(&[
            "skill",
            "install",
            "--agent",
            "codex",
            "--skills-dir",
            &dir_text,
        ]);
        assert_eq!(install.action(), SkillAction::Install);
        assert_eq!(
            install.options().skills_dir.as_deref(),
            Some(dir_text.as_str())
        );
        let installed = install.execute(&SPEC);
        assert!(matches!(
            installed.report(),
            Some(SkillReport::Install { .. })
        ));
        assert!(installed.error().is_none());

        let unmanaged = dir.join("agent-first-widget").join("SKILL.md");
        assert!(
            std::fs::write(
                &unmanaged,
                "---\nname: agent-first-widget\ndescription: Mine.\n---\n"
            )
            .is_ok()
        );
        let refused = install.execute(&SPEC);
        assert!(refused.report().is_none());
        assert_eq!(
            refused.error().map(|error| error.kind),
            Some(SkillErrorKind::Refused)
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn status_rejects_force() {
        assert!(resolve(&["skill", "status", "--force"]).is_err());
    }
}