memd 0.61.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
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
//! `memd consolidate` — LLM-backed memory consolidation (Phase 2).
//!
//! Builds a working region from chunks written (and retrieved) since
//! the last run, asks the configured [`Consolidator`] to rewrite them
//! into a smaller deduplicated set of `kind:consolidated` lessons,
//! persists those lessons, and soft-tombstones the superseded
//! sources. Nothing is ever deleted — superseded chunks stay on disk
//! and are merely hidden from retrieval.

use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::Deserialize;
use serde_json::{json, Value};

use super::paths::absolutize_project_dir;
use crate::consolidate::prompt::{
    build_consolidation_prompt, parse_consolidation_response, ConsolidatedEntry, RegionChunk,
};
use crate::consolidate::select::select_consolidator;
use crate::consolidate::Consolidator;
use crate::error::{MemdError, Result};
use crate::store::Store;
use crate::types::lifecycle::LifecycleDelta;
use crate::types::{ChunkId, ChunkStatus, ChunkType, MemoryChunk, ProjectId, TenantId};

/// Minimum region size below which consolidation is skipped unless
/// `--force` is passed. Also the dirty-chunk threshold at which
/// `memd session-start` spawns a background consolidation.
pub(super) const MIN_REGION: usize = 10;

/// Hard ceiling on chunks scanned while building the region.
const SCAN_LIMIT: usize = 500;

/// Options for the `consolidate` subcommand.
#[derive(Debug, Clone)]
pub(super) struct ConsolidateOptions {
    pub(super) tenant_id: Option<String>,
    pub(super) project_id: Option<String>,
    pub(super) project_dir: PathBuf,
    pub(super) max_region: usize,
    pub(super) dry_run: bool,
    pub(super) background: bool,
    pub(super) force: bool,
    /// Promote consolidated lessons that span ≥2 projects to the
    /// shared tenant. OFF by default so consolidation never crosses
    /// the tenant boundary without an explicit opt-in.
    pub(super) promote_to_shared: bool,
}

/// Entry point: resolves the consolidator backend from the
/// environment, then runs the consolidation.
pub(super) async fn run_consolidate<S: Store>(
    store: &S,
    options: ConsolidateOptions,
) -> Result<Value> {
    if options.background {
        return spawn_background(&options);
    }
    let consolidator = select_consolidator()?;
    consolidate_core(store, options, consolidator.as_ref()).await
}

/// Core consolidation flow, parameterised over the [`Consolidator`] so
/// tests can inject a deterministic backend.
async fn consolidate_core<S: Store>(
    store: &S,
    options: ConsolidateOptions,
    consolidator: &dyn Consolidator,
) -> Result<Value> {
    let project_dir = absolutize_project_dir(&options.project_dir)?;
    let (tenant_id, project_id) = resolve_scope(
        &project_dir,
        options.tenant_id.clone(),
        options.project_id.clone(),
    )?;
    let tenant = TenantId::new(&tenant_id)?;
    let max_region = options.max_region.clamp(MIN_REGION, SCAN_LIMIT);

    let state_path = consolidate_state_path(&project_dir);
    let since_ms = read_last_consolidation_ms(&state_path);

    let region = collect_region(
        store,
        &tenant,
        project_id.as_deref(),
        since_ms,
        &project_dir,
        max_region,
    )
    .await?;

    if region.len() < MIN_REGION && !options.force {
        return Ok(json!({
            "skipped": "below_threshold",
            "region_size": region.len(),
            "min_region": MIN_REGION,
        }));
    }

    let prompt = build_consolidation_prompt(&region);
    if options.dry_run {
        return Ok(json!({
            "dry_run": true,
            "region_size": region.len(),
            "prompt": prompt,
        }));
    }

    let raw = consolidator.consolidate(&prompt).await?;
    let entries = parse_consolidation_response(&raw, &region)?;

    let now = now_ms();
    let inherited_ctx = most_common_ctx_tags(&region, 3);
    // Map from source `chunk_id` → owning `project_id` so a
    // multi-project supersedes set triggers cross-tenant promotion.
    let source_projects = source_project_map(&region);
    let shared_tenant = std::env::var("MEMD_SHARED_TENANT")
        .ok()
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| "shared".to_string());
    let mut written = Vec::new();
    let mut tombstoned = 0usize;
    let mut promoted = 0usize;

    for entry in &entries {
        let new_id = persist_consolidated(
            store,
            &tenant,
            project_id.as_deref(),
            entry,
            consolidator.name(),
            &inherited_ctx,
        )
        .await?;
        tombstoned += tombstone_sources(store, &tenant, entry, &new_id, now).await?;
        written.push(new_id.to_string());

        if options.promote_to_shared && spans_multiple_projects(entry, &source_projects) {
            // Best-effort promotion to the shared tenant; gated on
            // the explicit `--promote-to-shared` opt-in so the
            // default consolidate flow never crosses tenants.
            if promote_to_shared_tenant(
                store,
                &shared_tenant,
                &tenant_id,
                entry,
                consolidator.name(),
                &new_id,
                &source_projects,
                &inherited_ctx,
            )
            .await
            .is_ok()
            {
                promoted += 1;
            }
        }
    }

    write_last_consolidation_ms(&state_path, now)?;

    Ok(json!({
        "tenant_id": tenant_id,
        "project_id": project_id,
        "region_size": region.len(),
        "consolidated": written.len(),
        "tombstoned": tombstoned,
        "promoted_to_shared": promoted,
        "consolidator": consolidator.name(),
        "new_chunk_ids": written,
    }))
}

