kazam 1.28.1

Local infrastructure for coding agents: context, visibility, durable execution. One Rust binary, no cloud.
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
use anyhow::Result;
use clap::{Parser, Subcommand};
use std::path::PathBuf;

mod actions;
mod agents;
mod agl;
mod annotations;
mod audit;
mod board;
mod build;
mod cli_reference;
mod connect;
mod ctx;
mod dev;
mod export;
mod freshness;
mod http;
mod icons;
mod id;
mod ingest;
mod init;
mod install;
mod links;
mod llms;
mod manifest;
mod mcp;
mod minify;
mod open;
mod packhook;
mod prompts;
mod render;
mod sdk;
mod search;
mod server;
mod shape;
mod show;
mod theme;
mod track;
mod types;
mod validate;
mod voice;
mod wish;
mod workspace;

#[derive(Parser)]
#[command(
    name = "kazam",
    about = "Local infrastructure for coding agents: context, visibility, durable execution",
    version
)]
pub struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Build a site from a directory of .yaml files
    Build {
        /// Directory of .yaml source files
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// Output directory for the built site
        #[arg(short, long, default_value = "_site")]
        out: PathBuf,
        /// Minify HTML, CSS, and JS in the output
        #[arg(short, long)]
        release: bool,
        /// Silence the orphan-page check (broken links still reported).
        /// Useful for draft pages you haven't wired into nav yet.
        #[arg(long)]
        allow_orphans: bool,
        /// Emit structured NDJSON instead of human-readable output
        #[arg(long)]
        json: bool,
        /// Skip emitting site.json manifest
        #[arg(long)]
        no_manifest: bool,
        /// Skip emitting search.json index
        #[arg(long)]
        no_search: bool,
        /// Skip emitting _health.html health dashboard
        #[arg(long)]
        no_health: bool,
    },
    /// Watch source, rebuild on change, serve at localhost:PORT
    Dev {
        /// Directory of .yaml source files
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// Output directory for the built site
        #[arg(short, long, default_value = "_site")]
        out: PathBuf,
        /// Port to serve the live-reloading site on
        #[arg(short, long, default_value_t = 3000)]
        port: u16,
    },
    /// Scaffold a new kazam site in <NAME>/
    Init {
        /// Directory to create, also used as the site name
        name: String,
    },
    /// Print the LLM authoring guide (full AGENTS.md to stdout)
    Agents,
    /// Install an AI tool pack from a curata instance (writes CLAUDE.md + .cursorrules)
    Install {
        /// Pack URL: https://<instance>/pages/<slug>, /p/<org>/<slug>, <instance>/<slug>,
        /// or a bare pack name (resolved against KAZAM_CURATA_URL)
        url: String,
        /// API key for the curata instance (falls back to KAZAM_CURATA_API_KEY)
        #[arg(long)]
        api_key: Option<String>,
        /// Directory to write config files into (implies --repo if not "."; repo scope)
        #[arg(short, long, default_value = ".")]
        dir: PathBuf,
        /// Install even if the page has no pack: (or skill:, with --as-skill) marker
        #[arg(long)]
        force: bool,
        /// Override the pack's declared targets. Repeatable or comma-separated.
        /// Supported: claude, cursor, agents, windsurf, copilot, gemini, aider
        #[arg(long, value_delimiter = ',')]
        cli: Vec<String>,
        /// Also install the pack's declarative hooks (writes hook config +
        /// registers the kazam runner in .claude/settings.json). Off by default.
        #[arg(long)]
        allow_hooks: bool,
        /// Install for the current user (~/.claude), shared across every
        /// project. This is the default when no scope flag is given.
        #[arg(long)]
        user: bool,
        /// Install into this repo only (writes at --dir). Mutually exclusive
        /// with --user.
        #[arg(long)]
        repo: bool,
        /// Install a skill:-marked page as a Claude Code skill
        /// (.claude/skills/<slug>/SKILL.md) instead of into rules targets.
        /// Mutually exclusive with --cli.
        #[arg(long)]
        as_skill: bool,
    },
    /// Check installed packs for drift against their curata source pages
    Check {
        /// Directory to scan for installed packs
        #[arg(short, long, default_value = ".")]
        dir: PathBuf,
        /// API key for the curata instance (falls back to KAZAM_CURATA_API_KEY)
        #[arg(long)]
        api_key: Option<String>,
    },
    /// Manage AI tool packs on the configured curata instance
    Packs {
        #[command(subcommand)]
        command: PacksCommand,
    },
    /// Internal: run a declarative pack hook (registered in settings by install)
    PackHook {
        /// Pack slug whose hook config to load
        #[arg(long)]
        pack: String,
        /// Index of the hook within the pack's config
        #[arg(long)]
        index: usize,
        /// Absolute path to the hook config, set automatically by install.
        /// When absent (pre-1.8.0 installs), falls back to walking up from
        /// `dir` for the old `.kazam/packs/` location.
        #[arg(long)]
        config: Option<PathBuf>,
        /// Project directory (default: current directory)
        #[arg(long, default_value = ".")]
        dir: PathBuf,
    },
    /// Grant a wish - install a recipe for self-refreshing docs
    Wish {
        #[command(subcommand)]
        command: WishCommand,
    },
    /// Pull data from vendor APIs, transform, aggregate, and output to curata or terminal
    Connect {
        #[command(subcommand)]
        command: connect::ConnectCommand,
        /// Project directory (default: current directory)
        #[arg(short, long, default_value = ".", global = true)]
        dir: PathBuf,
    },
    /// Manage the work graph - tasks, dependencies, activity log.
    Track {
        #[command(subcommand)]
        command: track::Command,
        /// Project directory (default: current directory)
        #[arg(short, long, default_value = ".", global = true)]
        dir: PathBuf,
    },
    /// Manage context intelligence - file anatomy, learnings, bugs.
    Ctx {
        #[command(subcommand)]
        command: ctx::Command,
        /// Project directory (default: current directory)
        #[arg(short, long, default_value = ".", global = true)]
        dir: PathBuf,
    },
    /// Live dashboard - renders .kazam/ state as a visual board.
    Board {
        /// Project directory (default: current directory)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// Port to serve the board on
        #[arg(short, long, default_value_t = 3001)]
        port: u16,
    },
    /// Export a page to another format (currently: pdf via headless Chrome)
    Export {
        #[command(subcommand)]
        command: ExportCommand,
    },
    /// Open a file (.md, .yaml, .json) in the browser with live reload and inline editing.
    Open {
        /// Path to the file to open
        path: PathBuf,
        /// Port to serve the file view on
        #[arg(short, long, default_value_t = 3002)]
        port: u16,
    },
    /// Pretty-print a file (.md, .yaml, .json) in the terminal.
    Show {
        /// Path to the file to show
        path: PathBuf,
    },
    /// Initialize the full agent workspace (track + ctx + hooks) in one shot.
    Workspace {
        #[command(subcommand)]
        command: WorkspaceCommand,
        /// Project directory (default: current directory)
        #[arg(short, long, default_value = ".", global = true)]
        dir: PathBuf,
    },
    /// Validate page YAML files against component schemas and structural rules.
    Validate {
        /// Directory of .yaml source files to validate (default: current directory)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// Validate a single YAML file instead of the whole directory
        #[arg(long)]
        file: Option<PathBuf>,
        /// Human-readable output (default is JSON)
        #[arg(long)]
        pretty: bool,
    },
    /// Run an MCP server over stdio for AI client integration
    Mcp {
        /// Site directory to serve
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// Allow write operations (write_page, annotate_page, update_annotation)
        #[arg(long)]
        allow_writes: bool,
        /// Transport: stdio (default) or http
        #[arg(long, default_value = "stdio")]
        transport: String,
        /// Port for HTTP transport
        #[arg(long, default_value = "8080")]
        port: u16,
        /// Bind to localhost only (default for http). Mutually exclusive with --remote.
        #[arg(long, conflicts_with = "remote")]
        local: bool,
        /// Bind to all interfaces (0.0.0.0) for remote access. Requires --token or KAZAM_MCP_TOKEN.
        #[arg(long, conflicts_with = "local")]
        remote: bool,
        /// Bearer token for remote HTTP auth. Also reads KAZAM_MCP_TOKEN env var.
        #[arg(long)]
        token: Option<String>,
    },
    /// Show freshness status for all pages in the site
    Freshness {
        #[command(subcommand)]
        command: Option<FreshnessCommand>,
        /// Site directory
        #[arg(default_value = ".", global = true)]
        dir: PathBuf,
    },
    /// Show or manage the site's voice configuration
    Voice {
        /// Site directory
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Manage prompt templates for agent workflows
    Prompt {
        #[command(subcommand)]
        command: prompts::Command,
        /// Project directory (default: current directory)
        #[arg(short, long, default_value = ".", global = true)]
        dir: PathBuf,
    },
    /// Manage GitHub Action workflow templates
    Actions {
        #[command(subcommand)]
        command: ActionsCommand,
        /// Project directory (default: current directory)
        #[arg(short, long, default_value = ".", global = true)]
        dir: PathBuf,
    },
    /// Audit site health - freshness, structural quality, and completeness
    Audit {
        /// Site directory
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// Human-readable output (default is JSON)
        #[arg(long)]
        pretty: bool,
    },
    /// Ingest content from external platforms into kazam pages
    Ingest {
        #[command(subcommand)]
        command: IngestCommand,
    },
    /// Manage annotations on pages (sidecar files in .kazam/annotations/)
    Annotate {
        #[command(subcommand)]
        command: AnnotateCommand,
        /// Site directory
        #[arg(short, long, default_value = ".", global = true)]
        dir: PathBuf,
    },
    /// Emit a TypeScript SDK from the page schema (types, enums, interfaces)
    Sdk {
        #[command(subcommand)]
        command: SdkCommand,
    },
    /// Output the kazam CSS theme for use in external apps
    Theme {
        #[command(subcommand)]
        command: ThemeCommand,
    },
    /// Parse, validate, and compile Agent Graph Language (.agl) specs
    Agl {
        #[command(subcommand)]
        command: agl::Command,
    },
    /// Generate the CLI command reference from --help metadata
    CliReference {
        /// Write the generated reference into README.md between the markers
        #[arg(long)]
        write: bool,
        /// Exit 1 if README.md's block doesn't match freshly generated output (for CI)
        #[arg(long)]
        check: bool,
    },
}

