ai-memory 0.7.0

AI-agnostic persistent memory system — MCP server, HTTP API, and CLI for any AI platform
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0

//! v0.7.0 Cluster E API-2 (issue #767) — `ai-memory skill <subcommand>`
//! CLI surface.
//!
//! Closes the CLI/HTTP parity gap surfaced by the v0.7.0 6-reviewer audit:
//! the L1-5 Agent Skills substrate landed with seven MCP tools
//! (`memory_skill_*`) but zero CLI subcommands and zero HTTP routes, so
//! HTTP-daemon operators and shell-driven workflows could not interact
//! with skills at all. This module adds the CLI surface; the matching
//! HTTP routes live in `src/handlers/http.rs`.
//!
//! Each subcommand delegates to the **same** substrate handler the MCP
//! dispatch already uses (re-exported as `crate::mcp::handle_skill_*`).
//! No business logic is re-implemented here — the CLI is a clap-shaped
//! thin client over the existing handlers, so MCP / CLI / HTTP share a
//! single source of truth for skill semantics.
//!
//! Verb mapping (CLI → MCP tool name):
//!
//!   * `ai-memory skill register`    → `memory_skill_register`
//!   * `ai-memory skill list`        → `memory_skill_list`
//!   * `ai-memory skill get`         → `memory_skill_get`
//!   * `ai-memory skill resource`    → `memory_skill_resource`
//!   * `ai-memory skill export`      → `memory_skill_export`
//!   * `ai-memory skill promote`     → `memory_skill_promote_from_reflection`
//!   * `ai-memory skill compose`     → `memory_skill_compositional_context`
//!
//! All seven mirror the MCP tool surface 1:1. No new MCP tools land
//! here — the MCP surface stays at whatever
//! `Profile::full().expected_tool_count()` reports (canonical SSOT in
//! `src/profile.rs`; pinned by `profile_full_matches_registry_all`).

use crate::models::field_names;
use std::path::{Path, PathBuf};

use anyhow::Result;
use clap::{Args, Subcommand};
use serde_json::{Value, json};

use crate::cli::CliOutput;
use crate::db;

/// Top-level `ai-memory skill <subcommand>` argument struct.
#[derive(Args, Debug, Clone)]
pub struct SkillArgs {
    #[command(subcommand)]
    pub action: SkillAction,
}

/// `ai-memory skill ...` sub-subcommands. One per MCP `memory_skill_*`
/// tool so the CLI surface is parity-checkable by name.
#[derive(Subcommand, Debug, Clone)]
pub enum SkillAction {
    /// Register a SKILL.md skill from a folder or inline manifest text.
    Register(RegisterArgs),
    /// List current (non-superseded) skills — discovery payload only.
    List(ListArgs),
    /// Fetch the full activation payload for a skill (body included).
    Get(GetArgs),
    /// Fetch the decompressed content of a single skill resource and
    /// verify its SHA-256 digest.
    Resource(ResourceArgs),
    /// Export a skill back to a folder as a round-trip-stable SKILL.md.
    Export(ExportArgs),
    /// Promote a Reflection-kind memory into a reusable Agent Skill.
    Promote(PromoteArgs),
    /// Load a skill body together with the reflections declared in its
    /// `composes_with_reflections` frontmatter list.
    Compose(ComposeArgs),
}

// ---------------------------------------------------------------------------
// Per-verb argument structs
// ---------------------------------------------------------------------------

/// `ai-memory skill register` — accepts EITHER `--manifest <folder-or-file>`
/// OR `--inline <text>`.
#[derive(Args, Debug, Clone)]
pub struct RegisterArgs {
    /// Path to a directory containing `SKILL.md` (and an optional
    /// `resources/` sub-directory), OR a path to a SKILL.md file
    /// directly (the parent directory is then treated as the folder).
    /// Mirrors the MCP `folder_path` parameter.
    #[arg(long, value_name = "PATH")]
    pub manifest: Option<PathBuf>,

