trusty-memory 0.1.45

Machine-wide, blazingly fast AI memory service
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
//! CLI module: clap derive structures and subcommand handlers.
//!
//! Why: Centralizes the project-aware command surface so `main.rs` only
//! parses + dispatches. Subcommand handlers live in their own files for
//! readability and to keep file sizes well under 800 lines.
//! What: Exports `Cli` (top-level parser), `Commands` enum (subcommands),
//! per-group enums (`PalaceCommands`, `KgCommands`, …), and handler modules.
//! Test: `cargo test --test integration_tests` plus `cargo build` covers
//! the parse surface; per-handler unit tests live in their own modules.

use clap::{Parser, Subcommand, ValueEnum};
use std::net::SocketAddr;
use std::path::PathBuf;

pub mod analytics;
pub mod backup;
pub mod bench;
pub mod chat;
pub mod config;
pub mod convert;
pub mod daemon_probe;
pub mod dashboard;
pub mod decay;
pub mod doctor;
pub mod dream;
pub mod git;
pub mod hooks;
pub mod kg;
pub mod kuzu;
pub mod memory;
pub mod output;
pub mod start;
pub mod stop;

pub use memory::{handle_forget, handle_list, handle_recall, handle_recall_all, handle_remember};
pub mod palace;
pub mod palace_resolver;
pub mod service;
pub mod setup;

#[derive(Parser)]
#[command(
    name = "trusty-memory",
    about = "Machine-wide AI memory service with Memory Palace architecture",
    version,
    propagate_version = true,
    after_help = "Examples:\n  trusty-memory remember \"Rust uses HNSW for vector search\"\n  trusty-memory recall \"vector store\"\n  trusty-memory palace list\n  trusty-memory git ingest\n  trusty-memory status"
)]
pub struct Cli {
    /// Active palace [default: inferred from current directory]
    #[arg(short = 'p', long, global = true, env = "TRUSTY_PALACE")]
    pub palace: Option<String>,

    /// Output as JSON
    #[arg(short = 'j', long, global = true)]
    pub json: bool,

    /// Disable ANSI color
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Suppress headers and decoration
    #[arg(short = 'q', long, global = true)]
    pub quiet: bool,

