agent-first-slug 0.6.0

Rust slug generation with explicit caller configuration for path and URL path segments.
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
#![cfg(feature = "cli")]
#![allow(clippy::expect_used)]

use std::process::{Command, Output};

use serde_json::{Value, json};

fn run(args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_afslug"))
        .args(args)
        .output()
        .expect("afslug should run")
}

fn stdout_json(output: &Output) -> Value {
    serde_json::from_slice(&output.stdout).expect("stdout should contain one JSON event")
}

fn stderr_json(output: &Output) -> Value {
    serde_json::from_slice(&output.stderr).expect("stderr should contain one JSON event")
}

fn help_of(output: &Output) -> Value {
    stdout_json(output)["result"]["help"].clone()
}

#[test]
fn slugifies_with_a_strict_afdata_result() {
    let output = run(&["slugify", "Hello, 世界!"]);

    assert!(output.status.success());
    assert!(output.stderr.is_empty());
    assert_eq!(
        stdout_json(&output),
        json!({
            "kind": "result",
            "result": {
                "code": "slugify",
                "slug": "hello-世界",
                "changed_from_input": true
            },
            "trace": {}
        })
    );
}

#[test]
fn supports_plain_afdata_output() {
    let output = run(&["slugify", "Already-Slug", "--output", "plain"]);

    assert!(output.status.success());
    assert!(output.stderr.is_empty());
    let stdout = String::from_utf8(output.stdout).expect("stdout should be UTF-8");
    // `trace={}` is present because plain renders an empty container explicitly
    // rather than letting the key vanish; plain is not a lossy view of the JSON.
    assert_eq!(
        stdout,
        "kind=result result.changed_from_input=true result.code=slugify \
         result.slug=already-slug trace={}\n"
    );
}

#[test]
fn supports_yaml_afdata_output() {
    let output = run(&["slugify", "Hello, World!", "--output", "yaml"]);

    assert!(output.status.success());
    assert!(output.stderr.is_empty());
    let stdout = String::from_utf8(output.stdout).expect("stdout should be UTF-8");
    assert_eq!(
        stdout,
        concat!(
            "---\n",
            "kind: \"result\"\n",
            "result:\n",
            "  changed_from_input: true\n",
            "  code: \"slugify\"\n",
            "  slug: \"hello-world\"\n",
            "trace: {}\n",
        )
    );
}

#[test]
fn slugify_honors_config_flags() {
    // ASCII-only charset drops the CJK run, truncation caps the slug, and the
    // trailing delimiter the cut exposes is stripped.
    let output = run(&[
        "slugify",
        "Rust 版 CLI Tool",
        "--charset",
        "ascii-alphanumeric",
        "--max-chars",
        "8",
    ]);

    assert!(output.status.success());
    assert_eq!(stdout_json(&output)["result"]["slug"], "rust-cli");
}

#[test]
fn slugify_keeps_case_when_lowercasing_is_disabled() {
    let output = run(&["slugify", "Hello World", "--no-lowercase"]);

    assert!(output.status.success());
    assert_eq!(stdout_json(&output)["result"]["slug"], "Hello-World");
}

#[test]
fn slugify_substitutes_fallback_for_empty_output() {
    let output = run(&["slugify", "!!!", "--fallback", "item"]);

    assert!(output.status.success());
    assert_eq!(stdout_json(&output)["result"]["slug"], "item");
}

#[test]
fn slugify_validation_failure_is_a_structured_error() {
    // Punctuation-only input yields an empty slug, which is not a valid URL segment.
    let output = run(&["slugify", "!!!", "--validation", "url-path"]);

    assert_eq!(output.status.code(), Some(1));
    let event = stderr_json(&output);
    assert_eq!(event["kind"], "error");
    assert_eq!(event["error"]["code"], "slug_error");
}

#[test]
fn validate_accepts_a_valid_segment() {
    let output = run(&["validate", "my-slug", "--policy", "url-path"]);

    assert!(output.status.success());
    assert_eq!(
        stdout_json(&output),
        json!({
            "kind": "result",
            "result": {
                "code": "validate",
                "value": "my-slug",
                "valid": true
            },
            "trace": {}
        })
    );
}

#[test]
fn validate_rejects_an_invalid_segment_as_a_structured_error() {
    let output = run(&["validate", "bad/slug", "--policy", "local-path"]);

    assert_eq!(output.status.code(), Some(1));
    let event = stderr_json(&output);
    assert_eq!(event["kind"], "error");
    assert_eq!(event["error"]["code"], "slug_error");
    assert_eq!(event["error"]["retryable"], false);
}

