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
mod audit;
mod backfill;
mod cli;
mod config;
mod epoch;
mod errors;
mod gitx;
mod governance;
mod index;
mod integrations;
mod mapview;
mod mcp;
mod memgraph;
mod parsers;
mod proptests;
mod records;
mod retrieval;
mod stats;
mod sync;
mod team;
use clap::{Parser, Subcommand};
use errors::code_of;
use std::path::PathBuf;
use std::process::ExitCode;
#[derive(Parser)]
#[command(
name = "memlay",
version,
about = "Repo-native shared memory and codebase navigation layer for AI coding agents"
)]
struct Cli {
/// Select a repository/worktree explicitly (default: discover from cwd)
#[arg(long, global = true)]
repo: Option<PathBuf>,
/// Stable structured JSON output
#[arg(long, global = true)]
json: bool,
/// Suppress non-essential output
#[arg(long, global = true)]
quiet: bool,
/// Verbose diagnostics to stderr
#[arg(long, global = true)]
verbose: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
enum Command {
/// Initialize memlay in the current Git repository
Init {
/// Skip the initial index
#[arg(long = "no-index", action = clap::ArgAction::SetTrue)]
no_index: bool,
/// Install Codex MCP config and AGENTS.md guidance
#[arg(long, overrides_with = "no_codex")]
codex: bool,
#[arg(long = "no-codex")]
no_codex: bool,
/// Install Claude Code MCP config, hooks, and CLAUDE.md guidance
#[arg(long, overrides_with = "no_claude")]
claude: bool,
#[arg(long = "no-claude")]
no_claude: bool,
/// Skip lifecycle hook installation
#[arg(long = "no-hooks")]
no_hooks: bool,
},
/// Ingest an agent lifecycle hook payload from stdin
#[command(subcommand)]
Hook(HookCommand),
/// Audit session operations
#[command(subcommand)]
Audit(AuditCommand),
/// Show repository, memory, and team-revision status
Status,
/// Print baseline/branch/working memory revisions and sync state
Revision,
/// Create a new immutable memory record
Record {
#[arg(long)]
key: Option<String>,
#[arg(long, default_value = "change")]
kind: String,
#[arg(long, default_value = "assert")]
op: String,
#[arg(long)]
summary: Option<String>,
#[arg(long)]
rationale: Option<String>,
#[arg(long = "detail")]
details: Vec<String>,
#[arg(long = "alternative")]
alternatives: Vec<String>,
#[arg(long = "consequence")]
consequences: Vec<String>,
/// Scope path (repeatable)
#[arg(long = "scope")]
scope: Vec<String>,
#[arg(long = "symbol")]
symbols: Vec<String>,
#[arg(long = "tag")]
tags: Vec<String>,
/// Evidence as `<type>:<value>` (repeatable)
#[arg(long = "evidence")]
evidence: Vec<String>,
#[arg(long = "supersede")]
supersedes: Vec<String>,
#[arg(long = "related")]
related: Vec<String>,
#[arg(long, default_value = "verified")]
confidence: String,
#[arg(long)]
agent: Option<String>,
#[arg(long)]
session: Option<String>,
#[arg(long)]
pr: Option<String>,
#[arg(long)]
issue: Option<String>,
/// Import a logical record from a JSON file ('-' for stdin)
#[arg(long = "from-json")]
from_json: Option<String>,
/// Import a record from an MRF (.mly) file ('-' for stdin)
#[arg(long = "from-mly")]
from_mly: Option<String>,
/// Write an editable change-record draft pre-filled from the diff
#[arg(long = "draft-from-diff")]
draft_from_diff: bool,
/// Base ref for --draft-from-diff (default: configured baseline)
#[arg(long)]
base: Option<String>,
/// Create the key even though a strong duplicate candidate exists
#[arg(long = "create-distinct")]
create_distinct: bool,
/// Required with --create-distinct: why this is a distinct concept
#[arg(long)]
justification: Option<String>,
},
/// Show all versions and supersession history for a key
History { key: String },
/// List semantic conflicts (keys with multiple current heads)
Conflicts,
/// Create a record that resolves a semantic conflict
Resolve {
key: String,
/// Head record ID to supersede (repeatable; default: all heads)
#[arg(long = "supersede")]
supersede: Vec<String>,
#[arg(long)]
summary: Option<String>,
#[arg(long)]
rationale: Option<String>,
},
/// Validate records, graphs, immutability, and configuration
Check {
/// Base ref for immutability checking (e.g. origin/main)
#[arg(long)]
base: Option<String>,
#[arg(long)]
ci: bool,
/// Require a change record covering changed source paths
#[arg(long = "require-change-record")]
require_change_record: bool,
},
/// Key governance: catalog, similarity, aliases, duplicate suspects
#[command(subcommand)]
Keys(KeysCommand),
/// Summarize branch memory changes for review
Diff {
#[arg(long, default_value = "refs/remotes/origin/main")]
base: String,
/// Output format: human or markdown
#[arg(long, default_value = "human")]
format: String,
},
/// Print the MRF grammar or logical JSON Schema
Schema {
/// What to print: record
#[arg(default_value = "record")]
what: String,
#[arg(long, default_value = "text")]
format: String,
},
/// Export all records as logical JSON
Export {
#[arg(long, default_value = "json")]
format: String,
},
/// Start the MCP server over STDIO (for Codex / Claude Code)
Mcp {
/// STDIO transport (required in P0)
#[arg(long)]
stdio: bool,
},
/// Whole-repository module map: orientation at minimal token cost
Map {
/// Token budget for the rendered map
#[arg(long, default_value = "800")]
budget: u32,
/// Module depth (path segments); deepens automatically when trivial
#[arg(long, default_value = "1")]
depth: usize,
/// Restrict the map to a directory
#[arg(long)]
scope: Option<String>,
},
/// Token-budgeted codebase and memory context for a task
Context {
task: String,
/// Token budget (default from config, min 200)
#[arg(long)]
budget: Option<u32>,
/// Restrict to a path or tag scope (repeatable)
#[arg(long = "scope")]
scope: Vec<String>,
/// Include scoring explanations
#[arg(long)]
explain: bool,
},
/// Expand selected refs (memory:<id>, key:<key>, symbol:<id>, file:<path>)
Expand {
refs: Vec<String>,
#[arg(long)]
budget: Option<u32>,
},
/// List records whose evidence no longer resolves
Stale {
/// Draft rename-aware repair records for stale evidence
#[arg(long = "suggest-fixes")]
suggest_fixes: bool,
},
/// Local usage statistics (offline, never transmitted)
Stats {
/// Clear collected statistics
#[arg(long)]
reset: bool,
},
/// Archive operations (P1; the epoch format contract is validated in P0)
Archive,
/// Bulk-import logical records from JSON ('-' for stdin)
Import {
#[arg(long, default_value = "json")]
format: String,
#[arg(default_value = "-")]
file: String,
},
/// Generate a human-readable memory view (never committed)
Docs {
/// Write to this directory instead of stdout
#[arg(long)]
out: Option<String>,
/// One file per top-level key namespace plus index.md (requires --out)
#[arg(long)]
split: bool,
},
/// Generate shell completions (bash, zsh, fish, powershell, elvish)
Completions { shell: clap_complete::Shell },
/// Fetch and index the configured team baseline (never merges or rebases)
Sync {
/// Verify freshness without fetching; nonzero exit when behind
#[arg(long)]
check: bool,
/// Fetch all remotes instead of only the baseline ref
#[arg(long)]
all: bool,
/// Skip the network fetch entirely
#[arg(long)]
offline: bool,
},
/// Local index operations
#[command(subcommand)]
Index(IndexCommand),
/// Mine Git history and ADR docs into reviewable draft records
Backfill {
#[command(subcommand)]
action: Option<BackfillCommand>,
/// Limit to commits reachable from this ref
#[arg(long)]
base: Option<String>,
/// History window, e.g. 2y, 6m, 12w, 90d
#[arg(long)]
since: Option<String>,
/// Also mine ADR/decision documents
#[arg(long = "include-docs")]
include_docs: bool,
},
/// Environment and installation health checks
Doctor,
}
#[derive(Subcommand)]
enum BackfillCommand {
/// List drafts from a backfill run (default: latest)
Review { run_id: Option<String> },
/// Apply reviewed drafts as canonical records (refuses TODO drafts)
Apply {
run_id: Option<String>,
/// Draft id prefix to apply (repeatable; default: all)
#[arg(long = "selected")]
selected: Vec<String>,
},
/// Discard drafts from a run
Reject {
run_id: Option<String>,
#[arg(long = "selected")]
selected: Vec<String>,
},
}
#[derive(Subcommand)]
enum HookCommand {
/// Read one hook payload from stdin and append it to the audit spool
Ingest {
#[arg(long, default_value = "generic")]
agent: String,
#[arg(long)]
event: Option<String>,
#[arg(long)]
session: Option<String>,
},
}
#[derive(Subcommand)]
enum AuditCommand {
/// List audit sessions (open spools and finalized bundles)
List,
/// Show one session summary; --events expands raw events
Show {
session: String,
#[arg(long)]
events: bool,
},
/// Finalize a session spool into a compressed bundle (and audit ref)
Finalize { session: String },
/// Push/fetch dedicated audit refs (never normal branches)
Sync,
}
#[derive(Subcommand)]
enum KeysCommand {
/// List canonical keys with aliases and current state
Catalog {
#[arg(long)]
scope: Option<String>,
},
/// Rank existing keys similar to a key or description
Similar { query: String },
/// Show one key: aliases, state, and all versions
Show { key: String },
/// List alias conflicts and suspected duplicate keys
Conflicts,
/// Map a divergent key to its canonical identity (simulates impact first)
Alias {
alias_key: String,
canonical_key: String,
#[arg(long)]
rationale: Option<String>,
/// Proceed even when fusion introduces a semantic conflict
#[arg(long = "confirm-conflicts")]
confirm_conflicts: bool,
},
}
#[derive(Subcommand)]
enum IndexCommand {
/// Incrementally reconcile the repository and records into the index
Update,
/// Safely rebuild the local index from scratch
Rebuild,
/// Show index statistics
Stats,
}
fn main() -> ExitCode {
let cli = Cli::parse();
if cli.verbose {
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "memlay=debug".into()),
)
.init();
}
let result = run(&cli);
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
let code = code_of(&e);
if cli.json {
eprintln!(
"{}",
serde_json::json!({ "error": { "code": code.as_str(), "message": e.to_string() } })
);
} else {
eprintln!("error: {e}");
}
ExitCode::FAILURE
}
}
}
fn run(cli: &Cli) -> anyhow::Result<()> {
let repo_arg = cli.repo.as_deref();
match &cli.command {
Command::Init {
no_index,
codex,
no_codex,
claude,
no_claude,
no_hooks,
} => {
let app = cli::App::open_uninitialized(repo_arg, cli.json, cli.quiet)?;
cli::init(&app, !*no_index)?;
// Default: install both unless explicitly disabled (PRD §15.2).
let do_codex = *codex || !*no_codex;
let do_claude = *claude || !*no_claude;
let report = integrations::install(&app, do_codex, do_claude, !*no_hooks)?;
if !report.changed.is_empty() && !cli.quiet && !cli.json {
println!("Integrations updated: {}", report.changed.join(", "));
}
Ok(())
}
Command::Hook(HookCommand::Ingest {
agent,
event,
session,
}) => audit::ingest(
&cli::App::open(repo_arg, cli.json, cli.quiet)?,
agent,
event.as_deref(),
session.as_deref(),
),
Command::Audit(sub) => {
let app = cli::App::open(repo_arg, cli.json, cli.quiet)?;
match sub {
AuditCommand::List => audit::list(&app),
AuditCommand::Show { session, events } => audit::show(&app, session, *events),
AuditCommand::Finalize { session } => audit::finalize(&app, session),
AuditCommand::Sync => audit::sync_refs(&app),
}
}
Command::Status => cli::status(&cli::App::open(repo_arg, cli.json, cli.quiet)?),
Command::Revision => cli::revision(&cli::App::open(repo_arg, cli.json, cli.quiet)?),
Command::Record {
key,
kind,
op,
summary,
rationale,
details,
alternatives,
consequences,
scope,
symbols,
tags,
evidence,
supersedes,
related,
confidence,
agent,
session,
pr,
issue,
from_json,
from_mly,
draft_from_diff,
base,
create_distinct,
justification,
} => {
let app = cli::App::open(repo_arg, cli.json, cli.quiet)?;
if *draft_from_diff {
let base_ref = base
.clone()
.unwrap_or_else(|| app.config.team.baseline_ref.clone());
return cli::draft_from_diff(&app, &base_ref);
}
cli::record(
&app,
cli::RecordArgs {
key: key.clone(),
kind: kind.clone(),
op: op.clone(),
summary: summary.clone(),
rationale: rationale.clone(),
details: details.clone(),
alternatives: alternatives.clone(),
consequences: consequences.clone(),
scope_paths: scope.clone(),
symbols: symbols.clone(),
tags: tags.clone(),
evidence: evidence.clone(),
supersedes: supersedes.clone(),
related: related.clone(),
confidence: confidence.clone(),
agent: agent.clone(),
session: session.clone(),
pr: pr.clone(),
issue: issue.clone(),
from_json: from_json.clone(),
from_mly: from_mly.clone(),
create_distinct: *create_distinct,
justification: justification.clone(),
},
)
}
Command::Keys(sub) => {
let app = cli::App::open(repo_arg, cli.json, cli.quiet)?;
match sub {
KeysCommand::Catalog { scope } => governance::keys_catalog(&app, scope.as_deref()),
KeysCommand::Similar { query } => governance::keys_similar(&app, query),
KeysCommand::Show { key } => governance::keys_show(&app, key),
KeysCommand::Conflicts => governance::keys_conflicts(&app),
KeysCommand::Alias {
alias_key,
canonical_key,
rationale,
confirm_conflicts,
} => governance::keys_alias(
&app,
alias_key,
canonical_key,
rationale.clone(),
*confirm_conflicts,
),
}
}
Command::Diff { base, format } => governance::diff(
&cli::App::open(repo_arg, cli.json, cli.quiet)?,
base,
format,
),
Command::History { key } => {
cli::history(&cli::App::open(repo_arg, cli.json, cli.quiet)?, key)
}
Command::Conflicts => cli::conflicts(&cli::App::open(repo_arg, cli.json, cli.quiet)?),
Command::Resolve {
key,
supersede,
summary,
rationale,
} => cli::resolve(
&cli::App::open(repo_arg, cli.json, cli.quiet)?,
key,
supersede.clone(),
summary.clone(),
rationale.clone(),
),
Command::Check {
base,
ci,
require_change_record,
} => cli::check(
&cli::App::open(repo_arg, cli.json, cli.quiet)?,
base.clone(),
*ci,
*require_change_record,
),
Command::Schema { what, format } => match what.as_str() {
"record" => cli::schema(format),
"epoch" => {
println!("{}", epoch::MLE_GRAMMAR_TEXT);
Ok(())
}
other => anyhow::bail!("unknown schema '{other}'; supported: record, epoch"),
},
Command::Export { format } => {
if format != "json" {
anyhow::bail!("unsupported export format '{format}'; supported: json");
}
cli::export_json(&cli::App::open(repo_arg, cli.json, cli.quiet)?)
}
Command::Mcp { stdio } => {
if !stdio {
anyhow::bail!("only --stdio transport is available in this release (HTTP is P1)");
}
mcp::serve(&cli::App::open(repo_arg, cli.json, cli.quiet)?)
}
Command::Map { budget, depth, scope } => {
let app = cli::App::open(repo_arg, cli.json, cli.quiet)?;
let index = index::update_all(&app.repo, &app.config)?;
let (loaded, _, layers) = app.load_memory()?;
let revisions =
team::compute_revisions(&app.repo, &app.config, &loaded.records, &layers)?;
if cli.json {
let modules = mapview::collect(&app.repo, &index, scope.as_deref(), *depth)?;
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"revisions": revisions,
"modules": modules.values().collect::<Vec<_>>(),
}))?
);
} else {
print!(
"{}",
mapview::render(
&app.repo,
&index,
&revisions,
scope.as_deref(),
*depth,
*budget
)?
);
}
Ok(())
}
Command::Context {
task,
budget,
scope,
explain,
} => cli::context(
&cli::App::open(repo_arg, cli.json, cli.quiet)?,
task,
*budget,
scope.clone(),
*explain,
),
Command::Expand { refs, budget } => cli::expand(
&cli::App::open(repo_arg, cli.json, cli.quiet)?,
refs.clone(),
*budget,
),
Command::Stale { suggest_fixes } => {
cli::stale(&cli::App::open(repo_arg, cli.json, cli.quiet)?, *suggest_fixes)
}
Command::Stats { reset } => {
stats::report(&cli::App::open(repo_arg, cli.json, cli.quiet)?, *reset)
}
Command::Archive => Err(errors::err(
errors::ErrorCode::P1NotImplemented,
"archive plan/create/verify/fetch are P1; this release validates the committed .mle epoch contract via 'memlay check' and 'memlay schema epoch'",
)),
Command::Import { format, file } => {
if format != "json" {
anyhow::bail!("unsupported import format '{format}'; supported: json");
}
cli::import_json(&cli::App::open(repo_arg, cli.json, cli.quiet)?, file)
}
Command::Docs { out, split } => cli::docs(
&cli::App::open(repo_arg, cli.json, cli.quiet)?,
out.as_deref(),
*split,
),
Command::Completions { shell } => {
use clap::CommandFactory as _;
clap_complete::generate(
*shell,
&mut Cli::command(),
"memlay",
&mut std::io::stdout(),
);
Ok(())
}
Command::Sync {
check,
all,
offline,
} => {
let app = cli::App::open(repo_arg, cli.json, cli.quiet)?;
sync::sync(&app, *check, *all, *offline)
}
Command::Backfill {
action,
base,
since,
include_docs,
} => {
let app = cli::App::open(repo_arg, cli.json, cli.quiet)?;
match action {
Some(BackfillCommand::Review { run_id }) => {
backfill::review(&app, run_id.as_deref())
}
Some(BackfillCommand::Apply { run_id, selected }) => {
backfill::apply(&app, run_id.as_deref(), selected)
}
Some(BackfillCommand::Reject { run_id, selected }) => {
backfill::reject(&app, run_id.as_deref(), selected)
}
None => backfill::run(
&app,
&backfill::BackfillArgs {
base: base.clone(),
since: since.clone(),
include_docs: *include_docs,
},
),
}
}
Command::Doctor => cli::doctor(&cli::App::open(repo_arg, cli.json, cli.quiet)?),
Command::Index(sub) => {
let app = cli::App::open(repo_arg, cli.json, cli.quiet)?;
match sub {
IndexCommand::Update => {
let index = sync::index_update(&app)?;
let stats = index.stats()?;
if cli.json {
println!("{}", serde_json::to_string_pretty(&stats)?);
} else if !cli.quiet {
println!(
"index updated: {} files, {} symbols, {} records",
stats.files, stats.symbols, stats.records
);
}
Ok(())
}
IndexCommand::Rebuild => {
index::Index::rebuild(&app.repo)?;
let index = sync::index_update(&app)?;
index.integrity_check()?;
if !cli.quiet && !cli.json {
println!("index rebuilt");
}
Ok(())
}
IndexCommand::Stats => {
let index = index::Index::open(&app.repo)?;
let stats = index.stats()?;
if cli.json {
println!("{}", serde_json::to_string_pretty(&stats)?);
} else {
println!("files {}", stats.files);
println!("symbols {}", stats.symbols);
println!("records {}", stats.records);
println!("current keys {}", stats.heads);
println!("conflicts {}", stats.conflicts);
println!("parse failures {}", stats.parse_failures);
println!("db size {} bytes", stats.db_bytes);
for (lang, n) in &stats.languages {
println!(" {lang:<12} {n}");
}
}
Ok(())
}
}
}
}
}