    /// Verbose logging (-v debug, -vv trace)
    #[arg(short = 'v', long, global = true, action = clap::ArgAction::Count)]
    pub verbose: u8,

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

#[derive(Subcommand)]
pub enum Commands {
    /// Store a memory in the active palace.
    #[command(
        after_help = "Examples:\n  trusty-memory remember \"Rust uses HNSW for vectors\"\n  trusty-memory remember \"API uses JWT\" --room backend --importance 0.8"
    )]
    Remember {
        /// Memory content to store
        text: String,
        /// Room type
        #[arg(short, long, default_value = "general")]
        room: String,
        /// Comma-separated tags
        #[arg(short, long, value_delimiter = ',')]
        tags: Vec<String>,
        /// Importance 0.0 - 1.0
        #[arg(short, long, default_value = "0.5")]
        importance: f32,
    },

    /// Recall memories matching a query (L0+L1+L2).
    #[command(
        after_help = "Examples:\n  trusty-memory recall \"vector store\"\n  trusty-memory recall \"auth\" --room backend --top-k 5\n  trusty-memory recall \"deployment\" --deep --json"
    )]
    Recall {
        /// Search query
        query: String,
        /// Max results
        #[arg(short = 'k', long, default_value = "10")]
        top_k: usize,
        /// Filter by room type
        #[arg(short, long)]
        room: Option<String>,
        /// Use L3 full-index deep search
        #[arg(short, long)]
        deep: bool,
        /// Apply temporal decay to scores
        #[arg(long, default_value = "true")]
        decay: bool,
        /// Fan out the query across every palace on this machine,
        /// merge the results, deduplicate by drawer id, and rank by
        /// score descending. When set, the positional `<palace>` /
        /// `--palace` argument is ignored.
        #[arg(short = 'a', long = "all-palaces")]
        all_palaces: bool,
    },

    /// Remove a memory by ID.
    Forget {
        /// Drawer UUID to remove
        id: String,
    },

    /// List recent memories in the active palace.
    #[command(
        after_help = "Examples:\n  trusty-memory list\n  trusty-memory list --room backend --limit 5 --sort importance"
    )]
    List {
        #[arg(short = 'k', long, default_value = "20")]
        limit: usize,
        #[arg(short, long)]
        room: Option<String>,
        /// Sort field: importance | created | accessed
        #[arg(long, default_value = "created")]
        sort: String,
    },

    /// Manage memory palaces.
    #[command(
        subcommand,
        after_help = "Examples:\n  trusty-memory palace list\n  trusty-memory palace new my-project\n  trusty-memory palace info"
    )]
    Palace(PalaceCommands),

    /// Knowledge graph operations.
    #[command(subcommand)]
    Kg(KgCommands),

    /// Git history integration (NLP-based, no inference).
    #[command(subcommand)]
    Git(GitCommands),

    /// kuzu-memory compatibility layer.
    #[command(subcommand)]
    Kuzu(KuzuCommands),

    /// Usage analytics (hit/miss tracking).
    #[command(subcommand)]
    Analytics(AnalyticsCommands),

    /// Temporal decay management.
    #[command(subcommand)]
    Decay(DecayCommands),

    /// Memory consolidation (background dreaming).
    #[command(subcommand)]
    Dream(DreamCommands),

    /// Start the MCP server.
    ///
    /// By default serves *only* the stdio MCP transport — the primary use is
    /// as a Claude Code MCP stdio server. Pass `--http` to additionally bind
    /// the HTTP+SSE admin server (optionally with an explicit address; defaults
    /// to `127.0.0.1:3031` when given without one). When HTTP is enabled the
    /// bound address is printed on startup and written to trusty-memory's
    /// data-dir discovery file so other commands can discover the daemon.
    #[command(
        after_help = "Examples:\n  trusty-memory serve                       # stdio MCP only (default)\n  trusty-memory serve --http                # also bind HTTP on 127.0.0.1:3031\n  trusty-memory serve --http 127.0.0.1:8080 # also bind HTTP on a specific address"
    )]
    Serve {
        /// Enable the HTTP+SSE admin server. Optional address; defaults to
        /// `127.0.0.1:3031` when the flag is given without one. Auto-increments
        /// the port on conflict (up to +20). Omit the flag for stdio-only mode.
        #[arg(
            long,
            value_name = "ADDR",
            num_args = 0..=1,
            default_missing_value = "127.0.0.1:3031"
        )]
        http: Option<SocketAddr>,
        /// stdio MCP mode (used by Claude Code hook)
        #[arg(long)]
        mcp: bool,
        /// Default palace for MCP tool calls. When omitted, the palace is
        /// auto-detected from the working directory (`.trusty-memory` marker
        /// file, or the cwd directory name). Auto-created on startup if it
        /// does not exist. Returned in the `initialize` response under
        /// `serverInfo.default_palace` so MCP clients can verify the namespace.
        #[arg(long, value_name = "NAME")]
        palace: Option<String>,
    },

    /// Manage the trusty-memory background service (macOS launchd).
    ///
    /// Installs a LaunchAgent plist so `trusty-memory serve` runs at login and
    /// is restarted on crash. No daemon wrapper — launchd owns the process
    /// lifecycle directly.
    #[command(
        subcommand,
        after_help = "Examples:\n  trusty-memory service install\n  trusty-memory service status\n  trusty-memory service logs\n  trusty-memory service uninstall"
    )]
    Service(ServiceCommands),

    /// Chat with an OpenRouter model using palace memory as context.
    #[command(
        after_help = "Examples:\n  trusty-memory chat \"what do you know about the auth system?\"\n  trusty-memory chat \"summarize today\" --remember\n  trusty-memory chat \"deploy steps\" --palace ops"
    )]
    Chat {
        /// Message to send to the model.
        message: String,
        /// Top-k drawers to include in the memory context.
        #[arg(short = 'k', long, default_value = "10")]
        top_k: usize,
        /// Persist the assistant response back into the palace.
        #[arg(long)]
        remember: bool,
    },

    /// Manage user configuration in `~/.trusty-memory/config.toml`.
    #[command(
        subcommand,
        after_help = "Examples:\n  trusty-memory config show\n  trusty-memory config set openrouter.api_key sk-or-..."
    )]
    Config(ConfigCommands),

    /// Machine setup wizard.
    Setup {
        #[arg(long)]
        non_interactive: bool,
        #[arg(long)]
        skip_migration: bool,
        #[arg(long)]
        migrate_only: bool,
    },

    /// Competitive retrieval benchmarking.
    #[command(subcommand)]
    Bench(BenchCommands),

    /// Convert memories from external sources (kuzu-memory, mempalace) into palaces.
    #[command(
        after_help = "Examples:\n  trusty-memory convert project\n  trusty-memory convert all --dry-run\n  trusty-memory convert project --source kuzu --palace my-app"
    )]
    Convert(ConvertArgs),

    /// Install/manage event hooks (git, Claude Code) for passive memory ingest.
    #[command(
        after_help = "Examples:\n  trusty-memory hooks install --git\n  trusty-memory hooks install --claude-code\n  trusty-memory hooks install --all\n  trusty-memory hooks list\n  trusty-memory hooks status"
    )]
    Hooks(hooks::HooksArgs),

    /// Back up a palace (or all palaces) to a `.tar.gz` archive.
    #[command(
        after_help = "Examples:\n  trusty-memory backup my-project\n  trusty-memory backup --all\n  trusty-memory backup my-project -o /tmp/my-project.tar.gz"
    )]
    Backup(backup::BackupArgs),

    /// Restore a palace from a `.tar.gz` archive.
    #[command(
        after_help = "Examples:\n  trusty-memory restore ./my-project-20260509.tar.gz\n  trusty-memory restore archive.tar.gz --palace renamed\n  trusty-memory restore archive.tar.gz --merge"
    )]
    Restore(backup::RestoreArgs),

    /// Show daemon health and palace summary.
    Status,

    /// Open the HTTP admin dashboard in your browser.
    #[command(
        alias = "dash",
        after_help = "Examples:\n  trusty-memory dashboard\n  trusty-memory dash\n\nRequires `trusty-memory serve` to be running (reads trusty-memory's data-dir discovery file)."
    )]
    Dashboard,

    /// Start the daemon in the background (detached process).
    ///
    /// If the daemon is already running, exits silently with status 0. Spawns
    /// `trusty-memory serve` with detached stdio, then polls the discovery file
    /// until the daemon reports its bound address (up to 5 s).
    #[command(
        after_help = "Examples:\n  trusty-memory start\n  trusty-memory start --http 127.0.0.1:3031"
    )]
    Start {
        /// HTTP bind address (forwarded to `serve`). Prefers 3031; auto-increments
        /// on conflict (up to +20).
        #[arg(long, value_name = "ADDR", default_value = "127.0.0.1:3031")]
        http: SocketAddr,
    },

    /// Stop the running background daemon.
    ///
    /// Reads the PID file written by `serve`, sends SIGTERM, then waits up to
    /// 5 s for the discovery file to disappear as a signal of clean shutdown.
    #[command(after_help = "Examples:\n  trusty-memory stop")]
    Stop,

    /// Diagnose daemon health, configuration, and palace registry.
    ///
    /// Runs a set of independent checks and prints ✓ / ⚠ / ✗ for each.
    /// Exit code 0 when all checks pass or only warnings; exit code 1 when
    /// any error is found.
    #[command(after_help = "Examples:\n  trusty-memory doctor")]
    Doctor,

    /// Generate shell completions.
    #[command(
        after_help = "Examples:\n  trusty-memory completions zsh > ~/.zsh/completions/_trusty-memory\n  trusty-memory completions bash > /etc/bash_completion.d/trusty-memory"
    )]
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
}