/// Build `source_chunk_id → project_id` so we can tell which projects
/// each consolidated entry spans. Sources without a project id are
/// recorded as the empty string so they still form a distinct bucket.
fn source_project_map(region: &[RegionChunk]) -> std::collections::HashMap<String, String> {
    region
        .iter()
        .map(|chunk| {
            (
                chunk.chunk_id.clone(),
                chunk.project_id.clone().unwrap_or_default(),
            )
        })
        .collect()
}

/// True if `entry.supersedes` references chunks from ≥2 distinct
/// named projects. Unscoped sources (empty string bucket) are
/// excluded so a lesson spanning "one real project + ambient chunks"
/// is not treated as multi-project.
fn spans_multiple_projects(
    entry: &ConsolidatedEntry,
    source_projects: &std::collections::HashMap<String, String>,
) -> bool {
    let projects: std::collections::HashSet<&str> = entry
        .supersedes
        .iter()
        .filter_map(|id| source_projects.get(id).map(String::as_str))
        .filter(|p| !p.is_empty())
        .collect();
    projects.len() >= 2
}

/// Persist a copy of `entry` under the shared tenant with the
/// `kind:cross_tenant_promoted` provenance tags. The copy is itself
/// `kind:consolidated` so memory.md's cross-tenant section picks it
/// up; nothing in the source tenant changes.
///
/// Idempotent: identified by
/// `provenance:<source_tenant>:<sha-of-source-id+supersedes>`. If a
/// matching promotion already exists in the shared tenant we return
/// its id without writing a new chunk.
async fn promote_to_shared_tenant<S: Store>(
    store: &S,
    shared_tenant: &str,
    source_tenant: &str,
    entry: &ConsolidatedEntry,
    consolidator_name: &str,
    source_consolidated_id: &ChunkId,
    source_projects: &std::collections::HashMap<String, String>,
    inherited_ctx: &[String],
) -> Result<ChunkId> {
    let tenant = TenantId::new(shared_tenant)?;
    let provenance = promotion_provenance_tag(
        source_tenant,
        &source_consolidated_id.to_string(),
        &entry.supersedes,
    );

    // Idempotency: scan recent shared-tenant chunks for the same
    // provenance tag. Best-effort — failure here only risks a
    // duplicate write, not data loss.
    if let Ok(existing) = store.list_chunks_for_project(&tenant, None, 500, 0).await {
        for chunk in existing {
            if chunk.tags.iter().any(|t| t == &provenance) {
                return Ok(chunk.chunk_id);
            }
        }
    }

    let source_project_list: std::collections::BTreeSet<&str> = entry
        .supersedes
        .iter()
        .filter_map(|id| source_projects.get(id).map(String::as_str))
        .filter(|p| !p.is_empty())
        .collect();
    let source_projects_tag = format!(
        "source_projects:{}",
        source_project_list
            .into_iter()
            .collect::<Vec<_>>()
            .join(",")
    );

    let mut tags = vec![
        "kind:consolidated".to_string(),
        "kind:cross_tenant_promoted".to_string(),
        format!("priority:{}", entry.priority),
        format!("supersedes:{}", entry.supersedes.join(",")),
        format!("consolidator:{consolidator_name}"),
        format!("source_tenant:{source_tenant}"),
        format!("source_chunk:{source_consolidated_id}"),
        source_projects_tag,
        provenance,
    ];
    tags.extend(inherited_ctx.iter().cloned());
    let chunk = MemoryChunk::new(tenant, &entry.text, ChunkType::Summary).with_tags(tags);
    store.add(chunk).await
}