#[test]
fn reports_argument_errors_as_afdata_json() {
    let output = run(&[]);

    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());
    let event = stderr_json(&output);
    assert_eq!(event["kind"], "error");
    // The classification is the code itself, so an agent branches on one key
    // rather than parsing a message or reading a second field.
    assert_eq!(event["error"]["code"], "cli_unregistered_combination");
    assert_eq!(event["error"]["retryable"], false);
    assert_eq!(event["trace"], json!({}));
}

#[test]
fn explicit_json_version_is_structured() {
    let output = run(&["--version", "--output", "json"]);

    assert!(output.status.success());
    let value = stdout_json(&output);
    assert_eq!(value["kind"], "result");
    assert_eq!(value["result"]["code"], "version");
    assert_eq!(value["result"]["name"], "afslug");
    assert_eq!(value["result"]["display_name"], "Agent-First Slug");
    assert_eq!(value["result"]["version"], env!("CARGO_PKG_VERSION"));
    // "build" (git SHA) is environment-dependent (absent without a reachable
    // .git, e.g. a source tarball) so it is deliberately not asserted here.
    assert_eq!(value["trace"], json!({}));
}

#[test]
fn bare_version_is_structured() {
    let output = run(&["--version"]);

    assert!(output.status.success());
    assert!(output.stderr.is_empty());
    let value = stdout_json(&output);
    assert_eq!(value["kind"], "result");
    assert_eq!(value["result"]["code"], "version");
    assert_eq!(value["result"]["name"], "afslug");
    assert_eq!(value["result"]["version"], env!("CARGO_PKG_VERSION"));
}

#[test]
fn short_flags_do_not_exist() {
    // The registry has no short syntax at all, so `-V` is not a rejected alias
    // of `--version` — it is simply not an argument.
    for short in ["-V", "-h"] {
        let output = run(&[short]);

        assert_eq!(output.status.code(), Some(2), "{short} must be rejected");
        assert!(output.stdout.is_empty());
        let value = stderr_json(&output);
        assert_eq!(value["kind"], "error");
        assert_eq!(value["error"]["code"], "cli_unknown_argument");
        assert_eq!(
            value["error"]["message"],
            format!("unknown argument `{short}`")
        );
    }
}

#[test]
fn root_help_routes_to_commands_without_listing_their_arguments() {
    let root = run(&["--help"]);
    assert!(root.status.success());
    assert!(root.stderr.is_empty());
    assert_eq!(stdout_json(&root)["result"]["code"], "help");

    let help = help_of(&root);
    assert_eq!(help["schema"], "cli-help-v2");
    assert_eq!(help["command_path"], "afslug");
    // The root registers no combination, so it has no shape of its own — it is
    // a router, and every entry is a ready-to-run next call.
    assert!(help.get("shapes").is_none(), "{help}");
    assert_eq!(
        help["subcommands"],
        json!([
            "afslug skill --help",
            "afslug slugify --help",
            "afslug validate --help"
        ])
    );
    // `--docs` is injected but deliberately invisible: no agent calls it, and
    // it would cost a line of every discovery response.
    assert!(!help.to_string().contains("--docs"), "{help}");
}

#[test]
fn command_help_answers_in_one_round_trip() {
    let scoped = run(&["slugify", "--help"]);
    assert!(scoped.status.success());
    let help = help_of(&scoped);
    assert_eq!(help["command_path"], "afslug slugify");

    let shapes = help["shapes"].as_array().expect("slugify has one shape");
    assert_eq!(shapes.len(), 1);
    let usage = shapes[0]["usage"].as_str().expect("usage is a string");

    // Every optional argument is in this one answer. A second level could only
    // omit them, leaving a caller that stopped here unable to know they exist.
    for optional in [
        "[--delimiter <CHAR>]",
        "[--no-lowercase]",
        "[--max-chars <N>]",
        "[--fallback <SLUG>]",
    ] {
        assert!(usage.contains(optional), "{optional} missing from {usage}");
    }
    // A closed value set is spelled out, so the legal values are discoverable
    // rather than reachable only by guessing and reading the error.
    assert!(
        usage.contains("[--dots <replace|preserve|preserve-between-digits>]"),
        "{usage}"
    );
    assert_eq!(help["defaults"]["--charset"], "unicode-alphanumeric");
}