    /// Raw SKILL.md text including YAML frontmatter and markdown body.
    /// Mirrors the MCP `inline_skill` parameter. Mutually exclusive
    /// with `--manifest` at the substrate level — passing both surfaces
    /// the substrate's "either / or" error.
    #[arg(long, value_name = "TEXT", conflicts_with = "manifest")]
    pub inline: Option<String>,

    /// Emit a structured JSON envelope instead of a human summary line.
    #[arg(long, default_value_t = false)]
    pub json: bool,
}

/// `ai-memory skill list`
#[derive(Args, Debug, Clone)]
pub struct ListArgs {
    /// Filter to this namespace. Omit (or pass `%`) for all namespaces.
    #[arg(long, value_name = "NS")]
    pub namespace: Option<String>,

    /// Optional substring filter applied to name and description.
    #[arg(long, value_name = "TEXT")]
    pub filter: Option<String>,

    /// Emit a structured JSON envelope instead of a human table.
    #[arg(long, default_value_t = false)]
    pub json: bool,
}

/// `ai-memory skill get`
#[derive(Args, Debug, Clone)]
pub struct GetArgs {
    /// The UUID of the skill to retrieve. Mirrors MCP `skill_id`.
    #[arg(long, value_name = "ID")]
    pub id: String,

    /// Emit a structured JSON envelope; default is a brief summary.
    #[arg(long, default_value_t = false)]
    pub json: bool,
}

/// `ai-memory skill resource`
#[derive(Args, Debug, Clone)]
pub struct ResourceArgs {
    /// The UUID of the parent skill.
    #[arg(long, value_name = "ID")]
    pub id: String,

    /// Relative path of the resource (e.g. `scripts/run.sh`).
    #[arg(long, value_name = "PATH")]
    pub path: String,

    /// Emit a structured JSON envelope.
    #[arg(long, default_value_t = false)]
    pub json: bool,
}

/// `ai-memory skill export`
#[derive(Args, Debug, Clone)]
pub struct ExportArgs {
    /// The UUID of the skill to export.
    #[arg(long, value_name = "ID")]
    pub id: String,

    /// Destination directory. Created if absent. Re-registering the
    /// exported folder via `ai-memory skill register --manifest <dir>`
    /// produces the IDENTICAL SHA-256 digest (round-trip guarantee).
    #[arg(long, value_name = "PATH")]
    pub output: PathBuf,

    /// Emit a structured JSON envelope.
    #[arg(long, default_value_t = false)]
    pub json: bool,
}

/// `ai-memory skill promote`
#[derive(Args, Debug, Clone)]
pub struct PromoteArgs {
    /// The UUID of a Reflection-kind memory (created via `memory_reflect`).
    /// Mirrors MCP `reflection_id`.
    #[arg(long, value_name = "ID")]
    pub id: String,

    /// agentskills.io §3.1-compliant skill name (`^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$`,
    /// 1–64 chars).
    #[arg(long, value_name = "NAME")]
    pub name: String,

    /// 1–1024 char description for the promoted skill.
    #[arg(long, value_name = "TEXT")]
    pub description: String,

    /// Optional path to a JSON file containing the skill's parameters
    /// JSON-schema. Spliced into the SKILL.md body verbatim.
    #[arg(long, value_name = "PATH")]
    pub parameters_schema: Option<PathBuf>,

    /// Emit a structured JSON envelope.
    #[arg(long, default_value_t = false)]
    pub json: bool,
}

/// `ai-memory skill compose`
#[derive(Args, Debug, Clone)]
pub struct ComposeArgs {
    /// The UUID of the skill to load with composed reflections.
    #[arg(long, value_name = "ID")]
    pub id: String,

    /// Optional token cap on the cumulative reflection content (skill
    /// body is NOT counted). Default 4000 inside the substrate; hard-
    /// clamped to 32000.
    #[arg(long, value_name = "N")]
    pub budget_tokens: Option<u64>,

    /// Emit a structured JSON envelope (default).
    #[arg(long, default_value_t = true)]
    pub json: bool,
}