/// Deterministic provenance tag: `provenance:<tenant>:<sha8>` over
/// the source consolidated chunk id plus the sorted supersedes list.
fn promotion_provenance_tag(
    source_tenant: &str,
    source_chunk: &str,
    supersedes: &[String],
) -> String {
    use sha2::{Digest, Sha256};
    let mut sorted = supersedes.to_vec();
    sorted.sort();
    let mut hasher = Sha256::new();
    hasher.update(source_tenant.as_bytes());
    hasher.update(b"|");
    hasher.update(source_chunk.as_bytes());
    hasher.update(b"|");
    hasher.update(sorted.join(",").as_bytes());
    let digest = hasher.finalize();
    let short: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect();
    format!("provenance:{source_tenant}:{short}")
}

/// Count the chunks that would form the consolidation region for the
/// given scope. Used by `memd session-start` to decide whether a
/// background consolidation is worth spawning.
pub(super) async fn dirty_region_size<S: Store>(
    store: &S,
    project_dir: &Path,
    tenant_arg: Option<String>,
    project_arg: Option<String>,
) -> Result<usize> {
    let (tenant_id, project_id) = resolve_scope(project_dir, tenant_arg, project_arg)?;
    let tenant = TenantId::new(&tenant_id)?;
    let since_ms = read_last_consolidation_ms(&consolidate_state_path(project_dir));
    let region = collect_region(
        store,
        &tenant,
        project_id.as_deref(),
        since_ms,
        project_dir,
        SCAN_LIMIT,
    )
    .await?;
    Ok(region.len())
}

/// Resolve `(tenant_id, project_id)` from explicit args, falling back
/// to `.memd/project_scope.json` then `.memd/config.json`.
pub(super) fn resolve_scope(
    project_dir: &Path,
    tenant_arg: Option<String>,
    project_arg: Option<String>,
) -> Result<(String, Option<String>)> {
    let scope = read_scope_file(project_dir);
    let tenant_id = tenant_arg
        .or_else(|| scope.as_ref().and_then(|s| s.tenant_id.clone()))
        .ok_or_else(|| {
            MemdError::ValidationError(
                "consolidate requires --tenant-id or .memd/project_scope.json".to_string(),
            )
        })?;
    let project_id = project_arg.or_else(|| scope.and_then(|s| s.project_id));
    Ok((tenant_id, project_id))
}

#[derive(Debug, Deserialize)]
struct ScopeFile {
    #[serde(default)]
    tenant_id: Option<String>,
    #[serde(default)]
    project_id: Option<String>,
}

/// Read `{tenant_id, project_id}` from `.memd/project_scope.json` or
/// `.memd/config.json`, ignoring any other fields.
fn read_scope_file(project_dir: &Path) -> Option<ScopeFile> {
    for name in [".memd/project_scope.json", ".memd/config.json"] {
        let path = project_dir.join(name);
        let Ok(text) = std::fs::read_to_string(&path) else {
            continue;
        };
        if let Ok(scope) = serde_json::from_str::<ScopeFile>(&text) {
            return Some(scope);
        }
    }
    None
}

