sxmc 1.0.9

Sumac: bring out what your tools can do — bridge skills, MCP, and APIs into reusable agent, terminal, and automation workflows
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
use std::path::Path;

use serde_json::json;

use crate::cli_surfaces::model::{
    host_profile_spec, AiClientProfile, CliSurfaceProfile, CLI_AI_HOSTS_LAST_VERIFIED,
};

pub(crate) fn slugify(input: &str) -> String {
    let mut slug = String::new();
    let mut previous_dash = false;
    for ch in input.chars() {
        let mapped = if ch.is_ascii_alphanumeric() {
            previous_dash = false;
            ch.to_ascii_lowercase()
        } else {
            if previous_dash {
                continue;
            }
            previous_dash = true;
            '-'
        };
        slug.push(mapped);
    }
    slug.trim_matches('-').to_string()
}

pub(crate) fn render_agent_doc(profile: &CliSurfaceProfile, client: AiClientProfile) -> String {
    let spec = host_profile_spec(client);
    let mut lines = vec![
        format!("## sxmc CLI Surface: `{}`", profile.command),
        String::new(),
        format!(
            "Use `{}` as a first-class terminal workflow in this repo for {}.",
            profile.command, spec.label
        ),
        String::new(),
        format!("Summary: {}", profile.summary),
    ];

    if let Some(description) = &profile.description {
        lines.push(String::new());
        lines.push(description.clone());
    }

    if !profile.examples.is_empty() {
        lines.push(String::new());
        lines.push("Preferred flow:".into());
        for (index, example) in profile.examples.iter().take(3).enumerate() {
            lines.push(format!("{}. `{}`", index + 1, example.command));
        }
    } else {
        lines.push(String::new());
        lines.push("Preferred flow:".into());
        lines.push(format!("1. `{} --help`", profile.command));
        if let Some(subcommand) = profile.subcommands.first() {
            lines.push(format!(
                "2. `{} {}` --help",
                profile.command, subcommand.name
            ));
        }
    }

    push_subcommand_block(&mut lines, profile, 8, "Key subcommands");

    if !profile.environment.is_empty() {
        lines.push(String::new());
        lines.push("Environment/auth notes:".into());
        for env in &profile.environment {
            lines.push(format!(
                "- `{}`{}",
                env.name,
                env.summary
                    .as_ref()
                    .map(|summary| format!(": {}", summary))
                    .unwrap_or_default()
            ));
        }
    }

    lines.push(String::new());
    lines.push("Guidance:".into());
    lines.push(
        "- When the exact CLI surface is unclear, start with `sxmc inspect cli <tool> --depth 1 --format json-pretty` instead of pasting raw help output into chat."
            .into(),
    );
    lines.push(
        "- If the CLI has nested command groups, re-run with `--depth 2` to inspect deeper help without manually drilling into each branch."
            .into(),
    );
    lines.push(
        "- When the MCP surface is unknown, start with `sxmc stdio \"<cmd>\" --list` or `sxmc mcp grep <pattern>` before guessing tool calls."
            .into(),
    );
    lines.push(
        "- When the API surface is unknown, start with `sxmc api <url-or-spec> --list` before constructing requests by hand."
            .into(),
    );
    lines.push("- Keep bulky output in files or pipes when possible.".into());
    lines.push("- Prefer machine-friendly flags like `--json` when the CLI supports them.".into());
    lines.push("- Re-check `--help` before using low-confidence flows.".into());
    lines.push(format!(
        "- Startup file convention last verified against official docs on {}.",
        CLI_AI_HOSTS_LAST_VERIFIED
    ));
    lines.push(format!("- Reference: {}", spec.official_reference_url));

    lines.join("\n")
}