// ---------------------------------------------------------------------------
// Dispatch
// ---------------------------------------------------------------------------

/// Dispatch entry-point called from `daemon_runtime::run`.
///
/// Loads the active keypair (when configured) so register / export /
/// promote can sign their output, matching the MCP-side wiring.
///
/// # Errors
///
/// Surfaces DB-open errors verbatim. Substrate-handler failures bubble
/// up as exit codes (non-zero) with the substrate's error string
/// printed to stderr.
pub fn run(
    db_path: &Path,
    args: &SkillArgs,
    active_keypair: Option<&crate::identity::keypair::AgentKeypair>,
    out: &mut CliOutput<'_>,
) -> Result<i32> {
    let conn = db::open(db_path)?;
    match &args.action {
        SkillAction::Register(a) => run_register(&conn, a, active_keypair, out),
        SkillAction::List(a) => run_list(&conn, a, out),
        SkillAction::Get(a) => run_get(&conn, a, out),
        SkillAction::Resource(a) => run_resource(&conn, a, out),
        SkillAction::Export(a) => run_export(&conn, a, active_keypair, out),
        SkillAction::Promote(a) => run_promote(&conn, a, active_keypair, out),
        SkillAction::Compose(a) => run_compose(&conn, a, out),
    }
}

fn handler_err_exit(out: &mut CliOutput<'_>, verb: &str, e: &str) -> Result<i32> {
    writeln!(out.stderr, "ai-memory skill {verb}: {e}")?;
    Ok(2)
}

fn emit_json(out: &mut CliOutput<'_>, v: &Value) -> Result<()> {
    let s = serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string());
    writeln!(out.stdout, "{s}")?;
    Ok(())
}

// ---------------------------------------------------------------------------
// register
// ---------------------------------------------------------------------------

fn run_register(
    conn: &rusqlite::Connection,
    args: &RegisterArgs,
    active_keypair: Option<&crate::identity::keypair::AgentKeypair>,
    out: &mut CliOutput<'_>,
) -> Result<i32> {
    // Normalise --manifest: accept either a directory OR a SKILL.md
    // file path (in which case we hand the substrate the parent dir).
    let folder_path: Option<String> = args.manifest.as_ref().map(|p| {
        if p.is_file() {
            p.parent().map_or_else(
                || p.to_string_lossy().into_owned(),
                |d| d.to_string_lossy().into_owned(),
            )
        } else {
            p.to_string_lossy().into_owned()
        }
    });

    let mut params = json!({});
    if let Some(ref fp) = folder_path {
        params["folder_path"] = json!(fp);
    }
    if let Some(ref inl) = args.inline {
        params["inline_skill"] = json!(inl);
    }

    match crate::mcp::handle_skill_register(conn, &params, active_keypair) {
        Ok(v) => {
            if args.json {
                emit_json(out, &v)?;
            } else {
                let id = v["id"].as_str().unwrap_or("");
                let ns = v["namespace"].as_str().unwrap_or("");
                let name = v["name"].as_str().unwrap_or("");
                let digest = v["digest"].as_str().unwrap_or("");
                let signed = v["signed"].as_bool().unwrap_or(false);
                writeln!(
                    out.stdout,
                    "registered skill {ns}/{name} id={id} digest={} signed={signed}",
                    &digest[..digest.len().min(16)],
                )?;
                if let Some(prev) = v.get(field_names::SUPERSEDED_ID).and_then(Value::as_str) {
                    writeln!(out.stdout, "  superseded previous id={prev}")?;
                }
            }
            Ok(0)
        }
        Err(e) => handler_err_exit(out, "register", &e),
    }
}

// ---------------------------------------------------------------------------
// list
// ---------------------------------------------------------------------------

