rok-cli 0.3.2

Developer CLI for rok-based Axum applications
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
use clap::{Parser, Subcommand};

mod commands;
mod json_io;

#[derive(Parser)]
#[command(
    name = "rok",
    version,
    about = "rok developer CLI for Axum applications"
)]
struct Cli {
    /// Output result as JSON (machine-readable)
    #[arg(long, short = 'j', global = true)]
    json: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Scaffold a new rok/Axum application
    New {
        /// Name of the application directory to create
        name: String,
        /// Project template: api, saas, htmx, microservice, minimal (default: interactive prompt)
        #[arg(long, short = 't', value_name = "TEMPLATE")]
        template: Option<String>,
    },

    // ── make:* generators ──────────────────────────────────────────────────────
    /// Generate a controller
    #[command(name = "make:controller")]
    MakeController {
        /// Controller name (e.g. User, BlogPost)
        name: String,
        /// Generate a full resource controller with CRUD methods
        #[arg(long)]
        resource: bool,
    },

    /// Generate a model (and optionally a migration, controller, resource, and factory)
    #[command(name = "make:model")]
    MakeModel {
        /// Model name (e.g. User, BlogPost)
        name: String,
        /// Primary key type: ulid, cuid2, uuid_v7, snowflake, nanoid (default: bigserial i64)
        #[arg(long, value_name = "TYPE")]
        id: Option<String>,
        /// Also generate a migration for this model
        #[arg(long)]
        migration: bool,
        /// Also generate a controller for this model
        #[arg(long)]
        controller: bool,
        /// Also generate an API resource transformer for this model
        #[arg(long)]
        resource: bool,
        /// Also generate a model factory for this model
        #[arg(long)]
        factory: bool,
    },

    /// Generate a migration
    #[command(name = "make:migration")]
    MakeMigration {
        /// Migration name (e.g. create_users_table)
        name: String,
    },

    /// Generate a seeder
    #[command(name = "make:seeder")]
    MakeSeeder {
        /// Seeder name (e.g. User, BlogPost)
        name: String,
    },

    /// Generate a validator
    #[command(name = "make:validator")]
    MakeValidator {
        /// Validator name (e.g. Login, CreatePost)
        name: String,
    },

    /// Generate full CRUD scaffold: model, migration, controller, validator, resource, policy, factory, test, routes
    #[command(name = "make:crud")]
    MakeCrud {
        /// Resource name (e.g. Post, BlogArticle)
        name: String,
        /// Comma-separated fields: title:string,body:text,published:bool
        #[arg(long, value_name = "FIELDS")]
        fields: Option<String>,
        /// Primary key type: ulid, cuid2, uuid_v7, snowflake, nanoid (default: bigserial)
        #[arg(long, value_name = "TYPE")]
        id: Option<String>,
        /// Add auth guard (require authenticated user) to all routes
        #[arg(long)]
        auth: bool,
        /// Add deleted_at soft-delete column
        #[arg(long)]
        soft_delete: bool,
        /// Add created_at / updated_at timestamp columns
        #[arg(long, default_value = "true")]
        timestamps: bool,
        /// Add cursor-based pagination to index endpoint
        #[arg(long)]
        paginate: bool,
        /// Overwrite existing files
        #[arg(long)]
        force: bool,
    },

    /// Generate a model + migration from an inline JSON payload
    #[command(name = "make:from-json")]
    MakeFromJson {
        /// Resource name (e.g. Order)
        name: String,
        /// JSON string (inline) or path to a JSON file (use with --file)
        json_input: String,
        /// Treat `json` argument as a file path
        #[arg(long)]
        file: bool,
        /// Preview generated code without writing files
        #[arg(long)]
        dry_run: bool,
        /// Overwrite existing files
        #[arg(long)]
        force: bool,
    },

    /// Generate a model + migration from a JSON Schema file
    #[command(name = "make:from-schema")]
    MakeFromSchema {
        /// Resource name (e.g. Order)
        name: String,
        /// Path to the JSON Schema file
        #[arg(long, value_name = "FILE")]
        file: String,
        /// Preview generated code without writing files
        #[arg(long)]
        dry_run: bool,
        /// Overwrite existing files
        #[arg(long)]
        force: bool,
    },