fn consolidate_state_path(project_dir: &Path) -> PathBuf {
    project_dir.join(".memd/data/consolidate.state.json")
}

#[derive(Debug, Default, Deserialize, serde::Serialize)]
struct ConsolidateState {
    #[serde(default)]
    last_consolidation_ms: i64,
}

fn read_last_consolidation_ms(state_path: &Path) -> i64 {
    std::fs::read_to_string(state_path)
        .ok()
        .and_then(|text| serde_json::from_str::<ConsolidateState>(&text).ok())
        .map(|state| state.last_consolidation_ms)
        .unwrap_or(0)
}

fn write_last_consolidation_ms(state_path: &Path, ms: i64) -> Result<()> {
    if let Some(parent) = state_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let state = ConsolidateState {
        last_consolidation_ms: ms,
    };
    std::fs::write(state_path, serde_json::to_string_pretty(&state)? + "\n")?;
    Ok(())
}

/// Build the consolidation working region: chunks written since
/// `since_ms`, unioned with chunk ids seen in recent search logs.
/// `kind:consolidated` / `kind:superseded` chunks are excluded so the
/// region is always raw material, never prior output.
async fn collect_region<S: Store>(
    store: &S,
    tenant: &TenantId,
    project_id: Option<&str>,
    since_ms: i64,
    project_dir: &Path,
    max_region: usize,
) -> Result<Vec<RegionChunk>> {
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut region: Vec<RegionChunk> = Vec::new();

    let recent = store
        .list_chunks_for_project(tenant, project_id, SCAN_LIMIT, 0)
        .await?;
    for chunk in recent {
        consider_chunk(chunk, since_ms, project_id, &mut seen, &mut region);
    }

    for chunk_id in search_log_chunk_ids(project_dir, since_ms) {
        if seen.contains(&chunk_id) {
            continue;
        }
        let Ok(parsed) = ChunkId::parse(&chunk_id) else {
            continue;
        };
        // `store.get` is tenant-scoped only — `consider_chunk`
        // re-checks `project_id` so a project consolidation never
        // ingests (and later tombstones) another project's chunk.
        if let Ok(Some(chunk)) = store.get(tenant, &parsed).await {
            consider_chunk(chunk, since_ms, project_id, &mut seen, &mut region);
        }
    }

    // Newest first, then cap.
    region.sort_by(|a, b| b.timestamp_created.cmp(&a.timestamp_created));
    region.truncate(max_region);
    Ok(region)
}

/// Apply region-membership filters to one chunk and push it if it
/// qualifies. When `project_id` is `Some`, chunks outside that
/// project are rejected — this guards the search-log union path,
/// where chunk ids are resolved tenant-wide.
fn consider_chunk(
    chunk: MemoryChunk,
    since_ms: i64,
    project_id: Option<&str>,
    seen: &mut std::collections::HashSet<String>,
    region: &mut Vec<RegionChunk>,
) {
    if let Some(project_id) = project_id {
        if chunk.project_id.as_option() != Some(project_id) {
            return;
        }
    }
    if chunk.timestamp_created <= since_ms {
        return;
    }
    if matches!(
        chunk.status,
        ChunkStatus::Superseded | ChunkStatus::Deleted | ChunkStatus::Expired
    ) {
        return;
    }
    if chunk
        .tags
        .iter()
        .any(|t| t.starts_with("kind:consolidated") || t.starts_with("kind:superseded"))
    {
        return;
    }
    let id = chunk.chunk_id.to_string();
    if !seen.insert(id.clone()) {
        return;
    }
    region.push(RegionChunk {
        chunk_id: id,
        chunk_type: chunk.chunk_type.to_string(),
        tags: chunk.tags.clone(),
        timestamp_created: chunk.timestamp_created,
        text: chunk.text,
        project_id: chunk.project_id.as_option().map(str::to_string),
    });
}