// ── Subcommand groups ────────────────────────────────────────────────────────

#[derive(Subcommand)]
pub enum PalaceCommands {
    /// List all palaces.
    List,
    /// Create a new palace.
    New {
        name: String,
        #[arg(long)]
        description: Option<String>,
    },
    /// Show palace details.
    Info { id: Option<String> },
    /// Delete a palace.
    Delete { name: String },
    /// Rename a palace.
    Rename { old: String, new: String },
    /// Remove orphaned vectors (vectors in the HNSW index with no
    /// corresponding drawer row) from a palace's index. See issue #49.
    Compact {
        /// Palace id to compact. If omitted, uses the active palace passed
        /// via `--palace`.
        name: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum KgCommands {
    /// Assert a fact (subject predicate object).
    Assert {
        subject: String,
        predicate: String,
        object: String,
        #[arg(long, default_value = "1.0")]
        confidence: f32,
        #[arg(long)]
        provenance: Option<String>,
    },
    /// Query active triples for a subject.
    Query { subject: String },
    /// Show full interval history for a subject.
    History { subject: String },
}

#[derive(Subcommand)]
pub enum GitCommands {
    /// Extract facts from git history.
    #[command(
        after_help = "Examples:\n  trusty-memory git ingest\n  trusty-memory git ingest /path/to/repo --limit 200 --since 2024-01-01"
    )]
    Ingest {
        /// Repository path [default: current directory]
        path: Option<PathBuf>,
        #[arg(long)]
        since: Option<String>,
        #[arg(long, default_value = "100")]
        limit: usize,
        /// Show what would be stored without storing
        #[arg(long)]
        dry_run: bool,
    },
    /// Watch for new commits and ingest automatically.
    Watch {
        path: Option<PathBuf>,
        #[arg(long, default_value = "300")]
        interval: u64,
    },
}