pub(crate) fn render_portable_agent_doc(profile: &CliSurfaceProfile) -> String {
    let mut lines = vec![
        format!("## sxmc CLI Surface: `{}`", profile.command),
        String::new(),
        format!(
            "Use `{}` as a portable terminal workflow across AI tools in this repo.",
            profile.command
        ),
        String::new(),
        format!("Summary: {}", profile.summary),
    ];

    if let Some(description) = &profile.description {
        lines.push(String::new());
        lines.push(description.clone());
    }

    lines.push(String::new());
    lines.push("Recommended startup guidance:".into());
    lines.push(
        "- When the exact CLI surface is unclear, start with `sxmc inspect cli <tool> --depth 1 --format json-pretty`."
            .into(),
    );
    lines.push(
        "- For multi-layer CLIs, bump inspection to `--depth 2` before writing detailed agent guidance."
            .into(),
    );
    lines.push(format!(
        "- For this CLI specifically, `{}` `--help` is still a good follow-up once you know you are on the right command.",
        profile.command
    ));
    lines.push(
        "- When the MCP surface is unknown, start with `sxmc stdio \"<cmd>\" --list` or `sxmc mcp grep <pattern>`."
            .into(),
    );
    lines.push(
        "- When the API surface is unknown, start with `sxmc api <url-or-spec> --list`.".into(),
    );
    lines.push("- Prefer machine-friendly flags like `--json` when available.".into());
    lines.push(
        "- Keep bulky output in files or pipes instead of pasting it into chat context.".into(),
    );
    lines.push("- Re-check auth or environment requirements before write actions.".into());
    lines.push(format!(
        "- Host profile conventions in this repo were last verified on {}.",
        CLI_AI_HOSTS_LAST_VERIFIED
    ));

    if !profile.examples.is_empty() {
        lines.push(String::new());
        lines.push("Preferred commands:".into());
        for example in profile.examples.iter().take(4) {
            lines.push(format!("- `{}`", example.command));
        }
    }

    push_subcommand_block(&mut lines, profile, 8, "Key subcommands");

    lines.join("\n")
}

pub(crate) fn render_llms_txt(profile: &CliSurfaceProfile) -> String {
    let mut lines = vec![
        format!("# {}", profile.command),
        String::new(),
        profile.summary.clone(),
    ];

    if let Some(description) = &profile.description {
        lines.push(String::new());
        lines.push(description.clone());
    }

    if !profile.examples.is_empty() {
        lines.push(String::new());
        lines.push("## Recommended Commands".into());
        for example in profile.examples.iter().take(5) {
            lines.push(format!("- `{}`", example.command));
        }
    }

    push_subcommand_block(&mut lines, profile, 12, "## Key Subcommands");

    if !profile.environment.is_empty() {
        lines.push(String::new());
        lines.push("## Environment".into());
        for env in &profile.environment {
            lines.push(format!("- `{}`", env.name));
        }
    }

    lines.push(String::new());
    lines.push("## Notes".into());
    lines.push("- Generated by `sxmc scaffold llms-txt` from a CLI surface profile.".into());
    lines.push("- Review before publishing as project-facing LLM guidance.".into());
    lines.push(format!(
        "- Host profile conventions referenced by this repo were last verified on {}.",
        CLI_AI_HOSTS_LAST_VERIFIED
    ));

    lines.join("\n")
}

pub(crate) fn render_ci_workflow(profile: &CliSurfaceProfile) -> String {
    let slug = slugify(&profile.command);
    let profile_path = format!(".sxmc/ai/profiles/{slug}.json");
    format!(
        r#"name: sxmc drift ({command})

on:
  pull_request:
  workflow_dispatch:

jobs:
  cli-drift:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Install sxmc
        run: cargo install --locked sxmc

      - name: Summarize CLI drift
        run: |
          sxmc inspect diff {command} \
            --before {profile_path} \
            --format markdown | tee -a "$GITHUB_STEP_SUMMARY"

      - name: Fail on unexpected CLI drift
        run: |
          sxmc inspect diff {command} \
            --before {profile_path} \
            --exit-code \
            --format json-pretty >/dev/null

      - name: Snapshot status
        run: sxmc status --format json-pretty
"#,
        command = profile.command,
        profile_path = profile_path,
    )
}