fn run_list(conn: &rusqlite::Connection, args: &ListArgs, out: &mut CliOutput<'_>) -> Result<i32> {
    let mut params = json!({});
    if let Some(ref ns) = args.namespace {
        params["namespace"] = json!(ns);
    }
    if let Some(ref f) = args.filter {
        params["filter"] = json!(f);
    }
    match crate::mcp::handle_skill_list(conn, &params) {
        Ok(v) => {
            if args.json {
                emit_json(out, &v)?;
            } else {
                let empty: Vec<Value> = Vec::new();
                let arr = v["skills"].as_array().unwrap_or(&empty);
                writeln!(out.stdout, "{} skills", arr.len())?;
                for s in arr {
                    let ns = s["namespace"].as_str().unwrap_or("");
                    let name = s["name"].as_str().unwrap_or("");
                    let id = s["id"].as_str().unwrap_or("");
                    let desc = s[field_names::DESCRIPTION].as_str().unwrap_or("");
                    writeln!(out.stdout, "  {ns}/{name} ({id})\n    {desc}")?;
                }
            }
            Ok(0)
        }
        Err(e) => handler_err_exit(out, "list", &e),
    }
}

// ---------------------------------------------------------------------------
// get
// ---------------------------------------------------------------------------

fn run_get(conn: &rusqlite::Connection, args: &GetArgs, out: &mut CliOutput<'_>) -> Result<i32> {
    let params = json!({ "skill_id": args.id });
    match crate::mcp::handle_skill_get(conn, &params) {
        Ok(v) => {
            if args.json {
                emit_json(out, &v)?;
            } else {
                let ns = v["namespace"].as_str().unwrap_or("");
                let name = v["name"].as_str().unwrap_or("");
                let body = v["body"].as_str().unwrap_or("");
                writeln!(out.stdout, "# {ns}/{name}\n\n{body}")?;
            }
            Ok(0)
        }
        Err(e) => handler_err_exit(out, "get", &e),
    }
}

// ---------------------------------------------------------------------------
// resource
// ---------------------------------------------------------------------------

fn run_resource(
    conn: &rusqlite::Connection,
    args: &ResourceArgs,
    out: &mut CliOutput<'_>,
) -> Result<i32> {
    let params = json!({
        "skill_id": args.id,
        (field_names::RESOURCE_PATH): args.path,
    });
    match crate::mcp::handle_skill_resource(conn, &params) {
        Ok(v) => {
            if args.json {
                emit_json(out, &v)?;
            } else if let Some(content) = v["content"].as_str() {
                writeln!(out.stdout, "{content}")?;
            } else {
                emit_json(out, &v)?;
            }
            Ok(0)
        }
        Err(e) => handler_err_exit(out, "resource", &e),
    }
}

// ---------------------------------------------------------------------------
// export
// ---------------------------------------------------------------------------

fn run_export(
    conn: &rusqlite::Connection,
    args: &ExportArgs,
    active_keypair: Option<&crate::identity::keypair::AgentKeypair>,
    out: &mut CliOutput<'_>,
) -> Result<i32> {
    let params = json!({
        "skill_id": args.id,
        (field_names::TARGET_FOLDER): args.output.to_string_lossy(),
    });
    match crate::mcp::handle_skill_export(conn, &params, active_keypair) {
        Ok(v) => {
            if args.json {
                emit_json(out, &v)?;
            } else {
                let fallback_folder = args.output.to_string_lossy();
                let folder = v[field_names::TARGET_FOLDER]
                    .as_str()
                    .unwrap_or(&fallback_folder);
                writeln!(out.stdout, "exported skill {}{folder}", args.id)?;
            }
            Ok(0)
        }
        Err(e) => handler_err_exit(out, "export", &e),
    }
}

// ---------------------------------------------------------------------------
// promote
// ---------------------------------------------------------------------------

