memd 1.9.0

Local memory CLI for AI agents with hybrid retrieval
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
use std::path::{Path, PathBuf};

use serde_json::{Map, Value};

use super::args::{CliCommand, ProjectScopeConfig};
use crate::error::{MemdError, Result};

#[derive(Default)]
pub(super) struct OperationScopeCache {
    loaded: bool,
    scope: Option<ProjectScopeConfig>,
    error: Option<String>,
}

impl OperationScopeCache {
    pub(super) fn disabled() -> Self {
        Self {
            loaded: true,
            scope: None,
            error: None,
        }
    }
}

pub(super) fn find_project_scope(start: &Path) -> Result<Option<ProjectScopeConfig>> {
    let home = std::env::var_os("HOME").map(PathBuf::from);
    let mut current = start.to_path_buf();

    for _ in 0..64 {
        let scope_path = current.join(".memd").join("project_scope.json");
        let text = match std::fs::read_to_string(&scope_path) {
            Ok(text) => text,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                if home.as_deref().is_some_and(|home| current == home) {
                    break;
                }
                if !current.pop() {
                    break;
                }
                continue;
            }
            Err(error) => {
                return Err(MemdError::ValidationError(format!(
                "unable to read {}: {error}; fix its permissions or pass --tenant-id explicitly",
                scope_path.display()
            )))
            }
        };
        // A scope file that exists but cannot be read or parsed must stop the
        // walk: silently falling through to a parent scope would route
        // flagless writes into the wrong tenant/project.
        return serde_json::from_str::<ProjectScopeConfig>(&text)
            .map(Some)
            .map_err(|err| {
                MemdError::ValidationError(format!(
                    "malformed {}: {err}; repair this scope file or run memd init with explicit --tenant-id and --project-id for {}",
                    scope_path.display(),
                    current.display()
                ))
            });
    }

    Ok(None)
}

fn scope_missing_error(cwd: &Path) -> MemdError {
    MemdError::ValidationError(format!(
        "no --tenant-id given and no .memd/project_scope.json found upward from {}; run: memd session-start --project-dir . (or pass --tenant-id)",
        cwd.display()
    ))
}

pub(super) fn resolve_required(
    start: &Path,
    tenant: Option<String>,
    project: Option<String>,
) -> Result<(String, Option<String>)> {
    // The scope file is consulted only when --tenant-id is absent. An explicit
    // tenant targets that tenant directly; we never borrow the scope's
    // project_id for a different (or even the same) explicitly named tenant,
    // because that silently narrows broad lookups to an unrelated project.
    if let Some(tenant_id) = tenant {
        return Ok((tenant_id, project));
    }
    let scope = find_project_scope(start)?;
    let tenant_id = scope
        .as_ref()
        .map(|scope| scope.tenant_id.clone())
        .ok_or_else(|| scope_missing_error(start))?;
    let project_id = project.or_else(|| scope.and_then(|scope| scope.project_id));
    Ok((tenant_id, project_id))
}

pub(super) fn resolve_optional(
    start: &Path,
    tenant: Option<String>,
    project: Option<String>,
) -> Result<(Option<String>, Option<String>)> {
    // Same unit semantics as resolve_required: an explicit tenant suppresses
    // scope-file lookup so it never inherits an unrelated project_id.
    if let Some(tenant_id) = tenant {
        return Ok((Some(tenant_id), project));
    }
    let scope = find_project_scope(start)?;
    let tenant_id = scope.as_ref().map(|scope| scope.tenant_id.clone());
    let project_id = project.or_else(|| scope.and_then(|scope| scope.project_id));
    Ok((tenant_id, project_id))
}

pub(super) fn require_tenant(tenant: Option<String>) -> Result<String> {
    tenant.ok_or_else(|| scope_missing_error(&current_dir()))
}

fn current_dir() -> PathBuf {
    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}

