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
use clap::{Parser, Subcommand};
mod commands;
mod config;
mod error;
mod templates;
mod ui;
use error::Result;
#[derive(Parser)]
#[command(name = "forgedb")]
#[command(author, version, about = "ForgeDB - Type-safe database from schemas", long_about = None)]
struct Cli {
/// Enable verbose output
#[arg(short, long, global = true)]
verbose: bool,
/// Suppress output
#[arg(short, long, global = true)]
quiet: bool,
/// Path to forgedb.toml config file
#[arg(short, long, global = true)]
config: Option<String>,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Initialize a new ForgeDB project
Init {
/// Project name
project_name: String,
/// Use a template (blog, ecommerce, todo, blank)
#[arg(short, long)]
template: Option<String>,
/// Include Rust backend
#[arg(long)]
rust: bool,
/// Generate API only
#[arg(long)]
api_only: bool,
},
/// Generate code from schema
Generate {
/// Target: a runtime (`python`, `node`, `bun`, `browser`) paired with a
/// `--sdk`/`--runtime`/`--replica` mode, or a standalone artifact
/// (`all`, `rust`, `api`, `openapi`, `stubs`, `ffi`, `transform`).
#[arg(default_value = "all")]
target: String,
/// Mode (runtime targets): network REST client
#[arg(long, group = "gen_mode")]
sdk: bool,
/// Mode (runtime targets): in-process native FFI binding
#[arg(long, group = "gen_mode")]
runtime: bool,
/// Mode (runtime targets): in-process read-replica follower
#[arg(long, group = "gen_mode")]
replica: bool,
/// Verify nothing needs regeneration (CI mode)
#[arg(long)]
check: bool,
/// Output directory
#[arg(short, long)]
output: Option<String>,
/// Schema file path
#[arg(short, long)]
schema: Option<String>,
/// Force regeneration even if up-to-date
#[arg(short, long)]
force: bool,
/// Origin format version for the `transform` target (#74)
#[arg(long)]
from: Option<u32>,
/// Destination format version for the `transform` target (#74)
#[arg(long)]
to: Option<u32>,
},
/// Validate schema and check implementations
Validate {
/// Fail on unimplemented computed/views
#[arg(long)]
strict: bool,
/// Only validate schema syntax
#[arg(long)]
schema_only: bool,
/// Check computed field implementations (not yet enforced — see task #46)
#[arg(long)]
implementations: bool,
/// Check UI component files (tsx://, jsx://, api:// references)
#[arg(long)]
components: bool,
/// Schema file path
#[arg(short, long)]
schema: Option<String>,
},
/// Build production-ready artifacts
Build {
/// Build with optimizations (default)
#[arg(long, default_value = "true")]
release: bool,
/// Build target (native, wasm, both)
#[arg(short, long, default_value = "native")]
target: String,
/// Output directory
#[arg(short, long)]
output: Option<String>,
/// Schema file path
#[arg(long)]
schema: Option<String>,
/// Skip API server build
#[arg(long)]
no_api: bool,
},
/// Watch schema file and auto-regenerate on changes
Dev {
/// Schema file to watch
#[arg(short, long, default_value = "schema.forge")]
schema: String,
/// Output directory for generated code
#[arg(short, long, default_value = "generated")]
output: String,
/// Debounce delay in milliseconds
#[arg(short, long, default_value = "200")]
debounce: u64,
/// Clear terminal on each regeneration
#[arg(long, default_value = "true")]
clear: bool,
},
/// Database migration commands
#[command(subcommand)]
Migrate(MigrateCommands),
/// Database compaction and maintenance commands
#[command(subcommand)]
Compact(CompactCommands),
/// Snapshot backup & restore for a database directory
#[command(subcommand)]
Backup(BackupCommands),
/// Manage physical, dir-per-tenant data directories (#59 multi-tenancy)
#[command(subcommand)]
Tenant(TenantCommands),
/// Run the ForgeDB language server over stdio (used by editor extensions).
///
/// Thin launcher for the sibling `forgedb-lsp` binary shipped alongside the
/// CLI — keeps the async LSP stack out of the main binary (epic #173).
Lsp {
/// Explicit path to the `forgedb-lsp` server binary (otherwise resolved
/// next to `forgedb`, then on PATH)
#[arg(long)]
server_path: Option<std::path::PathBuf>,
/// Extra arguments forwarded to the language server
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Start the Tier 3 MVCC commit coordinator (multi-process writers, #84)
Coordinate {
/// Data root directory to coordinate.
root: std::path::PathBuf,
/// Unix socket path. Default: <root>/_coord.sock
#[arg(short, long)]
socket: Option<std::path::PathBuf>,
/// Replication-log fsync policy (#156): `always` (default, max durability),
/// `never` (rely on the OS; a crash rewinds replication only — no committed
/// client data lost), or `periodic` (fsync once per `--fsync-interval`
/// commits). Overridable via `FORGEDB_COORDINATOR_FSYNC`.
#[arg(long)]
fsync: Option<String>,
/// Commits per fsync when `--fsync periodic` (default 64). Overridable via
/// `FORGEDB_COORDINATOR_FSYNC_INTERVAL`.
#[arg(long)]
fsync_interval: Option<u64>,
/// Seconds a granted turn may stay un-committed before it is reclaimed
/// (#144, default 30). Governs multi-process write fairness vs
/// head-of-line blocking. Overridable via `FORGEDB_COORDINATOR_TURN_TIMEOUT`.
#[arg(long)]
turn_timeout: Option<u64>,
/// Max protocol frame in MiB (#145, default 16) — bounds per-turn
/// write-set size vs memory. Overridable via
/// `FORGEDB_COORDINATOR_MAX_FRAME_MIB`.
#[arg(long)]
max_frame_mib: Option<u64>,
},
}
#[derive(Subcommand)]
enum MigrateCommands {
/// Create a new migration
Create {
/// Description of the migration
description: String,
/// Auto-detect schema changes
#[arg(short, long)]
auto: bool,
/// Schema file to diff against the recorded snapshot (for --auto)
#[arg(short, long)]
schema: Option<std::path::PathBuf>,
},
/// Show migration status
Status,
/// Generate + compile the offline transformer bin for a version range (#74).
/// The one operator artifact that migrates data-at-rest from --from to --to.
Build {
/// Origin (current on-disk) format version
#[arg(long)]
from: u32,
/// Destination format version
#[arg(long)]
to: u32,
/// Where to emit + build the transformer (default: migrations/transform)
#[arg(short, long)]
output: Option<std::path::PathBuf>,
},
/// Run a built transformer over a src→dest data dir (app must be stopped).
Run {
/// Source data directory (at the origin format version)
#[arg(long)]
src: std::path::PathBuf,
/// Destination directory to materialize (must not exist / be empty)
#[arg(long)]
dest: std::path::PathBuf,
/// The transformer crate dir (default: migrations/transform)
#[arg(long)]
bin_dir: Option<std::path::PathBuf>,
},
/// One-CLI migration: build the transformer + run it over a data dir (or every
/// tenant dir under --tenant-root). The app must be STOPPED. #74 Phase 4.
Up {
/// Origin format version (default: detected from the source manifests)
#[arg(long)]
from: Option<u32>,
/// Destination format version (default: the lineage's current version)
#[arg(long)]
to: Option<u32>,
/// Source data directory (single-dir mode)
#[arg(long)]
src: Option<std::path::PathBuf>,
/// Destination directory to materialize (single-dir mode)
#[arg(long)]
dest: Option<std::path::PathBuf>,
/// Transformer crate dir (default: migrations/transform)
#[arg(short, long)]
output: Option<std::path::PathBuf>,
/// Migrate every data dir directly under this root (per-tenant sweep)
#[arg(long)]
tenant_root: Option<std::path::PathBuf>,
/// Per-tenant destination suffix (default: -migrated-v<to>)
#[arg(long)]
dest_suffix: Option<String>,
},
}
#[derive(Subcommand)]
enum TenantCommands {
/// Create a new tenant's data directory under the tenant root
Create {
/// Tenant name (becomes the directory name under the root)
name: String,
/// Tenant root directory (default: from forgedb.toml `[tenant].root`, else ./data)
#[arg(short, long)]
root: Option<String>,
},
/// List existing tenant data directories under the tenant root
List {
/// Tenant root directory (default: from forgedb.toml `[tenant].root`, else ./data)
#[arg(short, long)]
root: Option<String>,
/// Output as JSON
#[arg(long)]
json: bool,
},
/// Remove a tenant's data directory (destructive)
Drop {
/// Tenant name to remove
name: String,
/// Tenant root directory (default: from forgedb.toml `[tenant].root`, else ./data)
#[arg(short, long)]
root: Option<String>,
/// Skip the confirmation guard
#[arg(long)]
force: bool,
},
}
#[derive(Subcommand)]
enum CompactCommands {
/// DEPRECATED (see #105): offline compaction is removed because it is unsafe
/// against the generated mutation surface (it can resurrect deleted rows).
/// Use in-process `Database::compact()` instead (auto-invoked). This command
/// mutates nothing and exits non-zero.
Run {
/// Data directory (default: ./data)
#[arg(short, long, default_value = "data")]
data_dir: String,
/// Compact specific model only
#[arg(short, long)]
model: Option<String>,
/// Compact all models (ignore threshold)
#[arg(short, long)]
all: bool,
/// Dead space threshold (0.0-1.0)
#[arg(short, long)]
threshold: Option<f64>,
},
/// Show database statistics
Stats {
/// Data directory (default: ./data)
#[arg(short, long, default_value = "data")]
data_dir: String,
/// Show stats for specific model only
#[arg(short, long)]
model: Option<String>,
/// Output as JSON
#[arg(long)]
json: bool,
},
/// DEPRECATED (see #105): alias for the removed offline compaction path.
/// Use in-process `Database::compact()`. Mutates nothing; exits non-zero.
Vacuum {
/// Data directory (default: ./data)
#[arg(short, long, default_value = "data")]
data_dir: String,
},
/// Analyze database and show recommendations
Analyze {
/// Data directory (default: ./data)
#[arg(short, long, default_value = "data")]
data_dir: String,
/// Output as JSON
#[arg(long)]
json: bool,
},
}
#[derive(Subcommand)]
enum BackupCommands {
/// Create a lock-free snapshot archive of a database directory (full, or
/// an incremental byte-tail delta with `--incremental`)
Create {
/// Data directory (default: ./data)
#[arg(short, long, default_value = "data")]
data_dir: String,
/// Output archive path
#[arg(short, long, default_value = "backup.forgebk")]
output: String,
/// Produce an incremental delta against a base archive instead of a
/// full snapshot. Refused if compaction bumped the epoch since the base.
#[arg(long)]
incremental: bool,
/// Base archive the incremental deltas from (required with
/// `--incremental`; may itself be an earlier incremental in the chain)
#[arg(long)]
base: Option<String>,
},
/// Restore a snapshot archive (or a base + incremental chain) into a data
/// directory. Pass the base first, then each incremental in order.
Restore {
/// Archive path(s) to restore. One full archive, or a base followed by
/// its incrementals in `sequence` order.
#[arg(required = true, num_args = 1..)]
archive: Vec<String>,
/// Destination data directory
#[arg(short, long, default_value = "data")]
output: String,
/// Replace an existing non-empty destination directory
#[arg(long)]
overwrite: bool,
},
/// List the contents of a snapshot archive without restoring it
List {
/// Archive path to inspect
archive: String,
/// Output as JSON
#[arg(long)]
json: bool,
},
}
fn run(cli: Cli) -> Result<()> {
// Wire the global -v/-q flags into the UI output level: --quiet suppresses
// everything but errors, --verbose unlocks detail lines.
ui::set_verbosity(cli.verbose, cli.quiet);
// Load generator config (--config path or auto-discover forgedb.toml).
// Commands that need config-derived defaults pull from this.
let forge_config = config::load_config(cli.config.as_deref())?;
match cli.command {
Commands::Init {
project_name,
template,
rust,
api_only,
} => commands::init::run(commands::init::InitOptions {
project_name,
template,
rust,
api_only,
}),
Commands::Generate {
target,
sdk,
runtime,
replica,
check,
output,
schema,
force,
from,
to,
} => {
// Precedence: CLI flag > config > built-in default
let resolved_output = output.or_else(|| forge_config.generate.output.clone());
let resolved_schema = schema.or_else(|| forge_config.generate.schema.clone());
// The `--sdk`/`--runtime`/`--replica` flags are a clap ArgGroup, so at
// most one is set — collapse them into the mode axis (#122).
let mode = if sdk {
Some(commands::generate::GenerateMode::Sdk)
} else if runtime {
Some(commands::generate::GenerateMode::Runtime)
} else if replica {
Some(commands::generate::GenerateMode::Replica)
} else {
None
};
// Generate-time runtime-behavior config (epic #126): resolve the
// schema-blind [runtime]/[storage] knobs into the codegen GenConfig
// baked into database.rs. An invalid knob value is a config error.
let gen_config = forge_config.gen_config()?;
commands::generate::run(commands::generate::GenerateOptions {
target,
mode,
check,
output: resolved_output,
schema: resolved_schema,
config_targets: forge_config.generate.targets.clone(),
gen_config,
force,
from,
to,
})
}
Commands::Validate {
strict,
schema_only,
implementations,
components,
schema,
} => {
let resolved_schema = schema.or_else(|| forge_config.generate.schema.clone());
commands::validate::run(commands::validate::ValidateOptions {
strict,
schema_only,
implementations,
components,
schema: resolved_schema,
})
}
Commands::Build {
release,
target,
output,
schema,
no_api,
} => {
let resolved_output = output.or_else(|| forge_config.generate.output.clone());
let resolved_schema = schema.or_else(|| forge_config.generate.schema.clone());
commands::build::run(commands::build::BuildOptions {
release,
target,
output: resolved_output,
schema: resolved_schema,
no_api,
})
}
Commands::Dev {
schema,
output,
debounce,
clear,
} => commands::dev::run(commands::dev::DevOptions {
schema,
output,
debounce,
clear,
}),
Commands::Migrate(migrate_cmd) => match migrate_cmd {
MigrateCommands::Create { description, auto, schema } => {
commands::migrate::create(commands::migrate::MigrateCreateOptions {
description,
schema,
auto,
})
}
MigrateCommands::Status => {
commands::migrate::status(commands::migrate::MigrateStatusOptions)
}
MigrateCommands::Build { from, to, output } => {
commands::migrate::build(commands::migrate::MigrateBuildOptions {
from,
to,
output,
})
}
MigrateCommands::Run { src, dest, bin_dir } => {
commands::migrate::run(commands::migrate::MigrateRunOptions {
src,
dest,
bin_dir,
})
}
MigrateCommands::Up {
from,
to,
src,
dest,
output,
tenant_root,
dest_suffix,
} => commands::migrate::up(commands::migrate::MigrateUpOptions {
from,
to,
src,
dest,
output,
tenant_root,
dest_suffix,
}),
},
Commands::Lsp { server_path, args } => {
commands::lsp::run(commands::lsp::LspOptions { server_path, args })
}
Commands::Coordinate {
root,
socket,
fsync,
fsync_interval,
turn_timeout,
max_frame_mib,
} => commands::coordinate::run(commands::coordinate::CoordinateOptions {
root,
socket,
fsync,
fsync_interval,
turn_timeout_secs: turn_timeout,
max_frame_mib,
}),
Commands::Compact(compact_cmd) => match compact_cmd {
CompactCommands::Run {
data_dir,
model,
all,
threshold,
} => commands::compact::compact(commands::compact::CompactOptions {
data_dir: data_dir.into(),
model,
all,
threshold,
}),
CompactCommands::Stats {
data_dir,
model,
json,
} => commands::compact::stats(commands::compact::StatsOptions {
data_dir: data_dir.into(),
model,
json,
}),
CompactCommands::Vacuum { data_dir } => {
commands::compact::vacuum(commands::compact::VacuumOptions {
data_dir: data_dir.into(),
})
}
CompactCommands::Analyze { data_dir, json } => {
commands::compact::analyze(commands::compact::AnalyzeOptions {
data_dir: data_dir.into(),
json,
})
}
},
Commands::Backup(backup_cmd) => match backup_cmd {
BackupCommands::Create {
data_dir,
output,
incremental,
base,
} => commands::backup::create(commands::backup::CreateOptions {
data_dir: data_dir.into(),
output: output.into(),
incremental,
base: base.map(Into::into),
}),
BackupCommands::Restore {
archive,
output,
overwrite,
} => commands::backup::restore(commands::backup::RestoreOptions {
archives: archive.into_iter().map(Into::into).collect(),
output: output.into(),
overwrite,
}),
BackupCommands::List { archive, json } => {
commands::backup::list(commands::backup::ListOptions {
archive: archive.into(),
json,
})
}
},
Commands::Tenant(tenant_cmd) => {
// Root precedence: --root flag > [tenant].root in config > ./data.
let default_root = forge_config.tenant.root();
let resolve = |root: Option<String>| {
root.map(std::path::PathBuf::from)
.unwrap_or_else(|| default_root.clone())
};
match tenant_cmd {
TenantCommands::Create { name, root } => {
commands::tenant::create(commands::tenant::CreateOptions {
name,
root: resolve(root),
auth_env: forge_config.auth.env_exports(),
})
}
TenantCommands::List { root, json } => {
commands::tenant::list(commands::tenant::ListOptions {
root: resolve(root),
json,
})
}
TenantCommands::Drop { name, root, force } => {
commands::tenant::drop(commands::tenant::DropOptions {
name,
root: resolve(root),
force,
})
}
}
}
}
}
fn main() {
let cli = Cli::parse();
if let Err(e) = run(cli) {
eprintln!("error: {e}");
std::process::exit(e.exit_code());
}
}