fn run_promote(
    conn: &rusqlite::Connection,
    args: &PromoteArgs,
    active_keypair: Option<&crate::identity::keypair::AgentKeypair>,
    out: &mut CliOutput<'_>,
) -> Result<i32> {
    let mut params = json!({
        (field_names::REFLECTION_ID): args.id,
        (field_names::SKILL_NAME): args.name,
        (field_names::SKILL_DESCRIPTION): args.description,
    });
    if let Some(ref p) = args.parameters_schema {
        let raw = std::fs::read_to_string(p)
            .map_err(|e| anyhow::anyhow!("read parameters_schema {}: {e}", p.display()))?;
        let v: Value = serde_json::from_str(&raw)
            .map_err(|e| anyhow::anyhow!("parse parameters_schema {}: {e}", p.display()))?;
        params[field_names::PARAMETERS_SCHEMA] = v;
    }
    match crate::mcp::handle_skill_promote_from_reflection(conn, &params, active_keypair) {
        Ok(v) => {
            if args.json {
                emit_json(out, &v)?;
            } else {
                let id = v["skill_id"]
                    .as_str()
                    .or_else(|| v["id"].as_str())
                    .unwrap_or("");
                writeln!(out.stdout, "promoted reflection {} → skill {id}", args.id)?;
            }
            Ok(0)
        }
        Err(e) => handler_err_exit(out, "promote", &e),
    }
}

// ---------------------------------------------------------------------------
// compose
// ---------------------------------------------------------------------------

fn run_compose(
    conn: &rusqlite::Connection,
    args: &ComposeArgs,
    out: &mut CliOutput<'_>,
) -> Result<i32> {
    let mut params = json!({ "skill_id": args.id });
    if let Some(b) = args.budget_tokens {
        params[field_names::BUDGET_TOKENS] = json!(b);
    }
    match crate::mcp::handle_skill_compositional_context(conn, &params) {
        Ok(v) => {
            emit_json(out, &v)?;
            Ok(0)
        }
        Err(e) => handler_err_exit(out, "compose", &e),
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::drop_non_drop)] // explicit borrow-release of CliOutput; see file-level note above.
mod tests {
    use super::*;
    use crate::cli::CliOutput;
    use tempfile::TempDir;

    fn fresh_db() -> (TempDir, PathBuf) {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("ai-memory.db");
        let _conn = db::open(&path).unwrap();
        (dir, path)
    }

    fn minimal_skill_md(name: &str) -> String {
        format!("---\nnamespace: testns\nname: {name}\ndescription: A demo skill.\n---\n\nBody.\n")
    }