#[derive(Subcommand)]
pub enum KuzuCommands {
    /// Scan for kuzu-memory databases on this machine.
    Discover,
    /// Recall from a kuzu database.
    Recall {
        query: String,
        #[arg(long)]
        db: Option<PathBuf>,
    },
    /// Migrate kuzu databases to palaces.
    Migrate { db_path: Option<PathBuf> },
}

#[derive(Subcommand)]
pub enum AnalyticsCommands {
    /// Show recall summary.
    Show {
        #[arg(long, default_value = "7")]
        days: u32,
    },
    /// Top most-recalled drawers.
    Top {
        #[arg(short = 'k', long, default_value = "10")]
        limit: usize,
    },
}

#[derive(Subcommand)]
pub enum DecayCommands {
    /// Show drawers with largest importance gap.
    Report,
    /// Show/set decay configuration.
    Config,
}

#[derive(Subcommand)]
pub enum DreamCommands {
    /// Trigger a consolidation pass now.
    Run,
    /// Show last dream run stats.
    Status,
}

#[derive(Subcommand)]
pub enum ServiceCommands {
    /// Install and start the launchd service (macOS).
    Install,
    /// Stop and uninstall the launchd service (macOS).
    Uninstall,
    /// Show launchd status (PID, last exit code).
    Status,
    /// Print the last 50 lines of the service log.
    Logs,
}

#[derive(Subcommand)]
pub enum ConfigCommands {
    /// Print the resolved user configuration.
    Show,
    /// Set a dotted config key (e.g. `openrouter.api_key sk-or-...`).
    Set { key: String, value: String },
}

#[derive(Subcommand)]
pub enum BenchCommands {
    /// Compare retrieval quality across systems on a labeled corpus.
    #[command(
        after_help = "Examples:\n  trusty-memory bench compare\n  trusty-memory bench compare --mempalace --kuzu\n  trusty-memory bench compare --mempalace --json\n  trusty-memory bench compare --top-k 10"
    )]
    Compare(BenchCompareArgs),
}

#[derive(clap::Args, Debug, Clone)]
pub struct BenchCompareArgs {
    /// Path to JSONL corpus (documents + labeled queries).
    #[arg(long, default_value = "tests/fixtures/bench_corpus.jsonl")]
    pub corpus: PathBuf,

    /// K for Recall@K.
    #[arg(long, default_value = "5")]
    pub top_k: usize,

    /// Include mempalace (drives `mempalace-mcp` against a fresh palace).
    #[arg(long)]
    pub mempalace: bool,

    /// Include kuzu-memory (drives `kuzu-memory mcp` in a fresh project dir).
    #[arg(long)]
    pub kuzu: bool,

    /// Emit machine-readable JSON metrics instead of the formatted table.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for the `convert` subcommand.
///
/// Why: Migrates pre-existing memories (kuzu-memory DBs, mempalace WAL) into
/// trusty-memory palaces so users don't lose history when adopting the new
/// service.
/// What: Carries the scope (single project vs whole machine), source filter,
/// dry-run flag, and palace-name override.
/// Test: Parse coverage via clap; behavioral tests live in `convert.rs`.
#[derive(clap::Args, Debug, Clone)]
pub struct ConvertArgs {
    /// Scope: "project" (current dir) or "all" (whole machine).
    #[arg(value_enum)]
    pub scope: ConvertScope,

    /// Which source to convert from.
    #[arg(long, value_enum, default_value = "all")]
    pub source: ConvertSource,

    /// Dry run — print what would be imported without writing.
    #[arg(long)]
    pub dry_run: bool,

    /// Override palace name (project mode only).
    #[arg(long)]
    pub palace: Option<String>,
}

#[derive(ValueEnum, Clone, Debug)]
pub enum ConvertScope {
    Project,
    All,
}

#[derive(ValueEnum, Clone, Debug, PartialEq, Eq)]
pub enum ConvertSource {
    Kuzu,
    Mempalace,
    All,
}