#[derive(Subcommand)]
enum SdkCommand {
    /// Print TypeScript type definitions to stdout
    Emit,
    /// Print React component renderer to stdout (TSX)
    EmitReact,
    /// Print JSON component schema to stdout (for agent tooling)
    EmitSchema,
    /// Print markdown component reference to stdout (for agent context)
    EmitAgents,
    /// Print the MCP guidance bundle (tool descriptions, instructions, per-component slices) as JSON
    EmitMcp,
}

#[derive(Subcommand)]
enum ExportCommand {
    /// Build one page and print it to PDF with headless Chrome. Honors the
    /// page's `print_flow` (use `letter` for a portrait document).
    Pdf {
        /// Path to the page .yaml
        page: PathBuf,
        /// Output PDF path (default: next to the page, .pdf extension)
        #[arg(short, long)]
        out: Option<PathBuf>,
        /// Chrome/Chromium binary (default: auto-detect, or $KAZAM_CHROME)
        #[arg(long)]
        chrome: Option<PathBuf>,
        /// Suppress the success line
        #[arg(short, long)]
        quiet: bool,
    },
}

#[derive(Subcommand)]
enum ThemeCommand {
    /// Print the full CSS stylesheet to stdout
    Css {
        /// Theme name (dark, light, red, orange, yellow, green, blue, indigo, violet)
        #[arg(long, default_value = "dark")]
        theme: String,
        /// Base mode for rainbow themes (dark, light). Ignored for dark/light themes.
        #[arg(long, default_value = "dark")]
        mode: String,
        /// Enable texture overlay (none, dots, grid, grain, topography, diagonal)
        #[arg(long, default_value = "none")]
        texture: String,
        /// Enable glow effect (none, accent, corner)
        #[arg(long, default_value = "none")]
        glow: String,
        /// Surface depth for panels (flat, soft, lifted)
        #[arg(long, default_value = "soft")]
        depth: String,
        /// Emit all theme/mode/texture/glow/depth variants as [data-*] CSS selectors
        /// for runtime switching. When set, --theme/--mode/--texture/--glow are ignored.
        #[arg(long)]
        switchable: bool,
    },
    /// Print only the :root CSS custom properties block to stdout
    Vars {
        /// Theme name (dark, light, red, orange, yellow, green, blue, indigo, violet)
        #[arg(long, default_value = "dark")]
        theme: String,
        /// Base mode for rainbow themes (dark, light). Ignored for dark/light themes.
        #[arg(long, default_value = "dark")]
        mode: String,
    },
    /// Print theme tokens as JSON (for programmatic consumption)
    Json {
        /// Theme name (dark, light, red, orange, yellow, green, blue, indigo, violet)
        #[arg(long, default_value = "dark")]
        theme: String,
        /// Base mode for rainbow themes (dark, light). Ignored for dark/light themes.
        #[arg(long, default_value = "dark")]
        mode: String,
    },
}