pub(crate) fn render_client_config(
    client: AiClientProfile,
    server_name: &str,
    skills_path: &Path,
) -> String {
    let skills_display = skills_path.display().to_string();
    match client {
        AiClientProfile::OpenaiCodex => format!(
            "# sxmc CLI->AI startup scaffold\n[mcp_servers.{server_name}]\ncommand = \"sxmc\"\nargs = [\"serve\", \"--paths\", \"{skills_display}\"]\n"
        ),
        AiClientProfile::GenericHttpMcp => serde_json::to_string_pretty(&json!({
            "mcpServers": {
                server_name: {
                    "url": "http://127.0.0.1:8000/mcp"
                }
            }
        }))
        .unwrap(),
        AiClientProfile::Cursor => serde_json::to_string_pretty(&json!({
            "mcpServers": {
                server_name: {
                    "type": "stdio",
                    "command": "sxmc",
                    "args": ["serve", "--paths", skills_display]
                }
            }
        }))
        .unwrap(),
        AiClientProfile::GeminiCli => serde_json::to_string_pretty(&json!({
            "mcpServers": {
                server_name: {
                    "command": "sxmc",
                    "args": ["serve", "--paths", skills_display]
                }
            }
        }))
        .unwrap(),
        AiClientProfile::OpenCode => serde_json::to_string_pretty(&json!({
            "mcp": {
                server_name: {
                    "type": "local",
                    "command": ["sxmc", "serve", "--paths", skills_display]
                }
            }
        }))
        .unwrap(),
        _ => serde_json::to_string_pretty(&json!({
            "mcpServers": {
                server_name: {
                    "command": "sxmc",
                    "args": ["serve", "--paths", skills_display]
                }
            }
        }))
        .unwrap(),
    }
}

pub(crate) fn render_skill_markdown(profile: &CliSurfaceProfile) -> String {
    let name = format!("{}-cli", slugify(&profile.command));
    let description = profile
        .description
        .as_deref()
        .unwrap_or(&profile.summary)
        .replace('"', "'");
    let argument_hint = profile
        .positionals
        .iter()
        .map(|positional| format!("<{}>", positional.name))
        .chain(
            profile
                .options
                .iter()
                .take(3)
                .map(|option| option.name.clone()),
        )
        .collect::<Vec<_>>()
        .join(" ");

    let mut body = vec![
        "---".to_string(),
        format!("name: {}", name),
        format!("description: \"{}\"", description),
    ];
    if !argument_hint.trim().is_empty() {
        body.push(format!("argument-hint: \"{}\"", argument_hint));
    }
    body.push("---".to_string());
    body.push(String::new());
    body.push(format!("# {} CLI workflow", profile.command));
    body.push(String::new());
    body.push(profile.summary.clone());

    if let Some(description) = &profile.description {
        body.push(String::new());
        body.push(description.clone());
    }

    if !profile.examples.is_empty() {
        body.push(String::new());
        body.push("Recommended commands:".into());
        for example in profile.examples.iter().take(5) {
            body.push(format!("- `{}`", example.command));
        }
    }

    push_subcommand_block(&mut body, profile, 10, "Key subcommands");

    body.push(String::new());
    body.push("Execution guidance:".into());
    body.push(format!(
        "- Start with `{}` `--help` if the exact shape is unclear.",
        profile.command
    ));
    body.push("- Prefer machine-friendly flags like `--json` when available.".into());
    body.push("- Keep large output in files or pipes instead of pasting it into context.".into());
    body.push(
        "- Re-check auth or environment requirements before performing write actions.".into(),
    );
    body.push(String::new());
    body.push(
        "This file was generated by `sxmc scaffold skill` from a CLI profile and should be reviewed before wider use."
            .into(),
    );
    body.join("\n")
}

pub(crate) fn render_mcp_wrapper_readme(profile: &CliSurfaceProfile) -> String {
    let slug = slugify(&profile.command);
    let mut lines = vec![
        format!("# {} MCP wrapper scaffold", profile.command),
        String::new(),
        "This scaffold is a starting point for wrapping a CLI as a focused MCP server.".into(),
        String::new(),
        "Recommended approach:".into(),
        format!(
            "- Start from the `{}` CLI profile rather than mirroring the whole CLI.",
            slug
        ),
        "- Expose a few narrow tools first.".into(),
        "- Keep outputs machine-friendly and bounded.".into(),
        "- Treat prompts/resources as optional depending on the CLI.".into(),
    ];

    if !profile.subcommands.is_empty() {
        lines.push(String::new());
        lines.push("Candidate tool surfaces:".into());
        for subcommand in profile.subcommands.iter().take(5) {
            lines.push(format!("- `{}`: {}", subcommand.name, subcommand.summary));
        }
        if profile.subcommands.len() > 5 {
            lines.push(format!(
                "- ... plus {} more discovered subcommands in the inspected profile.",
                profile.subcommands.len() - 5
            ));
        }
    }

    if !profile.examples.is_empty() {
        lines.push(String::new());
        lines.push("Examples to preserve in wrapper behavior:".into());
        for example in profile.examples.iter().take(5) {
            lines.push(format!("- `{}`", example.command));
        }
    }

    lines.push(String::new());
    lines.push("Files:".into());
    lines.push(
        "- `manifest.json` captures the inspected profile details and suggested wrapper shape."
            .into(),
    );
    lines.push(
        "- Add server code, tests, and launch scripts beside this scaffold as needed.".into(),
    );
    lines.join("\n")
}