    #[test]
    fn cli_skill_register_inline_smoke() {
        let (_dir, db_path) = fresh_db();
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Register(RegisterArgs {
                manifest: None,
                inline: Some(minimal_skill_md("cli-register")),
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        drop(out);
        let text = String::from_utf8(stdout).unwrap();
        assert!(text.contains("\"registered\""));
        assert!(text.contains("cli-register"));
    }

    #[test]
    fn cli_skill_list_smoke() {
        let (_dir, db_path) = fresh_db();
        // Seed a skill via the register handler so list has something to find.
        let conn = db::open(&db_path).unwrap();
        let _ = crate::mcp::handle_skill_register(
            &conn,
            &json!({"inline_skill": minimal_skill_md("cli-list")}),
            None,
        )
        .unwrap();
        drop(conn);

        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::List(ListArgs {
                namespace: Some("testns".to_string()),
                filter: None,
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        drop(out);
        let text = String::from_utf8(stdout).unwrap();
        assert!(text.contains("cli-list"));
    }

    #[test]
    fn cli_skill_get_smoke() {
        let (_dir, db_path) = fresh_db();
        let conn = db::open(&db_path).unwrap();
        let reg = crate::mcp::handle_skill_register(
            &conn,
            &json!({"inline_skill": minimal_skill_md("cli-get")}),
            None,
        )
        .unwrap();
        let id = reg["id"].as_str().unwrap().to_string();
        drop(conn);

        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Get(GetArgs {
                id: id.clone(),
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        drop(out);
        let text = String::from_utf8(stdout).unwrap();
        assert!(text.contains(&id));
        assert!(text.contains("cli-get"));
    }

    #[test]
    fn cli_skill_export_smoke() {
        let (dir, db_path) = fresh_db();
        let conn = db::open(&db_path).unwrap();
        let reg = crate::mcp::handle_skill_register(
            &conn,
            &json!({"inline_skill": minimal_skill_md("cli-export")}),
            None,
        )
        .unwrap();
        let id = reg["id"].as_str().unwrap().to_string();
        drop(conn);

        let target = dir.path().join("export-out");

        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Export(ExportArgs {
                id: id.clone(),
                output: target.clone(),
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        // SKILL.md must exist in the output folder.
        assert!(target.join("SKILL.md").exists());
    }

    #[test]
    fn cli_skill_get_missing_id_exits_nonzero() {
        let (_dir, db_path) = fresh_db();
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Get(GetArgs {
                id: "no-such-skill".to_string(),
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 2);
        drop(out);
        let err = String::from_utf8(stderr).unwrap();
        assert!(err.contains(crate::errors::msg::SKILL_NOT_FOUND));
    }

    #[test]
    fn cli_skill_compose_smoke() {
        let (_dir, db_path) = fresh_db();
        let conn = db::open(&db_path).unwrap();
        let reg = crate::mcp::handle_skill_register(
            &conn,
            &json!({"inline_skill": minimal_skill_md("cli-compose")}),
            None,
        )
        .unwrap();
        let id = reg["id"].as_str().unwrap().to_string();
        drop(conn);

        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Compose(ComposeArgs {
                id: id.clone(),
                budget_tokens: Some(1000),
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        drop(out);
        let text = String::from_utf8(stdout).unwrap();
        // A skill with no `composes_with_reflections` declaration still
        // returns body and an empty reflections list — pin that.
        assert!(text.contains(&id) || text.contains("\"body\""));
    }

    // ------------------------------------------------------------------
    // Coverage-uplift block (2026-05-19): exercise the non-JSON (human-
    // render) paths for every skill verb so the `if args.json { ... }
    // else { ... writeln!(...) }` else-arms are not dead from a test-
    // coverage standpoint.
    // ------------------------------------------------------------------

    #[test]
    fn cli_skill_register_human_render_emits_summary_line() {
        let (_dir, db_path) = fresh_db();
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Register(RegisterArgs {
                manifest: None,
                inline: Some(minimal_skill_md("cli-register-human")),
                json: false,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        drop(out);
        let text = String::from_utf8(stdout).unwrap();
        // The human-render path emits "registered skill {ns}/{name} ..."
        assert!(
            text.starts_with("registered skill "),
            "expected human-render summary line, got: {text}"
        );
        assert!(text.contains("cli-register-human"));
        assert!(text.contains("digest="));
        assert!(text.contains("signed="));
    }

    #[test]
    fn cli_skill_list_human_render_emits_table() {
        let (_dir, db_path) = fresh_db();
        let conn = db::open(&db_path).unwrap();
        let _ = crate::mcp::handle_skill_register(
            &conn,
            &json!({"inline_skill": minimal_skill_md("cli-list-human")}),
            None,
        )
        .unwrap();
        drop(conn);

        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::List(ListArgs {
                namespace: Some("testns".to_string()),
                filter: Some("cli-list-human".to_string()),
                json: false,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        drop(out);
        let text = String::from_utf8(stdout).unwrap();
        // Human render prints "{N} skills" + per-skill indented lines.
        assert!(
            text.contains(" skills"),
            "expected count header, got: {text}"
        );
        assert!(text.contains("cli-list-human"));
    }

    #[test]
    fn cli_skill_get_human_render_emits_markdown_header_and_body() {
        let (_dir, db_path) = fresh_db();
        let conn = db::open(&db_path).unwrap();
        let reg = crate::mcp::handle_skill_register(
            &conn,
            &json!({"inline_skill": minimal_skill_md("cli-get-human")}),
            None,
        )
        .unwrap();
        let id = reg["id"].as_str().unwrap().to_string();
        drop(conn);

        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Get(GetArgs { id, json: false }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        drop(out);
        let text = String::from_utf8(stdout).unwrap();
        // Human render prints "# {ns}/{name}\n\n{body}"
        assert!(text.starts_with("# testns/cli-get-human"));
        assert!(text.contains("Body."));
    }

    #[test]
    fn cli_skill_export_human_render_emits_path_line() {
        let (dir, db_path) = fresh_db();
        let conn = db::open(&db_path).unwrap();
        let reg = crate::mcp::handle_skill_register(
            &conn,
            &json!({"inline_skill": minimal_skill_md("cli-export-human")}),
            None,
        )
        .unwrap();
        let id = reg["id"].as_str().unwrap().to_string();
        drop(conn);

        let target = dir.path().join("export-human-out");
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Export(ExportArgs {
                id: id.clone(),
                output: target.clone(),
                json: false,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        assert!(target.join("SKILL.md").exists());
        drop(out);
        let text = String::from_utf8(stdout).unwrap();
        // Human render prints "exported skill {id} → {folder}"
        assert!(text.starts_with("exported skill "));
        assert!(text.contains(&id));
    }

    #[test]
    fn cli_skill_register_handler_error_writes_to_stderr_and_returns_2() {
        let (_dir, db_path) = fresh_db();
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        // Pass neither --manifest nor --inline — substrate returns the
        // "either/or" error string. Exits 2 with stderr text.
        let args = SkillArgs {
            action: SkillAction::Register(RegisterArgs {
                manifest: None,
                inline: None,
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 2);
        drop(out);
        let err = String::from_utf8(stderr).unwrap();
        assert!(
            err.starts_with("ai-memory skill register:"),
            "expected stderr prefix, got: {err}"
        );
    }

    #[test]
    fn cli_skill_resource_returns_2_on_missing_skill() {
        let (_dir, db_path) = fresh_db();
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Resource(ResourceArgs {
                id: "no-such-skill-id".to_string(),
                path: "doesnt-matter.txt".to_string(),
                json: false,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 2);
        drop(out);
        let err = String::from_utf8(stderr).unwrap();
        assert!(err.starts_with("ai-memory skill resource:"));
    }

    #[test]
    fn cli_skill_promote_returns_2_on_missing_reflection() {
        let (_dir, db_path) = fresh_db();
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Promote(PromoteArgs {
                id: "no-such-reflection".to_string(),
                name: "demo-skill".to_string(),
                description: "Promoted from missing reflection.".to_string(),
                parameters_schema: None,
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 2);
        drop(out);
        let err = String::from_utf8(stderr).unwrap();
        assert!(err.starts_with("ai-memory skill promote:"));
    }

    #[test]
    fn cli_skill_compose_returns_2_on_missing_skill() {
        let (_dir, db_path) = fresh_db();
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Compose(ComposeArgs {
                id: "no-such-skill".to_string(),
                budget_tokens: None,
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 2);
        drop(out);
        let err = String::from_utf8(stderr).unwrap();
        assert!(err.starts_with("ai-memory skill compose:"));
    }

    #[test]
    fn cli_skill_register_manifest_file_path_normalised_to_parent_dir() {
        // The run_register branch at lines 260-269: if --manifest points
        // to a FILE (not a directory), the parent dir is handed to the
        // substrate. Build a real folder with SKILL.md and pass the file
        // path to exercise the is_file() → parent-dir branch.
        let (dir, db_path) = fresh_db();
        let folder = dir.path().join("skill-folder");
        std::fs::create_dir_all(&folder).unwrap();
        std::fs::write(
            folder.join("SKILL.md"),
            minimal_skill_md("cli-manifest-file"),
        )
        .unwrap();

        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let args = SkillArgs {
            action: SkillAction::Register(RegisterArgs {
                manifest: Some(folder.join("SKILL.md")),
                inline: None,
                json: true,
            }),
        };
        let code = run(&db_path, &args, None, &mut out).unwrap();
        assert_eq!(code, 0);
        drop(out);
        let text = String::from_utf8(stdout).unwrap();
        assert!(text.contains("cli-manifest-file"));
    }
}