#[derive(Subcommand)]
enum WishCommand {
    /// List available wishes (local + registry)
    List {
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Install a wish from the registry into local wishes/
    Init {
        /// Name of the wish to install
        name: String,
        /// Install to a specific directory instead of wishes/
        #[arg(long)]
        dir: Option<PathBuf>,
        /// Overwrite existing local wish
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum PacksCommand {
    /// List installable pack pages from the configured curata instance
    List {
        /// Curata instance base URL (falls back to KAZAM_CURATA_URL)
        #[arg(long)]
        url: Option<String>,
        /// API key for the curata instance (falls back to KAZAM_CURATA_API_KEY)
        #[arg(long)]
        api_key: Option<String>,
    },
}

/// Resolve `kazam install`'s scope from CLI flags, prompting interactively
/// when the scope is ambiguous. Kept deterministic input-wise (no hidden
/// state beyond argv/stdin) so the CLI stays scriptable: an explicit `--dir`
/// implies `--repo`, protecting scripted installs from a surprise prompt.
fn resolve_install_scope(user: bool, repo: bool, dir: PathBuf) -> Result<install::InstallScope> {
    use std::io::IsTerminal;

    if user && repo {
        anyhow::bail!("--user and --repo are mutually exclusive: pick one");
    }
    if repo {
        return Ok(install::InstallScope::Repo(dir));
    }
    if user {
        return Ok(install::InstallScope::User);
    }

    let dir_explicit = dir.as_path() != std::path::Path::new(".");
    if dir_explicit {
        return Ok(install::InstallScope::Repo(dir));
    }

    if std::io::stdin().is_terminal() {
        use std::io::Write;
        print!(
            "Install for all your projects (user) or just this repo? [user/repo] (default: user): "
        );
        std::io::stdout().flush().ok();
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).ok();
        let choice = line.trim().to_lowercase();
        return if choice == "repo" || choice == "r" {
            println!("Installing into this repo ({}).", dir.display());
            Ok(install::InstallScope::Repo(dir))
        } else {
            println!("Installing for all your projects (user scope, ~/.claude).");
            Ok(install::InstallScope::User)
        };
    }

    Ok(install::InstallScope::User)
}

fn parse_mode(s: &str) -> types::Mode {
    match s {
        "light" => types::Mode::Light,
        _ => types::Mode::Dark,
    }
}

fn parse_texture(s: &str) -> types::Texture {
    match s {
        "dots" => types::Texture::Dots,
        "grid" => types::Texture::Grid,
        "grain" => types::Texture::Grain,
        "topography" => types::Texture::Topography,
        "diagonal" => types::Texture::Diagonal,
        _ => types::Texture::None,
    }
}

fn parse_glow(s: &str) -> types::Glow {
    match s {
        "accent" => types::Glow::Accent,
        "corner" => types::Glow::Corner,
        _ => types::Glow::None,
    }
}

fn parse_depth(s: &str) -> types::Depth {
    match s {
        "flat" => types::Depth::Flat,
        "lifted" => types::Depth::Lifted,
        _ => types::Depth::Soft,
    }
}

fn main() -> Result<()> {
    match Cli::parse().command {
        Command::Build {
            dir,
            out,
            release,
            allow_orphans,
            json,
            no_manifest,
            no_search,
            no_health,
        } => build::run(
            &dir,
            &out,
            release,
            allow_orphans,
            json,
            no_manifest,
            no_search,
            no_health,
        ),
        Command::Dev { dir, out, port } => dev::run(&dir, &out, port),
        Command::Init { name } => init::run(&name),
        Command::Agents => agents::run(),
        Command::Install {
            url,
            api_key,
            dir,
            force,
            cli,
            allow_hooks,
            user,
            repo,
            as_skill,
        } => {
            let scope = resolve_install_scope(user, repo, dir)?;
            install::run(&url, api_key, scope, force, &cli, allow_hooks, as_skill)
        }
        Command::Check { dir, api_key } => install::check(&dir, api_key),
        Command::Packs { command } => match command {
            PacksCommand::List { url, api_key } => install::list_packs(url, api_key),
        },
        Command::PackHook {
            pack,
            index,
            config,
            dir,
        } => packhook::run(&pack, index, config, &dir),
        Command::Wish { command } => match command {
            WishCommand::List { json } => wish::list(json),
            WishCommand::Init { name, dir, force } => wish::init(&name, dir, force),
        },
        Command::Connect { command, dir } => connect::run(command, &dir),
        Command::Track { command, dir } => track::run(command, &dir),
        Command::Ctx { command, dir } => ctx::run(command, &dir),
        Command::Board { dir, port } => board::run(&dir, port),
        Command::Export { command } => match command {
            ExportCommand::Pdf {
                page,
                out,
                chrome,
                quiet,
            } => {
                let out = out.unwrap_or_else(|| page.with_extension("pdf"));
                export::run_pdf(&page, &out, chrome.as_deref(), quiet)
            }
        },
        Command::Open { path, port } => open::run(&path, port),
        Command::Show { path } => show::run(&path),
        Command::Workspace { command, dir } => workspace::run_command(command, &dir),
        Command::Validate { dir, file, pretty } => {
            let errors = if let Some(file_path) = file {
                let path = dir.join(&file_path);
                validate::validate_single_file(&path)
            } else {
                validate::validate_dir(&dir)
            };
            if pretty {
                validate::print_pretty(&errors);
            } else {
                println!("{}", serde_json::to_string_pretty(&errors)?);
            }
            if validate::has_errors(&errors) {
                std::process::exit(1);
            }
            Ok(())
        }
        Command::Mcp {
            dir,
            allow_writes,
            transport,
            port,
            local,
            remote,
            token,
        } => match transport.as_str() {
            "http" => {
                let bind_addr = if remote { "0.0.0.0" } else { "127.0.0.1" };
                let resolved_token = token.or_else(|| std::env::var("KAZAM_MCP_TOKEN").ok());
                if remote && resolved_token.is_none() {
                    anyhow::bail!(
                        "--remote requires a bearer token: pass --token <TOKEN> or set KAZAM_MCP_TOKEN"
                    );
                }
                if local && resolved_token.is_some() {
                    eprintln!("kazam mcp: note: --token is ignored in local mode");
                }
                mcp::run_http(
                    &dir,
                    allow_writes,
                    port,
                    bind_addr,
                    resolved_token.as_deref(),
                )
            }
            _ => mcp::run(&dir, allow_writes),
        },
        Command::Freshness { command, dir } => match command {
            None | Some(FreshnessCommand::Show { .. }) => {
                let (pretty, threshold) = match command {
                    Some(FreshnessCommand::Show { pretty, threshold }) => (pretty, threshold),
                    _ => (false, None),
                };
                freshness::run_command(&dir, pretty, threshold)
            }
            Some(FreshnessCommand::Review { json }) => freshness::run_review(&dir, json),
            Some(FreshnessCommand::Act { path, action }) => {
                freshness::run_act(&dir, &path, &action)
            }
            Some(FreshnessCommand::Notify { json }) => freshness::run_notify(&dir, json),
            Some(FreshnessCommand::Drift { pretty, repos }) => {
                freshness::run_drift(&dir, pretty, repos)
            }
        },
        Command::Voice { dir, json } => voice::run(&dir, json),
        Command::Prompt { command, dir } => prompts::run(command, &dir),
        Command::Actions { command, dir } => match command {
            ActionsCommand::List => actions::list(),
            ActionsCommand::Init { name } => actions::init(&name, &dir),
        },
        Command::Sdk { command } => match command {
            SdkCommand::Emit => sdk::emit_typescript(),
            SdkCommand::EmitReact => sdk::emit_react(),
            SdkCommand::EmitSchema => sdk::emit_schema(),
            SdkCommand::EmitAgents => sdk::emit_agents(),
            SdkCommand::EmitMcp => sdk::emit_mcp(),
        },
        Command::Audit { dir, pretty } => audit::run(&dir, pretty),
        Command::Annotate { command, dir } => match command {
            AnnotateCommand::Add {
                page,
                text,
                section,
                author,
                source,
            } => {
                let page_path = dir.join(&page);
                if !page_path.exists() {
                    anyhow::bail!("page not found: {}", page);
                }
                let source_enum: types::AnnotationSource = match source.as_str() {
                    "cli" => types::AnnotationSource::Cli,
                    "agent" => types::AnnotationSource::Agent,
                    "web" => types::AnnotationSource::Web,
                    other => {
                        anyhow::bail!("invalid source '{}': expected cli, agent, or web", other)
                    }
                };
                let today = freshness::today_iso();
                let id = annotations::generate_id(&today);
                let ann = types::Annotation {
                    id: id.clone(),
                    text,
                    author,
                    section,
                    added: today,
                    status: types::AnnotationStatus::Pending,
                    source: source_enum,
                };
                let slug = annotations::page_slug_from_path(&page);
                let path = annotations::save_annotation(&dir, &slug, &ann)?;
                println!("✓ annotation {} → {}", id, path.display());
                Ok(())
            }
            AnnotateCommand::List { page, json } => {
                let slug = annotations::page_slug_from_path(&page);
                let anns = annotations::load_annotations(&dir, &slug)?;
                if json {
                    println!("{}", serde_json::to_string_pretty(&anns)?);
                } else if anns.is_empty() {
                    println!("no annotations on {}", page);
                } else {
                    for ann in &anns {
                        let status = match ann.status {
                            types::AnnotationStatus::Pending => "pending",
                            types::AnnotationStatus::Incorporated => "incorporated",
                            types::AnnotationStatus::Ignored => "ignored",
                            types::AnnotationStatus::Stale => "stale",
                        };
                        let section = ann.section.as_deref().unwrap_or("-");
                        println!(
                            "  {} [{}] ({}, {}) {}",
                            ann.id, status, ann.author, section, ann.text
                        );
                    }
                    println!("\n{} annotation(s)", anns.len());
                }
                Ok(())
            }
            AnnotateCommand::Resolve { id } => {
                annotations::resolve_annotation(&dir, &id)?;
                println!("✓ {} → incorporated", id);
                Ok(())
            }
            AnnotateCommand::Clear { page } => {
                let slug = annotations::page_slug_from_path(&page);
                let count = annotations::clear_annotations(&dir, &slug)?;
                println!("✓ cleared {} annotation(s) from {}", count, page);
                Ok(())
            }
        },
        Command::Theme { command } => match command {
            ThemeCommand::Css {
                theme: theme_name,
                mode,
                texture,
                glow,
                depth,
                switchable,
            } => {
                if switchable {
                    let m = parse_mode(&mode);
                    let base_theme = if theme_name == "dark" {
                        "violet"
                    } else {
                        &theme_name
                    };
                    let t = theme::Theme::named(base_theme, m);
                    print!("{}", theme::render_switchable_css(&t));
                } else {
                    let m = parse_mode(&mode);
                    let t = theme::Theme::named(&theme_name, m);
                    let tex = parse_texture(&texture);
                    let g = parse_glow(&glow);
                    let d = parse_depth(&depth);
                    print!("{}", theme::render_css(&t, tex, g, d));
                }
                Ok(())
            }
            ThemeCommand::Vars {
                theme: theme_name,
                mode,
            } => {
                let m = parse_mode(&mode);
                let t = theme::Theme::named(&theme_name, m);
                print!("{}", t.root_block());
                Ok(())
            }
            ThemeCommand::Json {
                theme: theme_name,
                mode,
            } => {
                let m = parse_mode(&mode);
                let t = theme::Theme::named(&theme_name, m);
                print!("{}", t.to_json());
                Ok(())
            }
        },
        Command::Agl { command } => agl::run(command),
        Command::CliReference { write, check } => cli_reference::write_or_check(write, check),
        Command::Ingest { command } => match command {
            IngestCommand::Notion {
                database,
                page,
                token,
                out,
                dry_run,
                stats,
                all,
            } => {
                if stats {
                    ingest::notion_stats(&database, &page, &token, all)
                } else {
                    ingest::notion(&database, &page, &token, &out, dry_run, all)
                }
            }
        },
    }
}

#[derive(Subcommand)]
pub enum FreshnessCommand {
    /// Show freshness status for all pages (default)
    Show {
        /// Human-readable table output (default is JSON)
        #[arg(long)]
        pretty: bool,
        /// Days since last update before a page counts as stale
        #[arg(long)]
        threshold: Option<u64>,
    },
    /// List stale pages for review with recommended actions
    Review {
        /// Output as JSON (default is human-readable)
        #[arg(long)]
        json: bool,
    },
    /// Take action on a stale page: archive, refresh, or skip
    Act {
        /// Path to the page YAML file (relative to site dir)
        path: String,
        /// Action to take
        #[arg(value_enum)]
        action: FreshnessAction,
    },
    /// Generate a digest of stale pages grouped by owner (for Slack/email)
    Notify {
        /// Output as JSON instead of markdown
        #[arg(long)]
        json: bool,
    },
    /// Check if source-of-truth files have changed since pages were last updated
    Drift {
        /// Human-readable table output (default is JSON)
        #[arg(long)]
        pretty: bool,
        /// Additional repo mapping: PREFIX=LOCAL (can repeat)
        #[arg(long = "repo", value_name = "PREFIX=LOCAL")]
        repos: Vec<String>,
    },
}

#[derive(Clone, clap::ValueEnum)]
pub enum FreshnessAction {
    /// Set archived: true on the page
    Archive,
    /// Update freshness.updated to today's date
    Refresh,
}

#[derive(Subcommand)]
pub enum ActionsCommand {
    /// List available action templates
    List,
    /// Initialize an action template in .github/workflows/
    Init {
        /// Template name (validate, freshness, build)
        name: String,
    },
}

#[derive(Subcommand)]
pub enum IngestCommand {
    /// Import pages from a Notion workspace.
    ///
    /// Setup (one-time):
    ///   1. Go to https://www.notion.so/profile/integrations/internal
    ///   2. Click "New integration", name it (e.g. "kazam"), submit
    ///   3. Copy the Internal Integration Secret (starts with ntn_)
    ///   4. Set NOTION_TOKEN in .env or export NOTION_TOKEN=ntn_...
    ///   5. Find your workspace ID: click workspace name (top-left) → Settings → General
    ///      (workspace ID is at the bottom of the page)
    ///   6. Set NOTION_WORKSPACE_ID in .env (optional, for --all discovery)
    ///   7. In Notion, open the page/database you want to import
    ///   8. Click ··· → Connections → add your integration (gives it access to content)
    ///      (child pages inherit access from parent)
    ///
    /// Finding IDs:
    ///   Page URL:  notion.so/My-Page-abc123def456 → --page abc123de-f456-...
    ///   DB URL:    notion.so/abc123?v=...         → --database abc123...
    ///   The 32-char hex string in the URL is the ID (add dashes for UUID format)
    Notion {
        /// Notion database ID - each row becomes a page
        #[arg(long)]
        database: Option<String>,
        /// Notion page ID - import a single page and its children
        #[arg(long)]
        page: Option<String>,
        /// Notion API token (default: .env NOTION_TOKEN or env var)
        #[arg(long)]
        token: Option<String>,
        /// Output directory for generated YAML files (default: current dir)
        #[arg(long, default_value = ".")]
        out: PathBuf,
        /// Preview what would be created without writing files
        #[arg(long)]
        dry_run: bool,
        /// Show staleness stats without ingesting (metadata only, fast)
        #[arg(long)]
        stats: bool,
        /// Discover and ingest all pages the integration can access
        #[arg(long)]
        all: bool,
    },
}

#[derive(Subcommand)]
pub enum AnnotateCommand {
    /// Add an annotation to a page
    Add {
        /// Page path relative to site root (e.g. 'deals/acme.yaml')
        page: String,
        /// Annotation text
        text: String,
        /// Section this annotation applies to (e.g. 'competitive', 'timeline')
        #[arg(long)]
        section: Option<String>,
        /// Author name
        #[arg(long, default_value = "anonymous")]
        author: String,
        /// Source: cli, agent, or web
        #[arg(long, default_value = "cli")]
        source: String,
    },
    /// List annotations on a page
    List {
        /// Page path relative to site root
        page: String,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Mark an annotation as incorporated
    Resolve {
        /// Annotation ID (e.g. 'ann-20260507-e708')
        id: String,
    },
    /// Remove all annotations for a page
    Clear {
        /// Page path relative to site root
        page: String,
    },
}

#[derive(Subcommand)]
pub enum WorkspaceCommand {
    /// Initialize track + ctx + scan + hooks in one shot
    Init {
        /// Agent to register hooks for
        #[arg(long, default_value = "claude")]
        agent: String,
        /// Gitignore .kazam/ for shared repos
        #[arg(long)]
        skunkworks: bool,
        /// Sass level for human blocker callouts (none, some, lots)
        #[arg(long, default_value = "some")]
        sass: String,
    },
    /// Show workspace status
    Status,
    /// Set the sass level for human blocker callouts
    Sass {
        /// none, some, or lots
        level: String,
    },
    /// Toggle skunkworks mode (gitignore .kazam/)
    Skunkworks {
        /// enable or disable
        action: String,
    },
}