/// Scan `.memd/search-logs/*.json` for chunk ids retrieved since
/// `since_ms`. The unix-ms stamp in each filename
/// (`memd_search_<stamp>.json`) bounds the scan. Best-effort: any
/// unreadable or unparseable file is silently skipped.
fn search_log_chunk_ids(project_dir: &Path, since_ms: i64) -> Vec<String> {
    let log_dir = project_dir.join(".memd/search-logs");
    let Ok(entries) = std::fs::read_dir(&log_dir) else {
        return Vec::new();
    };
    let mut ids = Vec::new();
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();
        if !name.ends_with(".json") || name.ends_with("_log.jsonl") {
            continue;
        }
        if let Some(stamp) = name
            .rsplit_once('_')
            .and_then(|(_, tail)| tail.strip_suffix(".json"))
            .and_then(|s| s.parse::<i64>().ok())
        {
            if stamp <= since_ms {
                continue;
            }
        }
        let Ok(text) = std::fs::read_to_string(entry.path()) else {
            continue;
        };
        let Ok(payload) = serde_json::from_str::<Value>(&text) else {
            continue;
        };
        if let Some(results) = payload.get("results").and_then(Value::as_array) {
            for result in results {
                if let Some(id) = result.get("chunk_id").and_then(Value::as_str) {
                    if !id.is_empty() {
                        ids.push(id.to_string());
                    }
                }
            }
        }
    }
    ids
}

/// The `ctx:*` tags most common across the region, up to `limit`.
/// Consolidated lessons inherit these so subsystem/file context is
/// not lost when raw chunks are tombstoned.
fn most_common_ctx_tags(region: &[RegionChunk], limit: usize) -> Vec<String> {
    let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
    for chunk in region {
        for tag in &chunk.tags {
            if tag.starts_with("ctx:") {
                *counts.entry(tag.as_str()).or_insert(0) += 1;
            }
        }
    }
    let mut ranked: Vec<(&str, usize)> = counts.into_iter().collect();
    // Frequency desc, then tag asc for deterministic ties.
    ranked.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
    ranked
        .into_iter()
        .take(limit)
        .map(|(tag, _)| tag.to_string())
        .collect()
}

/// Persist one consolidated lesson and return its new chunk id.
async fn persist_consolidated<S: Store>(
    store: &S,
    tenant: &TenantId,
    project_id: Option<&str>,
    entry: &ConsolidatedEntry,
    consolidator_name: &str,
    inherited_ctx: &[String],
) -> Result<ChunkId> {
    let mut tags = vec![
        "kind:consolidated".to_string(),
        format!("priority:{}", entry.priority),
        format!("supersedes:{}", entry.supersedes.join(",")),
        format!("consolidator:{consolidator_name}"),
    ];
    tags.extend(inherited_ctx.iter().cloned());

    let mut chunk = MemoryChunk::new(tenant.clone(), &entry.text, ChunkType::Summary);
    if let Some(project_id) = project_id {
        chunk = chunk.with_project(ProjectId::from(project_id));
    }
    chunk = chunk.with_tags(tags);
    store.add(chunk).await
}

/// Soft-tombstone every source chunk an `entry` supersedes: set
/// `status = Superseded` and `superseded_by = <new_id>` on the
/// lifecycle overlay. The payload is never deleted. Returns the count
/// of sources successfully tombstoned.
async fn tombstone_sources<S: Store>(
    store: &S,
    tenant: &TenantId,
    entry: &ConsolidatedEntry,
    new_id: &ChunkId,
    now_ms: i64,
) -> Result<usize> {
    let persistent = store.as_persistent().ok_or_else(|| {
        MemdError::ValidationError(
            "consolidate requires a persistent store to tombstone superseded chunks".to_string(),
        )
    })?;
    let mut count = 0usize;
    for source_id in &entry.supersedes {
        let Ok(parsed) = ChunkId::parse(source_id) else {
            continue;
        };
        let delta = LifecycleDelta {
            status: Some(ChunkStatus::Superseded),
            superseded_by: Some(new_id.clone()),
            lifecycle_updated_at_ms: Some(now_ms),
            ..Default::default()
        };
        if persistent
            .update_lifecycle_if_exists(tenant, &parsed, &delta)
            .await?
        {
            count += 1;
        }
    }
    Ok(count)
}

