cortex-memory 0.3.1

Self-organizing graph memory for AI agents. Single binary, zero dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
pub mod agent;
pub mod audit;
pub mod backup;
pub mod briefing;
pub mod config_cmd;
pub mod doctor;
pub mod edge;
pub mod export;
pub mod import;
pub mod init;
pub mod migrate;
pub mod node;
pub mod prompt;
pub mod search;
pub mod security;
pub mod shell;
pub mod stats;
pub mod traverse;
pub mod trust;

use clap::{Args, Parser, Subcommand};
use std::path::PathBuf;

#[derive(Parser, Debug)]
#[command(name = "cortex")]
#[command(version, about = "Self-organizing graph memory for AI agents")]
pub struct Cli {
    /// Path to cortex.toml
    #[arg(
        long,
        global = true,
        env = "CORTEX_CONFIG",
        default_value = "cortex.toml"
    )]
    pub config: PathBuf,

    /// Path to data directory (overrides config file)
    #[arg(long, global = true, env = "CORTEX_DATA_DIR")]
    pub data_dir: Option<PathBuf>,

    /// Cortex server address for client commands
    #[arg(
        long,
        global = true,
        env = "CORTEX_ADDR",
        default_value = "http://localhost:9090"
    )]
    pub server: String,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Start the gRPC + HTTP server
    Serve,
    /// Interactive setup wizard
    Init(InitArgs),
    /// Interactive REPL
    Shell,
    /// Node operations
    #[command(subcommand)]
    Node(NodeCommands),
    /// Edge operations
    #[command(subcommand)]
    Edge(EdgeCommands),
    /// Search the graph
    Search(SearchArgs),
    /// Graph traversal from a node
    Traverse(TraverseArgs),
    /// Find shortest path between two nodes
    Path(PathArgs),
    /// Generate a context briefing
    Briefing(BriefingArgs),
    /// Import data into the graph
    Import(ImportArgs),
    /// Export graph data
    Export(ExportArgs),
    /// Back up the database
    Backup(BackupArgs),
    /// Restore from backup
    Restore(RestoreArgs),
    /// Run schema migrations
    Migrate,
    /// Graph statistics
    Stats,
    /// Diagnose issues
    Doctor,
    /// Configuration commands
    #[command(subcommand)]
    Config(ConfigCommands),
    /// Query the audit log
    Audit(AuditArgs),
    /// Security utilities (key generation, etc.)
    #[command(subcommand)]
    Security(SecurityCommands),
    /// Start an MCP server (stdio transport for AI agent integration)
    Mcp(McpArgs),
    /// Agent ↔ prompt binding management
    #[command(subcommand)]
    Agent(AgentCommands),
    /// Prompt versioning, branching, and migration (PromptForge integration)
    #[command(subcommand)]
    Prompt(PromptCommands),
    /// Show trust scores for nodes or agents
    Trust(TrustArgs),
}

// --- Trust args ---

#[derive(Args, Debug)]
pub struct TrustArgs {
    /// Node ID to score (omit to show agent reliabilities)
    pub id: Option<String>,
    /// Show trust score for an agent instead of a node
    #[arg(long)]
    pub agent: Option<String>,
    /// Output format: table (default), json
    #[arg(long, default_value = "table")]
    pub format: String,
}

// --- Init args ---

#[derive(Args, Debug)]
pub struct InitArgs {
    /// Agent template: default, coding, research, browser
    #[arg(long)]
    pub template: Option<String>,
}

// --- MCP args ---

#[derive(Args, Debug)]
pub struct McpArgs {
    /// Path to cortex data directory. Defaults to ~/.cortex/default or the global --data-dir.
    #[arg(long)]
    pub data_dir: Option<PathBuf>,

    /// Connect to a running Cortex server via gRPC instead of opening the database directly.
    #[arg(long)]
    pub server: Option<String>,
}

#[derive(Subcommand, Debug)]
pub enum NodeCommands {
    Create(NodeCreateArgs),
    Get(NodeGetArgs),
    List(NodeListArgs),
    Delete(NodeDeleteArgs),
    /// Show access-tracking stats for a node (access count, last accessed, decay info)
    Stats(NodeStatsArgs),
}

#[derive(Subcommand, Debug)]
pub enum EdgeCommands {
    Create(EdgeCreateArgs),
    List(EdgeListArgs),
}

#[derive(Subcommand, Debug)]
pub enum ConfigCommands {
    Validate,
    Show,
}