pub(super) fn apply_operation_scope(
    arguments: Value,
    cache: &mut OperationScopeCache,
) -> Result<Value> {
    apply_operation_scope_at(&current_dir(), arguments, cache)
}

pub(super) fn apply_operation_scope_at(
    start: &Path,
    arguments: Value,
    cache: &mut OperationScopeCache,
) -> Result<Value> {
    if arguments
        .as_object()
        .and_then(|object| object.get("tenant_id"))
        .is_some_and(|tenant_id| !tenant_id.is_null())
    {
        // An explicit tenant must not inherit the repository project, matching
        // the typed CLI's cross-project footgun guard.
        return Ok(arguments);
    }

    if !cache.loaded {
        cache.loaded = true;
        match find_project_scope(start) {
            Ok(scope) => cache.scope = scope,
            Err(error) => {
                cache.error = Some(match &error {
                    MemdError::ValidationError(message) => message.clone(),
                    _ => error.to_string(),
                });
                return Err(error);
            }
        }
    }
    if let Some(error) = cache.error.as_ref() {
        return Err(MemdError::ValidationError(error.clone()));
    }
    let Some(scope) = cache.scope.as_ref() else {
        return Ok(arguments);
    };

    let mut object = match arguments {
        Value::Object(object) => object,
        Value::Null => Map::new(),
        _ => {
            return Err(MemdError::ValidationError(
                "operation arguments must be a JSON object".to_string(),
            ))
        }
    };
    object.insert(
        "tenant_id".to_string(),
        Value::String(scope.tenant_id.clone()),
    );
    if !object.contains_key("project_id") {
        if let Some(project_id) = scope.project_id.as_ref() {
            object.insert("project_id".to_string(), Value::String(project_id.clone()));
        }
    }
    Ok(Value::Object(object))
}