/// Re-exec `memd consolidate` as a detached background child and
/// return immediately. The child runs the same scope without
/// `--background`.
fn spawn_background(options: &ConsolidateOptions) -> Result<Value> {
    let exe = std::env::current_exe()
        .map_err(|e| MemdError::ProtocolError(format!("cannot resolve current executable: {e}")))?;
    let mut command = std::process::Command::new(exe);
    command.arg("consolidate");
    if let Some(tenant) = &options.tenant_id {
        command.arg("--tenant-id").arg(tenant);
    }
    if let Some(project) = &options.project_id {
        command.arg("--project-id").arg(project);
    }
    command
        .arg("--project-dir")
        .arg(&options.project_dir)
        .arg("--max-region")
        .arg(options.max_region.to_string());
    if options.force {
        command.arg("--force");
    }
    if options.promote_to_shared {
        command.arg("--promote-to-shared");
    }
    command
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        command.process_group(0);
    }
    let child = command.spawn().map_err(|e| {
        MemdError::ProtocolError(format!("failed to spawn background consolidate: {e}"))
    })?;
    Ok(json!({ "spawned_background": true, "pid": child.id() }))
}

fn now_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::consolidate::MockEnvConsolidator;
    use crate::store::persistent::{PersistentStore, PersistentStoreConfig};
    use crate::store::Store;
    use tempfile::tempdir;

    fn persistent_store(dir: &Path) -> PersistentStore {
        let cfg = PersistentStoreConfig {
            data_dir: dir.to_path_buf(),
            enable_dense_search: false,
            enable_hybrid_search: false,
            ..Default::default()
        };
        PersistentStore::open(cfg).expect("open store")
    }

    fn region_chunk(id: &str, ctx: &[&str]) -> RegionChunk {
        RegionChunk {
            chunk_id: id.to_string(),
            chunk_type: "summary".to_string(),
            tags: ctx.iter().map(|t| t.to_string()).collect(),
            timestamp_created: 1,
            text: "t".to_string(),
            project_id: None,
        }
    }

    #[test]
    fn most_common_ctx_prefers_frequent_tags() {
        let region = vec![
            region_chunk("a", &["ctx:file:x", "ctx:subsystem:s"]),
            region_chunk("b", &["ctx:file:x"]),
            region_chunk("c", &["ctx:file:y"]),
        ];
        let tags = most_common_ctx_tags(&region, 2);
        assert_eq!(tags[0], "ctx:file:x");
        assert_eq!(tags.len(), 2);
    }

    #[test]
    fn state_roundtrip() {
        let dir = tempdir().unwrap();
        let path = consolidate_state_path(dir.path());
        assert_eq!(read_last_consolidation_ms(&path), 0);
        write_last_consolidation_ms(&path, 4242).unwrap();
        assert_eq!(read_last_consolidation_ms(&path), 4242);
    }

    #[test]
    fn resolve_scope_prefers_explicit_args() {
        let dir = tempdir().unwrap();
        let (tenant, project) =
            resolve_scope(dir.path(), Some("t".to_string()), Some("p".to_string())).unwrap();
        assert_eq!(tenant, "t");
        assert_eq!(project.as_deref(), Some("p"));
    }

    #[test]
    fn resolve_scope_reads_config_json() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(
            dir.path().join(".memd/config.json"),
            r#"{"tenant_id":"ct","project_id":"cp"}"#,
        )
        .unwrap();
        let (tenant, project) = resolve_scope(dir.path(), None, None).unwrap();
        assert_eq!(tenant, "ct");
        assert_eq!(project.as_deref(), Some("cp"));
    }

    #[tokio::test]
    async fn below_threshold_skips_without_force() {
        let dir = tempdir().unwrap();
        let store = persistent_store(&dir.path().join("store"));
        let tenant = TenantId::new("t").unwrap();
        for i in 0..3 {
            store
                .add(
                    MemoryChunk::new(tenant.clone(), format!("chunk {i}"), ChunkType::Summary)
                        .with_project(ProjectId::from("p")),
                )
                .await
                .unwrap();
        }
        let opts = ConsolidateOptions {
            tenant_id: Some("t".to_string()),
            project_id: Some("p".to_string()),
            project_dir: dir.path().to_path_buf(),
            max_region: 50,
            dry_run: false,
            background: false,
            force: false,
            promote_to_shared: false,
        };
        let consolidator = MockEnvConsolidator;
        let result = consolidate_core(&store, opts, &consolidator).await.unwrap();
        assert_eq!(result["skipped"], "below_threshold");
    }

    #[tokio::test]
    async fn consolidate_writes_and_tombstones() {
        let dir = tempdir().unwrap();
        let store = persistent_store(&dir.path().join("store"));
        let tenant = TenantId::new("t").unwrap();
        let mut ids = Vec::new();
        for i in 0..12 {
            let id = store
                .add(
                    MemoryChunk::new(
                        tenant.clone(),
                        format!("duplicate lesson {i}: cache keys must be tenant-scoped"),
                        ChunkType::Summary,
                    )
                    .with_project(ProjectId::from("p"))
                    .with_tags(vec!["ctx:subsystem:cache".to_string()]),
                )
                .await
                .unwrap();
            ids.push(id.to_string());
        }
        let response = format!(
            r#"[{{"text":"Cache keys must be tenant-scoped.","supersedes":{},"priority":8}}]"#,
            serde_json::to_string(&ids).unwrap()
        );
        std::env::set_var(crate::consolidate::MOCK_RESPONSE_ENV, &response);

        let opts = ConsolidateOptions {
            tenant_id: Some("t".to_string()),
            project_id: Some("p".to_string()),
            project_dir: dir.path().to_path_buf(),
            max_region: 50,
            dry_run: false,
            background: false,
            force: false,
            promote_to_shared: false,
        };
        let consolidator = MockEnvConsolidator;
        let result = consolidate_core(&store, opts, &consolidator).await.unwrap();
        std::env::remove_var(crate::consolidate::MOCK_RESPONSE_ENV);

        assert_eq!(result["consolidated"], 1);
        assert_eq!(result["tombstoned"], 12);

        // Sources are now superseded; the consolidated chunk carries
        // the provenance tag.
        let new_id = result["new_chunk_ids"][0].as_str().unwrap();
        let consolidated = store
            .get(&tenant, &ChunkId::parse(new_id).unwrap())
            .await
            .unwrap()
            .unwrap();
        assert!(consolidated.tags.iter().any(|t| t == "kind:consolidated"));
        assert!(consolidated
            .tags
            .iter()
            .any(|t| t.starts_with("ctx:subsystem:cache")));
    }

    #[tokio::test]
    async fn dry_run_emits_prompt_without_calling_llm() {
        let dir = tempdir().unwrap();
        let store = persistent_store(&dir.path().join("store"));
        let tenant = TenantId::new("t").unwrap();
        for i in 0..12 {
            store
                .add(
                    MemoryChunk::new(tenant.clone(), format!("chunk {i}"), ChunkType::Summary)
                        .with_project(ProjectId::from("p")),
                )
                .await
                .unwrap();
        }
        let opts = ConsolidateOptions {
            tenant_id: Some("t".to_string()),
            project_id: Some("p".to_string()),
            project_dir: dir.path().to_path_buf(),
            max_region: 50,
            dry_run: true,
            background: false,
            force: false,
            promote_to_shared: false,
        };
        // A mock with no response env set must NOT be invoked.
        let consolidator = MockEnvConsolidator;
        let result = consolidate_core(&store, opts, &consolidator).await.unwrap();
        assert_eq!(result["dry_run"], true);
        assert!(result["prompt"].as_str().unwrap().contains("CHUNKS:"));
    }
}