#[derive(Subcommand, Debug)]
pub enum SecurityCommands {
    /// Generate a new 256-bit AES encryption key
    GenerateKey,
}

// --- Agent args ---

#[derive(Subcommand, Debug)]
pub enum AgentCommands {
    /// List all agent nodes
    List(AgentListArgs),
    /// Show prompts bound to an agent
    Show(AgentShowArgs),
    /// Bind (or update weight of) a prompt to an agent
    Bind(AgentBindArgs),
    /// Unbind a prompt from an agent
    Unbind(AgentUnbindArgs),
    /// Show the fully resolved effective prompt for an agent
    Resolve(AgentResolveArgs),
    /// Select the best prompt variant for the current context (epsilon-greedy)
    Select(AgentSelectArgs),
    /// Show variant swap and performance history
    History(AgentHistoryArgs),
    /// Record a performance observation and update edge weights
    Observe(AgentObserveArgs),
}

#[derive(Args, Debug)]
pub struct AgentListArgs {
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct AgentShowArgs {
    /// Agent name (title of the agent node)
    pub name: String,
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct AgentBindArgs {
    /// Agent name
    pub name: String,
    /// Prompt slug (title of the prompt node)
    pub slug: String,
    /// Edge weight [0.0–1.0]; higher = more important
    #[arg(long, default_value = "1.0")]
    pub weight: f32,
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct AgentUnbindArgs {
    /// Agent name
    pub name: String,
    /// Prompt slug
    pub slug: String,
}

#[derive(Args, Debug)]
pub struct AgentResolveArgs {
    /// Agent name
    pub name: String,
    /// Output format: text (default) | json
    #[arg(long, default_value = "text")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct AgentSelectArgs {
    /// Agent name
    pub name: String,
    /// User sentiment: 0.0 (frustrated) – 1.0 (pleased)
    #[arg(long, default_value = "0.5")]
    pub sentiment: f32,
    /// Task type: coding | planning | casual | crisis | reflection
    #[arg(long, default_value = "casual")]
    pub task_type: String,
    /// Correction rate (0.0–1.0)
    #[arg(long, default_value = "0.0")]
    pub correction_rate: f32,
    /// Topic shift from conversation start (0.0–1.0)
    #[arg(long, default_value = "0.0")]
    pub topic_shift: f32,
    /// User energy proxy (0.0–1.0)
    #[arg(long, default_value = "0.5")]
    pub energy: f32,
    /// Exploration rate for epsilon-greedy (0.0 = always exploit)
    #[arg(long, default_value = "0.2")]
    pub epsilon: f32,
    /// Output format: table (default) | json
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct AgentHistoryArgs {
    /// Agent name
    pub name: String,
    /// Maximum number of history entries to show
    #[arg(long, default_value = "20")]
    pub limit: usize,
    /// Output format: table (default) | json
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct AgentObserveArgs {
    /// Agent name
    pub name: String,
    /// UUID of the prompt variant node that was active
    #[arg(long)]
    pub variant_id: String,
    /// Slug of the prompt variant (for display)
    #[arg(long)]
    pub variant_slug: String,
    /// Observed sentiment score: 0.0–1.0
    #[arg(long, default_value = "0.5")]
    pub sentiment_score: f32,
    /// Number of corrections the user made
    #[arg(long, default_value = "0")]
    pub correction_count: u32,
    /// Task outcome: success | partial | failure | unknown
    #[arg(long, default_value = "unknown")]
    pub task_outcome: String,
    /// Token cost of the interaction
    #[arg(long)]
    pub token_cost: Option<u32>,
}

// --- Prompt args ---

#[derive(Subcommand, Debug)]
pub enum PromptCommands {
    /// List all prompts (HEAD of each slug+branch)
    List(PromptListArgs),
    /// Show a prompt (resolved with inheritance by default)
    Get(PromptGetArgs),
    /// Import prompts from a migration JSON file
    Migrate(PromptMigrateArgs),
    /// Show aggregate performance metrics for a prompt variant
    Performance(PromptPerformanceArgs),
    /// Record a deployment and snapshot baseline metrics for rollback monitoring
    Deploy(PromptDeployArgs),
    /// Show rollback status, cooldown, and quarantine state for a prompt
    RollbackStatus(PromptRollbackStatusArgs),
    /// Remove quarantine from a prompt version (allows re-evaluation)
    Unquarantine(PromptUnquarantineArgs),
}

#[derive(Args, Debug)]
pub struct PromptListArgs {
    /// Filter by branch
    #[arg(long)]
    pub branch: Option<String>,
    /// Output format: table (default) | json
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct PromptGetArgs {
    /// Prompt slug
    pub slug: String,
    /// Branch (default: main)
    #[arg(long)]
    pub branch: Option<String>,
    /// Specific version number (omit for HEAD)
    #[arg(long)]
    pub version: Option<u32>,
    /// Output format: table (default) | json
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct PromptMigrateArgs {
    /// Path to migration JSON file
    pub file: std::path::PathBuf,
    /// Preview without writing to the database
    #[arg(long)]
    pub dry_run: bool,
}

#[derive(Args, Debug)]
pub struct PromptPerformanceArgs {
    /// Prompt slug
    pub slug: String,
    /// Maximum observations to include
    #[arg(long, default_value = "50")]
    pub limit: usize,
    /// Output format: table (default) | json
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct PromptDeployArgs {
    /// Prompt slug to deploy
    pub slug: String,
    /// Branch (default: main)
    #[arg(long, default_value = "main")]
    pub branch: String,
    /// Agent name responsible for this deployment
    #[arg(long)]
    pub agent_name: String,
    /// Number of recent observations to use for baseline (default: 20)
    #[arg(long, default_value = "20")]
    pub baseline_sample_size: usize,
    /// Output format: table (default) | json
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct PromptRollbackStatusArgs {
    /// Prompt slug
    pub slug: String,
    /// Branch (default: main)
    #[arg(long, default_value = "main")]
    pub branch: String,
    /// Output format: table (default) | json
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct PromptUnquarantineArgs {
    /// Prompt slug
    pub slug: String,
    /// Branch (default: main)
    #[arg(long, default_value = "main")]
    pub branch: String,
}

// --- Audit args ---

#[derive(Args, Debug)]
pub struct AuditArgs {
    /// Only show entries since this duration (e.g. "24h", "7d", "1h30m")
    #[arg(long)]
    pub since: Option<String>,
    /// Filter by node/edge ID
    #[arg(long)]
    pub node: Option<String>,
    /// Filter by actor name (e.g. "kai", "auto-linker")
    #[arg(long)]
    pub actor: Option<String>,
    /// Output format: table (default) | json
    #[arg(long, default_value = "table")]
    pub format: String,
    /// Maximum number of entries to return
    #[arg(long, default_value = "100")]
    pub limit: usize,
}

// --- Node args ---

#[derive(Args, Debug)]
pub struct NodeCreateArgs {
    #[arg(long)]
    pub kind: String,
    #[arg(long)]
    pub title: String,
    #[arg(long)]
    pub body: Option<String>,
    #[arg(long, default_value = "0.5")]
    pub importance: f32,
    #[arg(long, value_delimiter = ',')]
    pub tags: Vec<String>,
    /// Read body from stdin
    #[arg(long)]
    pub stdin: bool,
    /// JSON metadata (e.g. '{"entity_type": "company", "source_url": "https://..."}')
    #[arg(long)]
    pub metadata: Option<String>,
    /// When this fact became true (ISO 8601)
    #[arg(long)]
    pub valid_from: Option<String>,
    /// When this fact stopped being true (ISO 8601)
    #[arg(long)]
    pub valid_until: Option<String>,
    /// When to auto-delete this node (ISO 8601)
    #[arg(long)]
    pub expires_at: Option<String>,
    /// Print warnings if metadata doesn't follow conventions (still creates the node)
    #[arg(long)]
    pub check_conventions: bool,
    /// Output format: table (default), json
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct NodeGetArgs {
    pub id: String,
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct NodeListArgs {
    #[arg(long)]
    pub kind: Option<String>,
    #[arg(long, default_value = "20")]
    pub limit: u32,
    #[arg(long)]
    pub source: Option<String>,
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct NodeDeleteArgs {
    pub id: String,
    /// Skip confirmation prompt
    #[arg(long, short = 'y')]
    pub yes: bool,
}

#[derive(Args, Debug)]
pub struct NodeStatsArgs {
    pub id: String,
    #[arg(long, default_value = "table")]
    pub format: String,
}

// --- Edge args ---

#[derive(Args, Debug)]
pub struct EdgeCreateArgs {
    #[arg(long)]
    pub from: String,
    #[arg(long)]
    pub to: String,
    #[arg(long)]
    pub relation: String,
    #[arg(long, default_value = "1.0")]
    pub weight: f32,
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct EdgeListArgs {
    #[arg(long)]
    pub node: String,
    /// "outgoing", "incoming", "both"
    #[arg(long, default_value = "both")]
    pub direction: String,
    #[arg(long, default_value = "table")]
    pub format: String,
}

// --- Search args ---

#[derive(Args, Debug)]
pub struct SearchArgs {
    pub query: String,
    #[arg(long, default_value = "10")]
    pub limit: u32,
    /// Hybrid search (vector + graph)
    #[arg(long)]
    pub hybrid: bool,
    #[arg(long, default_value = "table")]
    pub format: String,
}

// --- Traverse / Path args ---

#[derive(Args, Debug)]
pub struct TraverseArgs {
    pub id: String,
    #[arg(long, default_value = "2")]
    pub depth: u32,
    /// "outgoing", "incoming", "both"
    #[arg(long, default_value = "both")]
    pub direction: String,
    #[arg(long)]
    pub relation: Option<String>,
    #[arg(long, default_value = "table")]
    pub format: String,
}

#[derive(Args, Debug)]
pub struct PathArgs {
    pub from: String,
    pub to: String,
    #[arg(long, default_value = "5")]
    pub max_hops: u32,
    #[arg(long, default_value = "table")]
    pub format: String,
}

// --- Briefing args ---

#[derive(Args, Debug)]
pub struct BriefingArgs {
    /// Agent ID (required unless --agents is used for unified scope)
    #[arg(default_value = "")]
    pub agent_id: String,
    #[arg(long)]
    pub compact: bool,
    /// "text", "json", "markdown"
    #[arg(long, default_value = "text")]
    pub format: String,
    #[arg(long)]
    pub no_cache: bool,
    /// Scope: "agent" (default), "shared"
    #[arg(long, default_value = "agent")]
    pub scope: String,
    /// Comma-separated agent IDs for unified scope (e.g. --agents kai,scout,lily)
    #[arg(long)]
    pub agents: Option<String>,
}

// --- Import args ---

#[derive(Args, Debug)]
pub struct ImportArgs {
    pub file: PathBuf,
    /// "json", "jsonl", "csv", "markdown" — auto-detected if omitted
    #[arg(long)]
    pub format: Option<String>,
    #[arg(long, default_value = "import")]
    pub source: String,
    #[arg(long)]
    pub dry_run: bool,
}

// --- Export args ---

#[derive(Args, Debug)]
pub struct ExportArgs {
    #[arg(long)]
    pub output: Option<PathBuf>,
    /// "json", "jsonl", "dot", "graphml"
    #[arg(long, default_value = "json")]
    pub format: String,
    #[arg(long)]
    pub kind: Option<String>,
}

// --- Backup / Restore args ---

#[derive(Args, Debug)]
pub struct BackupArgs {
    pub path: PathBuf,
    #[arg(long)]
    pub encrypt: bool,
}

#[derive(Args, Debug)]
pub struct RestoreArgs {
    pub path: PathBuf,
    #[arg(long, short = 'y')]
    pub yes: bool,
}

// --- gRPC client helper ---

use cortex_proto::cortex_service_client::CortexServiceClient;
use tonic::transport::Channel;

pub async fn grpc_connect(server: &str) -> anyhow::Result<CortexServiceClient<Channel>> {
    CortexServiceClient::connect(server.to_string())
        .await
        .map_err(|e| {
            anyhow::anyhow!(
                "Failed to connect to Cortex server at {}: {}\nIs `cortex serve` running?",
                server,
                e
            )
        })
}

// --- Table printing helpers ---

pub fn print_node_table(nodes: &[cortex_proto::NodeResponse]) {
    if nodes.is_empty() {
        println!("(no results)");
        return;
    }
    println!("{:<36}  {:<12}  {:<6}  TITLE", "ID", "KIND", "IMP");
    println!("{}", "".repeat(80));
    for n in nodes {
        let title = truncate(&n.title, 40);
        println!(
            "{:<36}  {:<12}  {:<6.2}  {}",
            n.id, n.kind, n.importance, title
        );
    }
}

pub fn print_edge_table(edges: &[cortex_proto::EdgeResponse]) {
    if edges.is_empty() {
        println!("(no edges)");
        return;
    }
    println!(
        "{:<36}  {:<36}  {:<20}  {:<5}",
        "FROM", "TO", "RELATION", "WEIGHT"
    );
    println!("{}", "".repeat(100));
    for e in edges {
        println!(
            "{:<36}  {:<36}  {:<20}  {:<5.2}",
            e.from_id, e.to_id, e.relation, e.weight
        );
    }
}

pub fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        format!("{}", s.chars().take(max - 1).collect::<String>())
    }
}