fn push_subcommand_block(
    lines: &mut Vec<String>,
    profile: &CliSurfaceProfile,
    limit: usize,
    heading: &str,
) {
    if profile.subcommands.is_empty() {
        return;
    }

    let total = profile.subcommands.len();
    let shown = total.min(limit);
    lines.push(String::new());
    lines.push(format!("{heading} (showing {shown} of {total}):"));
    for subcommand in profile.subcommands.iter().take(limit) {
        lines.push(format!("- `{}`: {}", subcommand.name, subcommand.summary));
    }
    if total > limit {
        lines.push(format!(
            "- ... plus {} more discovered subcommands in the inspected profile.",
            total - limit
        ));
    }
}

#[cfg(test)]
mod tests {
    use super::{push_subcommand_block, render_skill_markdown};
    use crate::cli_surfaces::model::{
        CliSurfaceProfile, ConfidenceLevel, OutputBehavior, ProfileSource, ProfileSubcommand,
        Provenance, PROFILE_SCHEMA,
    };

    fn demo_profile_with_subcommands(count: usize) -> CliSurfaceProfile {
        CliSurfaceProfile {
            profile_schema: PROFILE_SCHEMA.into(),
            command: "demo".into(),
            summary: "Demo CLI summary.".into(),
            description: Some("Demo CLI description.".into()),
            source: ProfileSource {
                kind: "cli".into(),
                identifier: "demo".into(),
            },
            subcommands: (0..count)
                .map(|index| ProfileSubcommand {
                    name: format!("cmd-{index}"),
                    summary: format!("Command {index}."),
                    interactive: false,
                    interactive_reasons: Vec::new(),
                    non_interactive_alternatives: Vec::new(),
                    confidence: ConfidenceLevel::Medium,
                })
                .collect(),
            subcommand_profiles: Vec::new(),
            options: Vec::new(),
            positionals: Vec::new(),
            examples: Vec::new(),
            auth: Vec::new(),
            environment: Vec::new(),
            output_behavior: OutputBehavior {
                stdout_style: "plain_text".into(),
                stderr_usage: "unknown".into(),
                machine_friendly: false,
            },
            workflows: Vec::new(),
            interactive: false,
            interactive_reasons: Vec::new(),
            non_interactive_alternatives: Vec::new(),
            confidence_notes: Vec::new(),
            provenance: Provenance {
                generated_by: "sxmc".into(),
                generator_version: env!("CARGO_PKG_VERSION").into(),
                source_kind: "cli".into(),
                source_identifier: "demo".into(),
                profile_schema: PROFILE_SCHEMA.into(),
                generation_depth: 0,
                generated_at: "unix:0".into(),
            },
        }
    }

    #[test]
    fn push_subcommand_block_reports_total_and_overflow() {
        let profile = demo_profile_with_subcommands(12);
        let mut lines = Vec::new();
        push_subcommand_block(&mut lines, &profile, 5, "Key subcommands");
        let rendered = lines.join("\n");
        assert!(rendered.contains("Key subcommands (showing 5 of 12):"));
        assert!(rendered.contains("plus 7 more discovered subcommands"));
    }

    #[test]
    fn render_skill_markdown_surfaces_more_than_five_subcommands() {
        let profile = demo_profile_with_subcommands(14);
        let rendered = render_skill_markdown(&profile);
        assert!(rendered.contains("Key subcommands (showing 10 of 14):"));
        assert!(rendered.contains("plus 4 more discovered subcommands"));
    }
}