#[test]
fn sibling_shapes_each_say_how_they_differ() {
    let help = help_of(&run(&["skill", "install", "--help"]));
    let shapes = help["shapes"].as_array().expect("two shapes");
    assert_eq!(shapes.len(), 2);

    let by_id = |id: &str| {
        shapes
            .iter()
            .find(|shape| shape["id"] == id)
            .unwrap_or_else(|| panic!("missing shape {id}: {help}"))
            .clone()
    };
    let every = by_id("skill-install-every-agent");
    let one = by_id("skill-install-one-agent");
    assert_ne!(every["about"], one["about"]);
    // --skills-dir names a single directory, so it belongs only to the shape
    // that targets a single agent.
    assert!(
        !every["usage"]
            .as_str()
            .unwrap_or_default()
            .contains("--skills-dir"),
        "{every}"
    );
    assert!(
        one["usage"]
            .as_str()
            .unwrap_or_default()
            .contains("[--skills-dir <DIR>]"),
        "{one}"
    );
}

#[test]
fn plain_help_is_not_weaker_than_the_structured_form() {
    let plain = run(&["slugify", "--help", "--output", "plain"]);
    assert!(plain.status.success());
    let text = String::from_utf8(plain.stdout).expect("plain help is UTF-8");

    assert!(text.contains("afslug slugify <TEXT>"), "{text}");
    // Notes and defaults are the two things plain help used to drop.
    assert!(text.contains("Text to slugify"), "{text}");
    assert!(text.contains("--charset=unicode-alphanumeric"), "{text}");
}

#[test]
fn an_unknown_command_names_itself() {
    // `help` was clap's pseudo-command; the registry has no such thing.
    let pseudo = run(&["help"]);
    assert_eq!(pseudo.status.code(), Some(2));
    assert!(pseudo.stdout.is_empty());
    let event = stderr_json(&pseudo);
    assert_eq!(event["error"]["code"], "cli_unknown_command");
    assert_eq!(event["error"]["message"], "unknown command `help`");
    assert_eq!(
        event["error"]["hint"],
        "run `afslug --help` and choose one registered combination"
    );
    assert!(
        pseudo.stderr.len() < 256,
        "an unknown command must not embed eager help"
    );
}

#[test]
fn output_to_is_honored_once_an_invocation_resolves() {
    let resolved = run(&["validate", "bad/slug", "--output-to", "stdout"]);
    assert_eq!(resolved.status.code(), Some(1));
    assert!(resolved.stderr.is_empty());
    assert_eq!(stdout_json(&resolved)["error"]["code"], "slug_error");
}

#[test]
fn a_rejected_invocation_reports_on_the_diagnostic_stream() {
    // `--output-to stdout` is part of the argv that failed to resolve, so there
    // is no output contract to honor yet; the rejection cannot be routed by the
    // request it is rejecting.
    let output = run(&["--output-to", "stdout"]);
    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());
    assert_eq!(stderr_json(&output)["kind"], "error");
}

#[test]
fn docs_render_the_whole_registry_as_markdown() {
    let output = run(&["--docs"]);
    assert!(output.status.success());
    assert!(output.stderr.is_empty());
    let text = String::from_utf8(output.stdout).expect("docs are UTF-8");

    assert!(text.starts_with("# afslug CLI reference"), "{text:.80}");
    for command in ["afslug slugify", "afslug validate", "afslug skill install"] {
        assert!(
            text.contains(command),
            "{command} missing from the reference"
        );
    }
}

#[test]
fn skill_install_bundles_skill_and_agent_asset() {
    let dir = std::env::temp_dir().join(format!("afslug_skill_test_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let dir_str = dir.to_str().expect("temp path is utf-8");
    let target = [
        "--agent",
        "claude-code",
        "--scope",
        "personal",
        "--skills-dir",
        dir_str,
    ];

    let mut install = vec!["skill", "install"];
    install.extend_from_slice(&target);
    install.push("--force");
    let installed = run(&install);
    assert!(
        installed.status.success(),
        "install failed: {}",
        String::from_utf8_lossy(&installed.stderr)
    );
    let skill_dir = dir.join("agent-first-slug");
    assert!(
        skill_dir.join("SKILL.md").is_file(),
        "SKILL.md must install"
    );
    assert!(
        skill_dir.join("agents").join("openai.yaml").is_file(),
        "the bundled agents/openai.yaml asset must install alongside SKILL.md"
    );

    let mut status = vec!["skill", "status"];
    status.extend_from_slice(&target);
    let value = stdout_json(&run(&status));
    assert_eq!(value["result"]["current_all"], json!(true));

    let mut uninstall = vec!["skill", "uninstall"];
    uninstall.extend_from_slice(&target);
    let removed = run(&uninstall);
    assert!(removed.status.success());
    assert!(
        !skill_dir.exists(),
        "uninstall must remove the skill directory"
    );
    let _ = std::fs::remove_dir_all(&dir);
}