    /// Generate an observer
    #[command(name = "make:observer")]
    MakeObserver {
        /// Observer name (e.g. User, Post)
        name: String,
        /// Overwrite existing file
        #[arg(long)]
        force: bool,
    },

    /// Generate an API resource transformer
    #[command(name = "make:resource")]
    MakeResource {
        /// Resource name (e.g. User, Post)
        name: String,
        /// Overwrite existing file
        #[arg(long)]
        force: bool,
    },

    /// Generate a query scope
    #[command(name = "make:scope")]
    MakeScope {
        /// Scope name (e.g. Active, Published)
        name: String,
        /// Overwrite existing file
        #[arg(long)]
        force: bool,
    },

    /// Generate an authorization policy
    #[command(name = "make:policy")]
    MakePolicy {
        /// Policy name (e.g. User, Post)
        name: String,
        /// Overwrite existing file
        #[arg(long)]
        force: bool,
    },

    /// Generate a background job
    #[command(name = "make:job")]
    MakeJob {
        /// Job name (e.g. SendWelcomeEmail)
        name: String,
        /// Overwrite existing file
        #[arg(long)]
        force: bool,
    },

    /// Generate an event
    #[command(name = "make:event")]
    MakeEvent {
        /// Event name (e.g. UserRegistered)
        name: String,
        /// Overwrite existing file
        #[arg(long)]
        force: bool,
    },

    /// Generate an event listener
    #[command(name = "make:listener")]
    MakeListener {
        /// Listener name (e.g. SendWelcomeEmail)
        name: String,
        /// Overwrite existing file
        #[arg(long)]
        force: bool,
    },

    /// Generate a notification
    #[command(name = "make:notification")]
    MakeNotification {
        /// Notification name (e.g. WelcomeMail)
        name: String,
        /// Overwrite existing file
        #[arg(long)]
        force: bool,
    },

    /// Generate a test file
    #[command(name = "make:test")]
    MakeTest {
        /// Test name (e.g. UserController)
        name: String,
        /// Overwrite existing file
        #[arg(long)]
        force: bool,
    },

    /// Generate a locale translation file from locales/en.json as template
    #[command(name = "make:locale")]
    MakeLocale {
        /// Language code to generate (e.g. fr, de, es, ja)
        lang: String,
        /// Overwrite if the locale file already exists
        #[arg(long)]
        force: bool,
    },

    /// Generate a TypeScript API client from resource structs
    #[command(name = "make:ts-client")]
    MakeTsClient {
        /// Output file path (default: client.ts)
        #[arg(long, value_name = "FILE")]
        output: Option<String>,
    },

    // ── db:* commands ──────────────────────────────────────────────────────────
    /// Apply all pending migrations
    #[command(name = "db:migrate")]
    DbMigrate {
        /// Print pending migrations without applying them
        #[arg(long)]
        dry_run: bool,
    },

    /// Rollback the last N migration batches
    #[command(name = "db:rollback")]
    DbRollback {
        /// Number of migration steps to roll back (default 1)
        #[arg(long, value_name = "N")]
        step: Option<u32>,
    },

    /// Show migration status
    #[command(name = "db:status")]
    DbStatus,

    /// Apply pending migrations with progress output
    #[command(name = "db:update")]
    DbUpdate,

    /// Run database seeders
    #[command(name = "db:seed")]
    DbSeed {
        /// Run only this specific seeder class
        #[arg(long, value_name = "CLASS")]
        class: Option<String>,
    },

    /// Drop all tables and re-run all migrations
    #[command(name = "db:fresh")]
    DbFresh,

    /// Introspect a live database table and generate a model struct
    #[command(name = "db:pull")]
    DbPull {
        /// Table name to introspect
        table: String,
        /// Write generated model to this file instead of printing
        #[arg(long, value_name = "FILE")]
        output: Option<String>,
    },

    /// Compare a model file against the live database schema and report drift
    #[command(name = "db:diff")]
    DbDiff {
        /// Path to the model source file (e.g. src/app/models/user.rs)
        model_file: String,
        /// Override table name (default: inferred from #[rok_orm(table = "...")])
        #[arg(long, value_name = "TABLE")]
        table: Option<String>,
    },