pub fn resolve_command_scope(cmd: &mut CliCommand) -> Result<()> {
    let cwd = current_dir();
    match cmd {
        CliCommand::Experience {
            tenant_id,
            project_id,
            ..
        }
        | CliCommand::Add {
            tenant_id,
            project_id,
            ..
        }
        | CliCommand::Search {
            tenant_id,
            project_id,
            ..
        }
        | CliCommand::AgentContext {
            tenant_id,
            project_id,
            ..
        }
        | CliCommand::ExportMarkdown {
            tenant_id,
            project_id,
            ..
        }
        | CliCommand::ExportOmf {
            tenant_id,
            project_id,
            ..
        } => {
            let (resolved_tenant, resolved_project) =
                resolve_required(&cwd, tenant_id.take(), project_id.take())?;
            *tenant_id = Some(resolved_tenant);
            *project_id = resolved_project;
        }
        CliCommand::Get { tenant_id, .. }
        | CliCommand::Delete { tenant_id, .. }
        | CliCommand::Outcome { tenant_id, .. }
        | CliCommand::Stats { tenant_id }
        | CliCommand::Export { tenant_id, .. }
        | CliCommand::ImportOmf { tenant_id, .. } => {
            let (resolved_tenant, _) = resolve_required(&cwd, tenant_id.take(), None)?;
            *tenant_id = Some(resolved_tenant);
        }
        CliCommand::Audit {
            tenant_id,
            project_id,
            ..
        }
        | CliCommand::Report {
            tenant_id,
            project_id,
            ..
        }
        | CliCommand::ConsolidateReview {
            tenant_id,
            project_id,
            ..
        } => {
            let (resolved_tenant, resolved_project) =
                resolve_optional(&cwd, tenant_id.take(), project_id.take())?;
            *tenant_id = resolved_tenant;
            *project_id = resolved_project;
        }
        _ => {}
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::{CliQueryMode, ExportFormat, SearchReranker, WarmMode};

    #[test]
    fn resolve_required_fills_search_scope_from_file() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(
            dir.path().join(".memd/project_scope.json"),
            r#"{
              "tenant_id": "scoped_tenant",
              "project_id": "scoped_project",
              "read_tenants": ["scoped_tenant"],
              "interface": "cli",
              "cli_command": "memd",
              "agent_context_output": ".memd/context.md",
              "project_dir": "."
            }"#,
        )
        .unwrap();

        let cmd = CliCommand::Search {
            tenant_id: None,
            query: Some("scope fallback".to_string()),
            query_positional: None,
            k: 2,
            project_id: None,
            task_id: None,
            thread_id: None,
            compact: false,
            dedupe_by_source: false,
            token_budget: None,
            mode: CliQueryMode::Generic,
            no_text: false,
            include_artifact: false,
            include_superseded: false,
            format: ExportFormat::Json,
            output: None,
            reranker: SearchReranker::None,
            reranker_model: "model".to_string(),
            reranker_device: "cpu".to_string(),
            reranker_batch_size: 1,
            reranker_timeout_seconds: 1,
            reranker_python: "python3".to_string(),
            warm: WarmMode::Off,
        };

        let (tenant_id, project_id) = match cmd {
            CliCommand::Search {
                tenant_id,
                project_id,
                ..
            } => resolve_required(dir.path(), tenant_id, project_id).unwrap(),
            _ => panic!("unexpected command"),
        };
        assert_eq!(tenant_id, "scoped_tenant");
        assert_eq!(project_id.as_deref(), Some("scoped_project"));
    }

    #[test]
    fn resolve_required_explicit_tenant_does_not_borrow_scope_project() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(
            dir.path().join(".memd/project_scope.json"),
            r#"{
              "tenant_id": "scoped_tenant",
              "project_id": "scoped_project",
              "read_tenants": ["scoped_tenant"],
              "interface": "cli",
              "cli_command": "memd",
              "agent_context_output": ".memd/context.md",
              "project_dir": "."
            }"#,
        )
        .unwrap();

        // Explicit tenant, no project: the scope file must not narrow the
        // lookup to its own project_id (cross-project footgun guard).
        let (tenant_id, project_id) =
            resolve_required(dir.path(), Some("other_tenant".to_string()), None).unwrap();
        assert_eq!(tenant_id, "other_tenant");
        assert_eq!(project_id, None);
    }

    #[test]
    fn malformed_scope_file_errors_instead_of_walking_up() {
        let dir = tempfile::tempdir().unwrap();
        let parent_scope = dir.path().join(".memd");
        std::fs::create_dir_all(&parent_scope).unwrap();
        std::fs::write(
            parent_scope.join("project_scope.json"),
            r#"{"tenant_id": "parent_tenant"}"#,
        )
        .unwrap();
        let child = dir.path().join("child");
        std::fs::create_dir_all(child.join(".memd")).unwrap();
        std::fs::write(child.join(".memd/project_scope.json"), "{ not json").unwrap();

        let err = resolve_required(&child, None, None).unwrap_err();
        let MemdError::ValidationError(message) = err else {
            panic!("unexpected error variant");
        };
        assert!(
            message.contains("malformed") && message.contains("memd init"),
            "unexpected message: {message}"
        );

        // An explicit tenant bypasses scope reading entirely, so the
        // malformed file must not break flagged invocations.
        let (tenant_id, _) =
            resolve_required(&child, Some("explicit_tenant".to_string()), None).unwrap();
        assert_eq!(tenant_id, "explicit_tenant");
    }

    #[test]
    fn resolve_required_errors_with_exact_message_without_scope() {
        let dir = tempfile::tempdir().unwrap();
        let err = resolve_required(dir.path(), None, None).unwrap_err();
        let MemdError::ValidationError(message) = err else {
            panic!("unexpected error variant");
        };
        assert_eq!(
            message,
            format!(
                "no --tenant-id given and no .memd/project_scope.json found upward from {}; run: memd session-start --project-dir . (or pass --tenant-id)",
                dir.path().display()
            )
        );
    }

    #[test]
    fn operation_arguments_inherit_scope_without_overriding_explicit_values() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(
            dir.path().join(".memd/project_scope.json"),
            r#"{
              "tenant_id": "scoped_tenant",
              "project_id": "scoped_project",
              "interface": "cli",
              "cli_command": "memd",
              "agent_context_output": ".memd/context.md",
              "project_dir": "."
            }"#,
        )
        .unwrap();

        let mut cache = OperationScopeCache::default();
        let scoped = apply_operation_scope_at(
            dir.path(),
            serde_json::json!({"text": "scope me"}),
            &mut cache,
        )
        .unwrap();
        assert_eq!(scoped["tenant_id"], "scoped_tenant");
        assert_eq!(scoped["project_id"], "scoped_project");

        let mut cache = OperationScopeCache::default();
        let project_override = apply_operation_scope_at(
            dir.path(),
            serde_json::json!({"project_id": "override"}),
            &mut cache,
        )
        .unwrap();
        assert_eq!(project_override["tenant_id"], "scoped_tenant");
        assert_eq!(project_override["project_id"], "override");

        let mut cache = OperationScopeCache::default();
        let explicit_tenant = apply_operation_scope_at(
            dir.path(),
            serde_json::json!({"tenant_id": "other_tenant"}),
            &mut cache,
        )
        .unwrap();
        assert_eq!(explicit_tenant["tenant_id"], "other_tenant");
        assert!(explicit_tenant.get("project_id").is_none());

        let mut cache = OperationScopeCache::default();
        let null_tenant = apply_operation_scope_at(
            dir.path(),
            serde_json::json!({"tenant_id": null}),
            &mut cache,
        )
        .unwrap();
        assert_eq!(null_tenant["tenant_id"], "scoped_tenant");
        assert_eq!(null_tenant["project_id"], "scoped_project");
    }

    #[test]
    fn explicit_operation_tenant_bypasses_malformed_scope() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(dir.path().join(".memd/project_scope.json"), "{ not json").unwrap();

        let mut cache = OperationScopeCache::default();
        let explicit = apply_operation_scope_at(
            dir.path(),
            serde_json::json!({"tenant_id": "explicit_tenant"}),
            &mut cache,
        )
        .unwrap();
        assert_eq!(explicit["tenant_id"], "explicit_tenant");
    }

    #[test]
    fn cached_operation_scope_error_keeps_one_validation_prefix() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(dir.path().join(".memd/project_scope.json"), "{ not json").unwrap();

        let mut cache = OperationScopeCache::default();
        let first =
            apply_operation_scope_at(dir.path(), serde_json::json!({"text": "first"}), &mut cache)
                .unwrap_err()
                .to_string();
        let replay = apply_operation_scope_at(
            dir.path(),
            serde_json::json!({"text": "second"}),
            &mut cache,
        )
        .unwrap_err()
        .to_string();

        assert_eq!(replay, first);
        assert_eq!(replay.matches("validation error:").count(), 1, "{replay}");
    }

    #[test]
    fn unreadable_scope_path_fails_closed_without_walking_up() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd/project_scope.json")).unwrap();

        let child = dir.path().join("child");
        std::fs::create_dir_all(&child).unwrap();
        let mut cache = OperationScopeCache::default();
        let error = apply_operation_scope_at(
            &child,
            serde_json::json!({"text": "do not route"}),
            &mut cache,
        )
        .unwrap_err();
        assert!(error.to_string().contains("unable to read"), "{error}");
        assert!(
            error.to_string().contains(".memd/project_scope.json"),
            "{error}"
        );

        let mut cache = OperationScopeCache::default();
        let explicit = apply_operation_scope_at(
            &child,
            serde_json::json!({"tenant_id": "explicit_tenant"}),
            &mut cache,
        )
        .unwrap();
        assert_eq!(explicit["tenant_id"], "explicit_tenant");
    }
}