    // ── queue:* commands ───────────────────────────────────────────────────────
    /// Start the queue worker (hint: integrate rok_queue::Worker in your app)
    #[command(name = "queue:work")]
    QueueWork {
        /// Queue name to consume (default: "default")
        #[arg(long, value_name = "QUEUE")]
        queue: Option<String>,
        /// Number of concurrent job runners (default: 4)
        #[arg(long, value_name = "N")]
        concurrency: Option<usize>,
    },

    /// Show pending/running/done/failed job counts per queue
    #[command(name = "queue:status")]
    QueueStatus,

    /// Reset a failed job back to pending
    #[command(name = "queue:retry")]
    QueueRetry {
        /// Job ID to retry
        #[arg(long, value_name = "ID")]
        job_id: i64,
    },

    /// Delete failed jobs from a queue (default: all queues)
    #[command(name = "queue:flush")]
    QueueFlush {
        /// Queue name (omit to flush all queues)
        #[arg(long, value_name = "QUEUE")]
        queue: Option<String>,
    },

    // ── key / routes / dev / env ───────────────────────────────────────────────
    /// Generate a cryptographically random JWT secret
    #[command(name = "key:generate")]
    KeyGenerate,

    /// Read .env.example, generate crypto-random values for all secret-like keys,
    /// and write .env
    #[command(name = "secrets:generate")]
    SecretsGenerate,

    /// Rotate APP_KEY / JWT_SECRET — generate a new key and optionally update .env
    #[command(name = "key:rotate")]
    KeyRotate {
        /// Write the new key to .env in-place (replaces the matching KEY= line)
        #[arg(long)]
        write: bool,
        /// Key name to rotate (default: JWT_SECRET)
        #[arg(long, value_name = "NAME", default_value = "JWT_SECRET")]
        key: String,
    },

    /// Print current environment / config values (secrets are masked)
    #[command(name = "config:show")]
    ConfigShow {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// List all registered routes
    #[command(name = "routes:list")]
    RoutesList,

    /// Start the dev server with file-watch auto-restart (requires cargo-watch)
    Dev,

    /// Start the application server (auto-reloads with cargo-watch if available)
    Serve {
        /// Port to listen on (sets LISTEN_ADDR env var)
        #[arg(long, value_name = "PORT")]
        port: Option<u16>,
        /// Build in release mode
        #[arg(long)]
        release: bool,
    },

    /// Check that all required env vars (from #[env(...)]) are set
    #[command(name = "env:check")]
    EnvCheck,

    /// Create a .rok/config.toml with generator defaults
    #[command(name = "rok:init")]
    RokInit,

    /// List all available commands grouped by category
    #[command(name = "list")]
    List,

    /// Check project structure, required files, and dependencies
    #[command(name = "check")]
    Check,

    /// Generate shell completions
    #[command(name = "completion")]
    Completion {
        /// Shell type: bash, zsh, fish, powershell, elvish
        shell: Option<String>,
    },

    /// Launch the terminal UI dashboard (DB browser, migrations, features, queue)
    Tui {
        /// Database URL override (defaults to DATABASE_URL env var)
        #[arg(long, value_name = "URL")]
        db: Option<String>,
    },

    // ── make:scaffold / make:feature ──────────────────────────────────────────
    /// One-command feature scaffold (auth, crud, crud-api, upload, webhook, ...)
    #[command(name = "make:scaffold")]
    MakeScaffold {
        /// Template name (run without args to list all)
        template: Option<String>,
        /// Resource name (used as prefix for generated files)
        #[arg(long, short = 'n', value_name = "NAME")]
        name: Option<String>,
        /// Model name for data-centric scaffolds
        #[arg(long, short = 'm', value_name = "MODEL")]
        model: Option<String>,
        /// Preview what would be generated without writing files
        #[arg(long)]
        dry_run: bool,
        /// Read scaffold config from JSON file
        #[arg(long, short = 'J', alias = "jf", value_name = "FILE")]
        json_file: Option<String>,
        /// List all available scaffold templates
        #[arg(long, short = 'l')]
        list: bool,
    },

    /// Generate a complete feature from a JSON spec (models + controllers + routes)
    #[command(name = "make:feature")]
    MakeFeature {
        /// Inline JSON spec string
        #[arg(long, value_name = "JSON")]
        spec: Option<String>,
        /// Path to JSON spec file
        #[arg(long, short = 'J', alias = "jf", value_name = "FILE")]
        json_file: Option<String>,
        /// Preview without writing files
        #[arg(long)]
        dry_run: bool,
    },

    // ── plan:* commands ───────────────────────────────────────────────────────
    /// Show the next incomplete phase in router.md
    #[command(name = "plan:next")]
    PlanNext,

    /// List all phases with their status
    #[command(name = "plan:list")]
    PlanList,

    /// Output the dependency graph in DOT format
    #[command(name = "plan:graph")]
    PlanGraph,

    /// Show status of a specific phase (or all phases)
    #[command(name = "plan:status")]
    PlanStatus {
        /// Phase number to inspect
        #[arg(long, value_name = "N")]
        phase: Option<u32>,
    },

    // ── agent:* commands ──────────────────────────────────────────────────────
    /// Print the rok coding rules injected into AI agents
    #[command(name = "agent:rules")]
    AgentRules,

    /// Show full context (feature.md + PRD + prompt + progress) for a phase
    #[command(name = "agent:context")]
    AgentContext {
        /// Phase number
        #[arg(long, value_name = "N")]
        phase: Option<u32>,
    },

    /// Append feedback to progress.txt
    #[command(name = "agent:feedback")]
    AgentFeedback {
        /// Progress note to append
        #[arg(long, value_name = "TEXT")]
        progress: String,
        /// PRD item index to mark updated (0-based)
        #[arg(long, value_name = "N")]
        prd_item: Option<usize>,
    },

    /// Launch Claude Code with rok rules pre-injected
    #[command(name = "agent:claude")]
    AgentClaude {
        /// Phase number to provide as context
        #[arg(long, value_name = "N")]
        phase: Option<u32>,
        /// Additional prompt text
        #[arg(long, value_name = "TEXT")]
        prompt: Option<String>,
    },

    /// Launch OpenCode with rok rules pre-injected
    #[command(name = "agent:opencode")]
    AgentOpencode {
        /// Phase number to provide as context
        #[arg(long, value_name = "N")]
        phase: Option<u32>,
    },

    // ── publish ───────────────────────────────────────────────────────────────
    /// Publish all crates to crates.io in dependency order (runs gates, creates tags)
    #[command(name = "publish")]
    Publish {
        /// Verify gates + show publish order without uploading
        #[arg(long)]
        dry_run: bool,
        /// Publish only this specific crate
        #[arg(long, value_name = "CRATE")]
        crate_name: Option<String>,
    },

    /// Bump version, commit, tag, push, and publish (patch|minor|major)
    #[command(name = "release")]
    Release {
        /// Version bump type: patch, minor, or major
        bump: String,
        /// Release only this specific crate
        #[arg(long, value_name = "CRATE")]
        crate_name: Option<String>,
        /// Skip the publish step after release
        #[arg(long)]
        skip_publish: bool,
    },

    /// Preview unreleased commits grouped by type
    #[command(name = "changelog")]
    Changelog,

    // ── openapi ──────────────────────────────────────────────────────────────
    /// Generate OpenAPI spec from code
    #[command(name = "openapi:generate")]
    OpenapiGenerate {
        /// Output file path (default: openapi.json)
        #[arg(long, short = 'o', value_name = "FILE")]
        output: Option<String>,
        /// Output format: json or yaml
        #[arg(long, default_value = "json")]
        format: String,
    },

    /// Serve OpenAPI spec preview with Swagger UI
    #[command(name = "openapi:serve")]
    OpenapiServe {
        /// Port to listen on (default: 3001)
        #[arg(long, short = 'p', value_name = "PORT")]
        port: Option<u16>,
    },

    /// Validate an OpenAPI spec file
    #[command(name = "openapi:validate")]
    OpenapiValidate {
        /// Path to OpenAPI spec file (default: openapi.json)
        file: Option<String>,
    },

    // ── self:* commands ──────────────────────────────────────────────────────
    /// Check for updates to rok-cli
    #[command(name = "self-update")]
    SelfUpdate {
        /// Install a specific version instead of latest
        #[arg(long, value_name = "VER")]
        version: Option<String>,
        /// Re-install even if already up-to-date
        #[arg(long)]
        force: bool,
        /// Show what would be updated without making changes
        #[arg(long)]
        dry_run: bool,
    },

    /// Migrate local configuration for a new rok-cli version
    #[command(name = "self-migrate")]
    SelfMigrate {
        /// Migrate from this version (default: current config version)
        #[arg(long, value_name = "VER")]
        from: Option<String>,
        /// Migrate to this version (default: current CLI version)
        #[arg(long, value_name = "VER")]
        to: Option<String>,
        /// Show what would be migrated without making changes
        #[arg(long)]
        dry_run: bool,
    },

    /// Show installed version, latest available, and migration status
    #[command(name = "self-status")]
    SelfStatus,
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();
    let json_mode = cli.json;

    let result: anyhow::Result<()> = match cli.command {
        Command::New { name, template } => commands::new::run(&name, template.as_deref()),

        // ── make:* ────────────────────────────────────────────────────────────
        Command::MakeController { name, resource } => commands::make::controller(&name, resource),
        Command::MakeModel {
            name,
            id,
            migration,
            controller,
            resource,
            factory,
        } => commands::make::model_full(
            &name,
            id.as_deref(),
            migration,
            controller,
            resource,
            factory,
        ),
        Command::MakeMigration { name } => commands::make::migration(&name),
        Command::MakeSeeder { name } => commands::make::seeder(&name),
        Command::MakeValidator { name } => commands::make::validator(&name),
        Command::MakeObserver { name, force } => commands::make::observer(&name, force),
        Command::MakeResource { name, force } => commands::make::resource(&name, force),
        Command::MakeScope { name, force } => commands::make::scope(&name, force),
        Command::MakePolicy { name, force } => commands::make::policy(&name, force),
        Command::MakeJob { name, force } => commands::make::job(&name, force),
        Command::MakeEvent { name, force } => commands::make::event(&name, force),
        Command::MakeListener { name, force } => commands::make::listener(&name, force),
        Command::MakeNotification { name, force } => commands::make::notification(&name, force),
        Command::MakeTest { name, force } => commands::make::test(&name, force),
        Command::MakeLocale { lang, force } => commands::make::locale(&lang, force),

        Command::MakeCrud {
            name,
            fields,
            id,
            auth,
            soft_delete,
            timestamps,
            paginate,
            force,
        } => commands::crud::crud(
            &name,
            fields.as_deref(),
            id.as_deref(),
            auth,
            soft_delete,
            paginate,
            timestamps,
            force,
        ),

        Command::MakeFromJson {
            name,
            json_input,
            file,
            dry_run,
            force,
        } => commands::from_json::from_json(&name, &json_input, file, dry_run, force),

        Command::MakeFromSchema {
            name,
            file,
            dry_run,
            force,
        } => commands::from_json::from_schema(&name, &file, dry_run, force),

        Command::MakeTsClient { output } => commands::ts_client::make_ts_client(output.as_deref()),

        // ── db:* ──────────────────────────────────────────────────────────────
        Command::DbMigrate { dry_run } => commands::db::migrate(dry_run).await,
        Command::DbRollback { step } => commands::db::rollback(step.unwrap_or(1)).await,
        Command::DbStatus => commands::db::status().await,
        Command::DbUpdate => commands::db::update().await,
        Command::DbSeed { class } => commands::db::seed(class.as_deref()).await,
        Command::DbFresh => commands::db::fresh().await,

        Command::DbPull { table, output } => {
            commands::inspect::pull(&table, output.as_deref()).await
        }
        Command::DbDiff { model_file, table } => {
            commands::inspect::diff(&model_file, table.as_deref()).await
        }

        // ── queue:* ───────────────────────────────────────────────────────────
        Command::QueueWork { queue, concurrency } => {
            commands::queue::work(queue.as_deref(), concurrency)
        }
        Command::QueueStatus => commands::queue::status().await,
        Command::QueueRetry { job_id } => commands::queue::retry(job_id).await,
        Command::QueueFlush { queue } => commands::queue::flush(queue.as_deref()).await,

        // ── utilities ─────────────────────────────────────────────────────────
        Command::KeyGenerate => {
            commands::key::run();
            Ok(())
        }
        Command::SecretsGenerate => commands::secrets::run(),
        Command::KeyRotate { write, key } => commands::key::rotate(&key, write),
        Command::ConfigShow { json } => commands::dev::config_show(json),
        Command::RoutesList => commands::routes::run(),
        Command::Dev => commands::dev::dev(),
        Command::Serve { port, release } => commands::dev::serve(port, release),
        Command::EnvCheck => commands::dev::env_check(),
        Command::RokInit => commands::dev::init_rok_config(),
        Command::List => {
            commands::list::run();
            Ok(())
        }
        Command::Check => {
            commands::check::run();
            Ok(())
        }
        Command::Completion { shell } => {
            commands::completion::run(shell);
            Ok(())
        }

        Command::Tui { db } => commands::tui::run(db.as_deref()),

        // ── make:scaffold / make:feature ──────────────────────────────────────
        Command::MakeScaffold {
            template,
            name,
            model,
            dry_run,
            json_file: _,
            list,
        } => {
            use commands::scaffolds::{ScaffoldArgs, ScaffoldRegistry};
            (|| -> anyhow::Result<()> {
                let reg = ScaffoldRegistry::new();
                if list || template.is_none() {
                    for (n, desc) in reg.list() {
                        println!("{:<20} {desc}", n);
                    }
                    return Ok(());
                }
                let tmpl = template.as_deref().unwrap();
                let scaffold = reg.get(tmpl).ok_or_else(|| {
                    anyhow::anyhow!("Unknown scaffold '{tmpl}' — run: rok make:scaffold --list")
                })?;
                let args = ScaffoldArgs {
                    name,
                    model,
                    fields: Vec::new(),
                    flags: Default::default(),
                    dry_run,
                    json: json_mode,
                };
                let result = scaffold.generate(&args)?;
                if json_mode {
                    result.print_json();
                } else {
                    result.print_human();
                }
                Ok(())
            })()
        }

        Command::MakeFeature {
            spec,
            json_file,
            dry_run,
        } => commands::feature::run(spec.as_deref(), json_file.as_deref(), dry_run, json_mode),

        // ── plan:* ────────────────────────────────────────────────────────────
        Command::PlanNext => commands::plan::next(json_mode),
        Command::PlanList => commands::plan::list(json_mode),
        Command::PlanGraph => commands::plan::graph(),
        Command::PlanStatus { phase } => commands::plan::status(phase, json_mode),

        // ── agent:* ───────────────────────────────────────────────────────────
        Command::AgentRules => commands::agent::rules(json_mode),
        Command::AgentContext { phase } => commands::agent::context(phase, json_mode),
        Command::AgentFeedback { progress, prd_item } => {
            commands::agent::feedback(&progress, prd_item, json_mode)
        }
        Command::AgentClaude { phase, prompt } => {
            commands::agent::launch_claude(phase, prompt.as_deref())
        }
        Command::AgentOpencode { phase } => commands::agent::launch_opencode(phase, None),

        // ── publish ──────────────────────────────────────────────────────────────
        Command::Publish {
            dry_run,
            crate_name,
        } => {
            commands::publish::run(dry_run, crate_name.as_deref());
            Ok(())
        }

        // ── release / changelog ───────────────────────────────────────────────
        Command::Release {
            bump,
            crate_name,
            skip_publish,
        } => {
            commands::release::run(&bump, crate_name.as_deref(), skip_publish);
            Ok(())
        }
        Command::Changelog => {
            commands::changelog::run();
            Ok(())
        }

        // ── openapi ─────────────────────────────────────────────────────────
        Command::OpenapiGenerate { output, format } => {
            commands::openapi::generate(output.as_deref(), &format)
        }
        Command::OpenapiServe { port } => commands::openapi::serve(port),
        Command::OpenapiValidate { file } => commands::openapi::validate(file.as_deref()),

        // ── self:* ─────────────────────────────────────────────────────────
        Command::SelfUpdate {
            version,
            force,
            dry_run,
        } => commands::self_update::run_update(version.as_deref(), force, dry_run),
        Command::SelfMigrate { from, to, dry_run } => {
            commands::self_update::run_migrate(from.as_deref(), to.as_deref(), dry_run)
        }
        Command::SelfStatus => commands::self_update::run_check(),
    };

    if let Err(e) = result {
        eprintln!("{} {e:#}", console::style("error:").red().bold());
        std::process::exit(1);
    }
}