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
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
//! `memd session-start` — invoked from the Claude Code / Codex
//! SessionStart hook (Phase 2).
//!
//! Reconciles stale consolidation runs, refreshes `memory.md`
//! synchronously, then starts detached background consolidation when
//! enough chunks have accumulated. It does not block on an LLM call.
//!
//! When the project has no `.memd/project_scope.json`, the command
//! auto-creates one using sensible defaults (USER as tenant, repo
//! basename as project) so automatic startup does not require a per-repo
//! `memd init`. Opt out by setting `MEMD_AUTO_SCOPE=0` or
//! dropping a `.memd-skip` file in the repo root.

use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

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

use super::args::{NativeHookHarness, ProjectScopeConfig};
use super::consolidate::{dirty_region_size, run_consolidate, ConsolidateOptions, MIN_REGION};
use super::memory_md::{read_project_scope, refresh_memory_md_with_health, MemoryMdOptions};
use super::paths::absolutize_project_dir;
use super::provenance::capture_execution_context;
use crate::error::{MemdError, Result};
use crate::store::{Store, TenantManager};
use crate::task_memory::ExecutionContext;
use crate::types::{ProjectId, TenantId};

/// Maximum length of an auto-derived `tenant_id` or `project_id`. Both
/// are written into directory names downstream, so we keep them short.
const MAX_AUTO_ID_LEN: usize = 64;
const MAX_NATIVE_HOOK_BYTES: u64 = 64 * 1024;

#[derive(Debug, Deserialize)]
struct NativeHookPayload {
    #[serde(default)]
    cwd: Option<String>,
    #[serde(default)]
    session_id: Option<String>,
    #[serde(default)]
    thread_id: Option<String>,
    #[serde(default)]
    agent_id: Option<String>,
    #[serde(default)]
    parent_agent_id: Option<String>,
    #[serde(default)]
    model: Option<String>,
}

/// Options for the `session-start` subcommand.
#[derive(Debug, Clone)]
pub(super) struct SessionStartOptions {
    pub(super) project_dir: PathBuf,
}

/// Resolved inputs for the auto-scope decision. Extracted so unit
/// tests can drive the logic without mutating process env.
#[derive(Debug, Clone)]
pub(super) struct AutoScopeInputs {
    /// Default tenant id to assign when scope is auto-created. Comes
    /// from `MEMD_DEFAULT_TENANT`, then `USER`, then "default".
    pub(super) default_tenant: String,
    /// When false, auto-scope is suppressed and the caller should
    /// behave as before (no-op on missing scope).
    pub(super) enabled: bool,
}

impl AutoScopeInputs {
    /// Read inputs from the process environment.
    ///
    /// `default_tenant` precedence: `MEMD_DEFAULT_TENANT` → `USER` →
    /// `"default"`. Each raw value is trimmed and sanitised (see
    /// `sanitize_id`) so a username with spaces or punctuation
    /// (`"felix-schulz"`, `"  alice  "`) yields a tenant id that
    /// `TenantId::validate` will accept. If sanitisation produces an
    /// id the validator still rejects, falls back to `"default"`.
    pub(super) fn from_env() -> Self {
        let raw_tenant = std::env::var("MEMD_DEFAULT_TENANT")
            .ok()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .or_else(|| {
                std::env::var("USER")
                    .ok()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
            })
            .unwrap_or_else(|| "default".to_string());
        let sanitized = sanitize_id(&raw_tenant, "default");
        // `sanitize_id` only produces alnum+`_`, which `TenantId`
        // always accepts. Guarded anyway so a future validator change
        // (e.g. min-length) doesn't silently write an invalid id.
        let default_tenant = if TenantId::validate(&sanitized).is_ok() {
            sanitized
        } else {
            "default".to_string()
        };
        let enabled = std::env::var("MEMD_AUTO_SCOPE")
            .map(|v| v != "0" && !v.eq_ignore_ascii_case("false"))
            .unwrap_or(true);
        Self {
            default_tenant,
            enabled,
        }
    }
}

/// Run the session-start routine. When `.memd/project_scope.json` is
/// missing, this auto-creates one using `inputs.default_tenant` and
/// the basename of `project_dir` (unless suppressed by env or a
/// `.memd-skip` file). After scope exists, refreshes `memory.md` and
/// optionally spawns a background consolidation.
pub(super) async fn run_session_start<S: Store>(
    store: &S,
    options: SessionStartOptions,
    execution_context: Option<ExecutionContext>,
) -> Result<Value> {
    let mut result = run_session_start_inner(store, options, AutoScopeInputs::from_env()).await?;
    if let Some(execution_context) = execution_context {
        let result_object = result.as_object_mut().ok_or_else(|| {
            MemdError::ProtocolError("session-start result must be a JSON object".to_string())
        })?;
        result_object.insert(
            "execution_context".to_string(),
            serde_json::to_value(execution_context)?,
        );
    }
    Ok(result)
}

pub(super) fn read_native_hook_context(
    harness: NativeHookHarness,
    project_dir: &Path,
) -> Result<ExecutionContext> {
    let stdin = std::io::stdin();
    parse_native_hook_context(harness, stdin.lock(), project_dir)
}

pub(super) fn native_hook_project_dir(requested: &Path, context: &ExecutionContext) -> PathBuf {
    if requested != Path::new(".") {
        return requested.to_path_buf();
    }
    context
        .cwd
        .as_deref()
        .filter(|cwd| !cwd.trim().is_empty())
        .map(PathBuf::from)
        .unwrap_or_else(|| requested.to_path_buf())
}

fn parse_native_hook_context(
    harness: NativeHookHarness,
    reader: impl Read,
    project_dir: &Path,
) -> Result<ExecutionContext> {
    let payload = read_bounded_hook_payload(reader)?;
    let payload: NativeHookPayload = serde_json::from_slice(&payload)?;
    let cwd = nonempty(payload.cwd)
        .map(PathBuf::from)
        .map(|path| {
            if path.is_absolute() {
                path
            } else {
                project_dir.join(path)
            }
        })
        .unwrap_or_else(|| project_dir.to_path_buf());
    let mut context = capture_execution_context(&cwd);
    let harness_name = match harness {
        NativeHookHarness::Claude => "claude",
        NativeHookHarness::Codex => "codex",
    };
    if context.harness.as_deref() != Some(harness_name) {
        context.native_session_id = None;
        context.native_thread_id = None;
    }
    context.harness = Some(harness_name.to_string());
    if let Some(model) = nonempty(payload.model) {
        context.model = Some(model);
    }
    if let Some(agent_id) = nonempty(payload.agent_id) {
        context.native_agent_id = Some(agent_id);
    }
    if let Some(parent_id) = nonempty(payload.parent_agent_id) {
        context.native_parent_id = Some(parent_id);
    }
    if let Some(session_id) = nonempty(payload.session_id) {
        context.native_session_id = Some(session_id);
    }
    if let Some(thread_id) = nonempty(payload.thread_id) {
        context.native_thread_id = Some(thread_id);
    }
    Ok(context)
}

fn read_bounded_hook_payload(reader: impl Read) -> Result<Vec<u8>> {
    let mut payload = Vec::new();
    reader
        .take(MAX_NATIVE_HOOK_BYTES + 1)
        .read_to_end(&mut payload)?;
    if payload.len() as u64 > MAX_NATIVE_HOOK_BYTES {
        return Err(MemdError::ValidationError(format!(
            "native hook payload exceeds {MAX_NATIVE_HOOK_BYTES} bytes"
        )));
    }
    Ok(payload)
}

fn nonempty(value: Option<String>) -> Option<String> {
    value
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

pub(super) async fn run_session_start_inner<S: Store>(
    store: &S,
    options: SessionStartOptions,
    auto_inputs: AutoScopeInputs,
) -> Result<Value> {
    let project_dir = absolutize_project_dir(&options.project_dir)?;

    // The marker disables all startup work, including refresh and recovery,
    // even when this repository was initialized previously.
    if project_dir.join(".memd-skip").exists() {
        return Ok(json!({ "skipped": "memd_skip_present" }));
    }

    let scope_path = project_dir.join(".memd").join("project_scope.json");
    let mut resolved_scope = match validated_project_scope(&project_dir) {
        Ok(scope) => scope.map(|scope| (scope.tenant_id, scope.project_id)),
        Err(error) => return Ok(invalid_scope_response(&scope_path, &error)),
    };
    // Preserve the legacy `.memd/config.json` fallback when there is no
    // project_scope.json. Auto-scope only applies when neither source resolves.
    if resolved_scope.is_none() {
        let legacy_path = project_dir.join(".memd/config.json");
        match read_legacy_scope(&legacy_path) {
            Ok(scope) => resolved_scope = scope,
            Err(error) => return Ok(invalid_scope_response(&legacy_path, &error)),
        }
    }

    // Auto-create only a truly absent scope. If another startup creates it
    // after our read, create_new leaves that file untouched and we validate
    // the winner before proceeding.
    let mut auto_scoped = false;
    if resolved_scope.is_none() {
        match maybe_auto_create_scope(&project_dir, &auto_inputs)? {
            AutoScopeOutcome::Created => {
                auto_scoped = true;
            }
            AutoScopeOutcome::AlreadyExists => {}
            AutoScopeOutcome::SkippedDisabled => {
                return Ok(json!({ "skipped": "auto_scope_disabled" }));
            }
            AutoScopeOutcome::SkippedMarker => {
                return Ok(json!({ "skipped": "memd_skip_present" }));
            }
        }
        resolved_scope = match validated_project_scope(&project_dir) {
            Ok(scope) => scope.map(|scope| (scope.tenant_id, scope.project_id)),
            Err(error) => return Ok(invalid_scope_response(&scope_path, &error)),
        };
    }

    let (tenant_id, project_id) = match resolved_scope {
        Some(scope) => scope,
        None => return Ok(json!({ "skipped": "no_scope" })),
    };

    // Reconcile staged candidates before generating agent-facing context.
    // Recovery is intentionally a session-start stage rather than a store-open
    // side effect. Session-start itself opens a short-lived writer when its
    // main store handle is read-only, preserving the writer-lock invariant.
    let consolidation_recovery = if let Some(persistent) = store.as_persistent() {
        let recovery_result = if persistent.is_read_only() {
            match persistent.open_consolidation_recovery_writer() {
                Ok(writer) => {
                    crate::consolidate::service::recover_consolidation_runs(&writer, 100).await
                }
                Err(error) => Err(error),
            }
        } else {
            crate::consolidate::service::recover_consolidation_runs(persistent, 100).await
        };
        match recovery_result {
            Ok(recovery) => {
                let mut index_refresh_errors = Vec::new();
                if persistent.is_read_only() {
                    let mut by_tenant = BTreeMap::<String, (TenantId, Vec<_>)>::new();
                    for (promoted_tenant, chunk_id) in &recovery.promoted_chunks {
                        by_tenant
                            .entry(promoted_tenant.to_string())
                            .or_insert_with(|| (promoted_tenant.clone(), Vec::new()))
                            .1
                            .push(chunk_id.clone());
                    }
                    for (_, (promoted_tenant, chunk_ids)) in by_tenant {
                        if let Err(error) = persistent
                            .refresh_promoted_chunks_in_memory(&promoted_tenant, &chunk_ids)
                            .await
                        {
                            index_refresh_errors.push(error.to_string());
                        }
                    }
                }
                json!({
                    "inspected": recovery.inspected,
                    "committed": recovery.committed,
                    "rolled_back": recovery.rolled_back,
                    "rejected": recovery.rejected,
                    "failed_recoverable": recovery.failed_recoverable,
                    "index_refresh_errors": index_refresh_errors,
                })
            }
            Err(error) => json!({ "error": error.to_string() }),
        }
    } else {
        json!({ "skipped": "non_persistent_store" })
    };

    // 1. Refresh memory.md synchronously.
    // The persistent store already carries the resolved data directory. Build
    // the lightweight manager from that exact path so session-start sees the
    // same central health and exposure ledgers as `memd memory-md`.
    let tenant_manager = store
        .as_persistent()
        .map(|persistent| TenantManager::new(persistent.data_dir().to_path_buf()));
    let memory_md = refresh_memory_md_with_health(
        store,
        tenant_manager.as_ref(),
        MemoryMdOptions {
            tenant_id: Some(tenant_id.clone()),
            project_id: project_id.clone(),
            project_dir: project_dir.clone(),
            output: PathBuf::from("memory.md"),
            project_limit: 10,
            // Machine-wide takeaways are capped by default so they
            // cannot dominate project startup context.
            global_limit: 2,
            candidate_k: 40,
            explain_output: None,
        },
    )
    .await?;

    // 2. If enough dirty chunks have accumulated, spawn a detached
    //    background consolidation. Counting failures are non-fatal —
    //    session-start must never block or fail the session.
    let dirty = dirty_region_size(
        store,
        &project_dir,
        Some(tenant_id.clone()),
        project_id.clone(),
    )
    .await
    .unwrap_or(0);

    // The background child runs with stdio nulled, so a missing CLI
    // backend would fail invisibly. Preflight the selector here and
    // skip the spawn (with a reason) when no backend is available.
    let mut consolidation_spawned = false;
    let mut skip_reason: Option<String> = None;
    if dirty >= MIN_REGION {
        match crate::consolidate::select::select_consolidator() {
            Ok(_) => {
                let spawn = run_consolidate(
                    store,
                    ConsolidateOptions {
                        tenant_id: Some(tenant_id),
                        project_id,
                        project_dir: project_dir.clone(),
                        max_region: 50,
                        dry_run: false,
                        background: true,
                        force: false,
                        promote: false,
                        legacy_immediate: false,
                    },
                )
                .await;
                // A contended scope returns Ok with a "skipped" reason and no
                // child, so success alone does not mean one was started.
                consolidation_spawned = spawn
                    .as_ref()
                    .ok()
                    .and_then(|v| v.get("spawned_background").and_then(Value::as_bool))
                    .unwrap_or(false);
                if !consolidation_spawned {
                    skip_reason = match spawn.as_ref() {
                        Ok(value) => value
                            .get("skipped")
                            .and_then(Value::as_str)
                            .map(str::to_string),
                        // Reported rather than dropped: the spawn now resolves
                        // scope and takes locks in the parent, so a failure here
                        // is a real condition and used to surface as a silent
                        // "nothing happened".
                        Err(e) => Some(format!("spawn failed: {e}")),
                    };
                }
            }
            Err(e) => {
                skip_reason = Some(format!("no consolidator backend: {e}"));
            }
        }
    }

    Ok(json!({
        "memory_md": memory_md,
        "dirty_count": dirty,
        "consolidation_spawned": consolidation_spawned,
        "consolidation_skipped": skip_reason,
        "auto_scoped": auto_scoped,
        "consolidation_recovery": consolidation_recovery,
    }))
}

fn validated_project_scope(project_dir: &Path) -> Result<Option<ProjectScopeConfig>> {
    let scope = read_project_scope(project_dir)?;
    if let Some(scope) = &scope {
        TenantId::validate(&scope.tenant_id)?;
        ProjectId::validate_opt(scope.project_id.as_deref())?;
    }
    Ok(scope)
}

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

fn read_legacy_scope(path: &Path) -> Result<Option<(String, Option<String>)>> {
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            match std::fs::symlink_metadata(path) {
                Err(metadata_error) if metadata_error.kind() == std::io::ErrorKind::NotFound => {
                    return Ok(None)
                }
                Ok(_) => {
                    return Err(crate::error::MemdError::ValidationError(format!(
                        "unable to read {}: {error}",
                        path.display()
                    )))
                }
                Err(metadata_error) => {
                    return Err(crate::error::MemdError::ValidationError(format!(
                        "unable to inspect {} after read failure ({error}): {metadata_error}",
                        path.display()
                    )))
                }
            }
        }
        Err(error) => {
            return Err(crate::error::MemdError::ValidationError(format!(
                "unable to read {}: {error}",
                path.display()
            )))
        }
    };
    let scope: LegacyScopeConfig = serde_json::from_str(&text).map_err(|error| {
        crate::error::MemdError::ValidationError(format!(
            "failed to parse {}: {error}",
            path.display()
        ))
    })?;
    if scope.tenant_id.is_none() && scope.project_id.is_none() {
        return Ok(None);
    }
    let tenant_id = scope.tenant_id.ok_or_else(|| {
        crate::error::MemdError::ValidationError(format!("{} is missing tenant_id", path.display()))
    })?;
    TenantId::validate(&tenant_id)?;
    ProjectId::validate_opt(scope.project_id.as_deref())?;
    Ok(Some((tenant_id, scope.project_id)))
}

fn invalid_scope_response(path: &Path, error: &crate::error::MemdError) -> Value {
    json!({
        "skipped": "invalid_project_scope",
        "project_scope": path,
        "diagnostic": format!(
            "existing scope file was preserved because it is invalid or unreadable: {error}"
        ),
    })
}

/// Outcome of the auto-scope attempt when no scope file is present.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum AutoScopeOutcome {
    Created,
    AlreadyExists,
    SkippedDisabled,
    SkippedMarker,
}

/// Create a minimal `.memd/project_scope.json` for a repo that has no
/// scope yet. Honors `MEMD_AUTO_SCOPE=0` and a `.memd-skip` opt-out
/// marker. Writes ONLY `project_scope.json` (not the full `memd init`
/// payload) — implicit hooks should never touch `AGENTS.md` /
/// `CLAUDE.md` or write tenant guardrails on the user's behalf.
pub(super) fn maybe_auto_create_scope(
    project_dir: &Path,
    inputs: &AutoScopeInputs,
) -> Result<AutoScopeOutcome> {
    if !inputs.enabled {
        return Ok(AutoScopeOutcome::SkippedDisabled);
    }
    if project_dir.join(".memd-skip").exists() {
        return Ok(AutoScopeOutcome::SkippedMarker);
    }

    let project_id = derive_project_id(project_dir);
    let scope = ProjectScopeConfig {
        tenant_id: inputs.default_tenant.clone(),
        project_id: Some(project_id),
        interface: "cli".to_string(),
        cli_command: "memd".to_string(),
        agent_context_output: ".memd/context.md".to_string(),
        project_dir: project_dir.display().to_string(),
    };

    let memd_dir = project_dir.join(".memd");
    std::fs::create_dir_all(&memd_dir)?;
    let path = memd_dir.join("project_scope.json");
    let serialized = format!("{}\n", serde_json::to_string_pretty(&scope)?);
    let mut file = match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
    {
        Ok(file) => file,
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
            return Ok(AutoScopeOutcome::AlreadyExists);
        }
        Err(error) => return Err(error.into()),
    };
    if let Err(error) = file.write_all(serialized.as_bytes()) {
        drop(file);
        let _ = std::fs::remove_file(&path);
        return Err(error.into());
    }
    Ok(AutoScopeOutcome::Created)
}

/// Derive a `project_id` from the repo basename via `sanitize_id`.
/// A linked git worktree uses the basename of its main checkout, so every
/// worktree of one repo shares one project. Pathological inputs (`/`, `.`,
/// missing basename) fall back to `"project"`.
fn derive_project_id(project_dir: &Path) -> String {
    let main_checkout = main_checkout_of_linked_worktree(project_dir);
    let raw = main_checkout
        .as_deref()
        .unwrap_or(project_dir)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("");
    sanitize_id(raw, "project")
}

/// The main checkout directory when `project_dir` is a linked git worktree.
///
/// A linked worktree has a `.git` file holding `gitdir: <admin dir>`. The admin
/// dir has a `commondir` file that points at the main `.git` directory, whose
/// parent is the main checkout. This reads files only and never runs `git`.
/// Plain repos, submodules (no `commondir`), bare-repo worktrees (common dir
/// not named `.git`), and unreadable files all return `None`.
fn main_checkout_of_linked_worktree(project_dir: &Path) -> Option<PathBuf> {
    let dot_git = project_dir.join(".git");
    if !dot_git.is_file() {
        return None;
    }
    let pointer = std::fs::read_to_string(&dot_git).ok()?;
    let gitdir = pointer
        .lines()
        .find_map(|line| line.strip_prefix("gitdir:"))?;
    let admin_dir = project_dir.join(gitdir.trim());
    let commondir = std::fs::read_to_string(admin_dir.join("commondir")).ok()?;
    let common_dir = admin_dir.join(commondir.trim()).canonicalize().ok()?;
    if common_dir.file_name()? != ".git" {
        return None;
    }
    common_dir.parent().map(Path::to_path_buf)
}

/// Sanitise a raw string into an id safe for `TenantId::validate`
/// (ASCII alphanumeric + `_`, lowercased) and bounded by
/// `MAX_AUTO_ID_LEN` so the resulting directory names stay sane.
///
/// Non-ASCII characters are dropped (replaced with a single `_` run).
/// This is lossy for repo names like `café`, which becomes `caf`. We
/// accept the loss in v1 — anyone with a non-ASCII repo name can
/// override with `MEMD_DEFAULT_TENANT` / `memd init`.
fn sanitize_id(raw: &str, fallback: &str) -> String {
    let mut out = String::with_capacity(raw.len().min(MAX_AUTO_ID_LEN));
    let mut last_underscore = false;
    for ch in raw.chars() {
        if out.len() >= MAX_AUTO_ID_LEN {
            break;
        }
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_lowercase());
            last_underscore = false;
        } else if !last_underscore && !out.is_empty() {
            // Skip leading separators (out empty) and collapse runs.
            out.push('_');
            last_underscore = true;
        }
    }
    let trimmed = out.trim_end_matches('_').to_string();
    if trimmed.is_empty() {
        fallback.to_string()
    } else {
        trimmed
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hit_stats::{record_hits_to_data_dir, HitRecord};
    use crate::store::{MemoryStore, PersistentStore, PersistentStoreConfig};
    use crate::types::{ChunkType, MemoryChunk};
    use tempfile::tempdir;

    fn disabled_inputs() -> AutoScopeInputs {
        AutoScopeInputs {
            default_tenant: "ignored".to_string(),
            enabled: false,
        }
    }

    fn enabled_inputs(tenant: &str) -> AutoScopeInputs {
        AutoScopeInputs {
            default_tenant: tenant.to_string(),
            enabled: true,
        }
    }

    #[test]
    fn native_hook_payload_keeps_only_allowlisted_context() {
        let dir = tempdir().unwrap();
        let payload = json!({
            "session_id": "claude-session",
            "thread_id": "claude-thread",
            "agent_id": "worker-2",
            "parent_agent_id": "lead-1",
            "model": "claude-fable-5",
            "cwd": dir.path(),
            "prompt": "do not retain this prompt",
            "transcript_path": "/private/native-transcript.jsonl",
            "tool_input": {"secret": "do not retain this tool input"}
        });

        let context = parse_native_hook_context(
            NativeHookHarness::Claude,
            std::io::Cursor::new(serde_json::to_vec(&payload).unwrap()),
            Path::new("/unused"),
        )
        .unwrap();
        let serialized = serde_json::to_string(&context).unwrap();

        assert_eq!(context.harness.as_deref(), Some("claude"));
        assert_eq!(context.native_session_id.as_deref(), Some("claude-session"));
        assert_eq!(context.native_thread_id.as_deref(), Some("claude-thread"));
        assert_eq!(context.native_agent_id.as_deref(), Some("worker-2"));
        assert_eq!(context.native_parent_id.as_deref(), Some("lead-1"));
        assert_eq!(context.model.as_deref(), Some("claude-fable-5"));
        assert_eq!(context.cwd.as_deref(), dir.path().to_str());
        assert_eq!(
            native_hook_project_dir(Path::new("."), &context),
            dir.path()
        );
        assert_eq!(
            native_hook_project_dir(Path::new("/explicit/project"), &context),
            Path::new("/explicit/project")
        );
        assert!(!serialized.contains("prompt"));
        assert!(!serialized.contains("transcript"));
        assert!(!serialized.contains("tool_input"));
        assert!(!serialized.contains("do not retain"));
    }

    #[test]
    fn native_hook_payload_is_bounded() {
        let payload = vec![b' '; MAX_NATIVE_HOOK_BYTES as usize + 1];
        let error = parse_native_hook_context(
            NativeHookHarness::Codex,
            std::io::Cursor::new(payload),
            Path::new("."),
        )
        .unwrap_err();

        assert!(error.to_string().contains("exceeds 65536 bytes"));
    }

    #[tokio::test]
    async fn missing_scope_with_auto_disabled_is_a_clean_noop() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: dir.path().to_path_buf(),
            },
            disabled_inputs(),
        )
        .await
        .unwrap();
        assert_eq!(result["skipped"], "auto_scope_disabled");
        assert!(!dir.path().join(".memd/project_scope.json").exists());
    }

    #[tokio::test]
    async fn memd_skip_marker_suppresses_auto_scope() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join(".memd-skip"), "").unwrap();
        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: dir.path().to_path_buf(),
            },
            enabled_inputs("alice"),
        )
        .await
        .unwrap();
        assert_eq!(result["skipped"], "memd_skip_present");
        assert!(!dir.path().join(".memd/project_scope.json").exists());
    }

    #[tokio::test]
    async fn memd_skip_marker_suppresses_initialized_repository() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        let memd_dir = dir.path().join(".memd");
        std::fs::create_dir_all(&memd_dir).unwrap();
        let existing = ProjectScopeConfig {
            tenant_id: "preexisting".to_string(),
            project_id: Some("keep_me".to_string()),
            interface: "cli".to_string(),
            cli_command: "memd".to_string(),
            agent_context_output: ".memd/context.md".to_string(),
            project_dir: dir.path().display().to_string(),
        };
        let scope_bytes = format!("{}\n", serde_json::to_string_pretty(&existing).unwrap());
        std::fs::write(memd_dir.join("project_scope.json"), &scope_bytes).unwrap();
        std::fs::write(dir.path().join("memory.md"), "keep existing memory\n").unwrap();
        std::fs::write(dir.path().join(".memd-skip"), "").unwrap();

        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: dir.path().to_path_buf(),
            },
            enabled_inputs("ignored"),
        )
        .await
        .unwrap();

        assert_eq!(result["skipped"], "memd_skip_present");
        assert_eq!(
            std::fs::read(memd_dir.join("project_scope.json")).unwrap(),
            scope_bytes.as_bytes()
        );
        assert_eq!(
            std::fs::read_to_string(dir.path().join("memory.md")).unwrap(),
            "keep existing memory\n"
        );
    }

    #[tokio::test]
    async fn auto_scope_writes_minimal_project_scope_and_runs_session() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        // Give the dir a stable basename so we can assert on project_id.
        let project_dir = dir.path().join("my-cool-repo");
        std::fs::create_dir_all(&project_dir).unwrap();

        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: project_dir.clone(),
            },
            enabled_inputs("alice"),
        )
        .await
        .unwrap();

        assert_eq!(result["auto_scoped"], true);
        assert!(result.get("memory_md").is_some());

        let scope: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(project_dir.join(".memd/project_scope.json")).unwrap(),
        )
        .unwrap();
        assert_eq!(scope["tenant_id"], "alice");
        assert_eq!(scope["project_id"], "my_cool_repo");
        assert_eq!(scope["interface"], "cli");
        // Auto-scope must NOT have touched AGENTS.md / CLAUDE.md or
        // written tenant_scope.json — implicit hooks stay minimal.
        assert!(!project_dir.join("AGENTS.md").exists());
        assert!(!project_dir.join("CLAUDE.md").exists());
        assert!(!project_dir.join(".memd/tenant_scope.json").exists());
        assert!(!project_dir.join(".memd/memory_guardrails.md").exists());
        assert!(project_dir.join("memory.md").exists());
    }

    #[tokio::test]
    async fn existing_scope_is_left_alone() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        // Write the full ProjectScopeConfig schema — that's what
        // `memd init` and our own auto-scope path emit, and what
        // downstream readers (memory_md::read_project_scope) require.
        let existing = ProjectScopeConfig {
            tenant_id: "preexisting".to_string(),
            project_id: Some("keep_me".to_string()),
            interface: "cli".to_string(),
            cli_command: "memd".to_string(),
            agent_context_output: ".memd/context.md".to_string(),
            project_dir: dir.path().display().to_string(),
        };
        std::fs::write(
            dir.path().join(".memd/project_scope.json"),
            format!("{}\n", serde_json::to_string_pretty(&existing).unwrap()),
        )
        .unwrap();
        let before = std::fs::read_to_string(dir.path().join(".memd/project_scope.json")).unwrap();

        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: dir.path().to_path_buf(),
            },
            enabled_inputs("would_overwrite"),
        )
        .await
        .unwrap();

        assert_eq!(result["auto_scoped"], false);
        let after = std::fs::read_to_string(dir.path().join(".memd/project_scope.json")).unwrap();
        assert_eq!(
            before, after,
            "auto-scope must not overwrite existing scope"
        );
    }

    #[test]
    fn derive_project_id_handles_punctuation_and_edge_cases() {
        assert_eq!(
            derive_project_id(Path::new("/tmp/Foo-Bar.v2")),
            "foo_bar_v2"
        );
        assert_eq!(derive_project_id(Path::new("/tmp/__weird__")), "weird");
        assert_eq!(derive_project_id(Path::new("/")), "project");
        // `.` resolves to file_name() == None — must fall back, not panic.
        assert_eq!(derive_project_id(Path::new(".")), "project");
        // Non-ASCII chars are dropped (lossy by design, documented).
        assert_eq!(derive_project_id(Path::new("/tmp/café")), "caf");
    }

    /// Lay out a main checkout and one linked worktree the way `git worktree
    /// add` does, without running git. Returns (main checkout, worktree).
    fn linked_worktree_layout(root: &Path, relative_gitdir: bool) -> (PathBuf, PathBuf) {
        let main = root.join("My-Repo");
        let git_dir = main.join(".git");
        let admin = git_dir.join("worktrees/cc-wt");
        std::fs::create_dir_all(&admin).unwrap();
        std::fs::write(admin.join("commondir"), "../..\n").unwrap();
        let worktree = main.join(".claude/worktrees/cc-20261017-074438-555a");
        std::fs::create_dir_all(&worktree).unwrap();
        std::fs::write(
            admin.join("gitdir"),
            format!("{}/.git\n", worktree.display()),
        )
        .unwrap();
        let target = if relative_gitdir {
            "../../../.git/worktrees/cc-wt".to_string()
        } else {
            admin.display().to_string()
        };
        std::fs::write(worktree.join(".git"), format!("gitdir: {target}\n")).unwrap();
        (main, worktree)
    }

    #[test]
    fn derive_project_id_resolves_a_linked_worktree_to_its_main_checkout() {
        for relative in [false, true] {
            let tmp = tempdir().unwrap();
            let (main, worktree) = linked_worktree_layout(tmp.path(), relative);
            assert_eq!(derive_project_id(&main), "my_repo");
            assert_eq!(
                derive_project_id(&worktree),
                "my_repo",
                "relative={relative}"
            );
        }
    }

    #[test]
    fn derive_project_id_keeps_the_basename_for_plain_repos_and_submodules() {
        let tmp = tempdir().unwrap();
        let plain = tmp.path().join("Plain-Repo");
        std::fs::create_dir_all(plain.join(".git")).unwrap();
        assert_eq!(derive_project_id(&plain), "plain_repo");

        let non_git = tmp.path().join("scratch");
        std::fs::create_dir_all(&non_git).unwrap();
        assert_eq!(derive_project_id(&non_git), "scratch");

        // A submodule has a `.git` file but no `commondir`: it is its own project.
        let super_repo = tmp.path().join("super");
        let module_git = super_repo.join(".git/modules/sub");
        std::fs::create_dir_all(&module_git).unwrap();
        let submodule = super_repo.join("Sub-Module");
        std::fs::create_dir_all(&submodule).unwrap();
        std::fs::write(
            submodule.join(".git"),
            format!("gitdir: {}\n", module_git.display()),
        )
        .unwrap();
        assert_eq!(derive_project_id(&submodule), "sub_module");

        // A dangling or malformed `.git` file falls back to the basename.
        let broken = tmp.path().join("Broken-Tree");
        std::fs::create_dir_all(&broken).unwrap();
        std::fs::write(broken.join(".git"), "gitdir: /does/not/exist\n").unwrap();
        assert_eq!(derive_project_id(&broken), "broken_tree");
    }

    #[test]
    fn sanitize_id_caps_length_and_validates_against_tenant_rules() {
        let huge = "a".repeat(500);
        let out = sanitize_id(&huge, "fallback");
        assert!(
            out.len() <= MAX_AUTO_ID_LEN,
            "len {} should be capped at {}",
            out.len(),
            MAX_AUTO_ID_LEN
        );
        // Output of sanitize_id must always satisfy TenantId rules so
        // it can safely be used as both tenant_id and project_id.
        assert!(TenantId::validate(&out).is_ok());
        // Hyphens / dots / spaces collapse to single underscore.
        assert_eq!(sanitize_id("Felix-Schulz", "x"), "felix_schulz");
        assert_eq!(sanitize_id("   ", "fallback"), "fallback");
    }

    #[test]
    fn from_env_falls_back_to_user_then_default() {
        // Pure smoke check on the env precedence chain — we don't
        // mutate process env (parallel tests share it). Call
        // and assert the result is non-empty and valid as a tenant.
        let inputs = AutoScopeInputs::from_env();
        assert!(!inputs.default_tenant.is_empty());
        assert!(
            TenantId::validate(&inputs.default_tenant).is_ok(),
            "from_env produced an invalid tenant_id: {:?}",
            inputs.default_tenant
        );
    }

    #[tokio::test]
    async fn invalid_existing_scope_is_preserved_with_diagnostic() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        let project_dir = dir.path().join("recover-me");
        std::fs::create_dir_all(project_dir.join(".memd")).unwrap();
        let scope_path = project_dir.join(".memd/project_scope.json");
        let original = b"{not json";
        std::fs::write(&scope_path, original).unwrap();

        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: project_dir.clone(),
            },
            enabled_inputs("alice"),
        )
        .await
        .unwrap();

        assert_eq!(result["skipped"], "invalid_project_scope");
        assert_eq!(result["project_scope"], scope_path.display().to_string());
        assert!(result["diagnostic"]
            .as_str()
            .unwrap()
            .contains("was preserved"));
        assert_eq!(std::fs::read(&scope_path).unwrap(), original);
        assert!(!project_dir.join("memory.md").exists());
    }

    #[tokio::test]
    async fn invalid_legacy_scope_is_preserved_without_creating_project_scope() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        let project_dir = dir.path().join("legacy-repo");
        std::fs::create_dir_all(project_dir.join(".memd")).unwrap();
        let legacy_path = project_dir.join(".memd/config.json");
        let project_scope_path = project_dir.join(".memd/project_scope.json");
        let original = b"{not legacy json";
        std::fs::write(&legacy_path, original).unwrap();

        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: project_dir.clone(),
            },
            enabled_inputs("would_mask_routing"),
        )
        .await
        .unwrap();

        assert_eq!(result["skipped"], "invalid_project_scope");
        assert_eq!(result["project_scope"], legacy_path.display().to_string());
        assert!(result["diagnostic"]
            .as_str()
            .unwrap()
            .contains("was preserved"));
        assert_eq!(std::fs::read(legacy_path).unwrap(), original);
        assert!(!project_scope_path.exists());
        assert!(!project_dir.join("memory.md").exists());
    }

    #[tokio::test]
    async fn legacy_config_without_scope_is_preserved_while_auto_scoping() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        let project_dir = dir.path().join("wiki-repo");
        std::fs::create_dir_all(project_dir.join(".memd")).unwrap();
        let legacy_path = project_dir.join(".memd/config.json");
        let original = b"{\n  \"wiki\": {\"outdir\": \"wiki\"}\n}\n";
        std::fs::write(&legacy_path, original).unwrap();

        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: project_dir.clone(),
            },
            enabled_inputs("alice"),
        )
        .await
        .unwrap();

        assert_eq!(result["auto_scoped"], true);
        assert_eq!(std::fs::read(&legacy_path).unwrap(), original);
        let scope: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(project_dir.join(".memd/project_scope.json")).unwrap(),
        )
        .unwrap();
        assert_eq!(scope["tenant_id"], "alice");
        assert_eq!(scope["project_id"], "wiki_repo");
        assert!(project_dir.join("memory.md").exists());
    }

    #[tokio::test]
    async fn valid_legacy_scope_is_preserved_as_fallback() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        let project_dir = dir.path().join("legacy-repo");
        std::fs::create_dir_all(project_dir.join(".memd")).unwrap();
        let legacy_path = project_dir.join(".memd/config.json");
        let original = b"{\n  \"tenant_id\": \"legacy_tenant\",\n  \"project_id\": \"legacy_project\",\n  \"wiki\": {\"outdir\": \"wiki\"}\n}\n";
        std::fs::write(&legacy_path, original).unwrap();

        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: project_dir.clone(),
            },
            enabled_inputs("would_replace_legacy"),
        )
        .await
        .unwrap();

        assert_eq!(result["auto_scoped"], false);
        assert_eq!(result["memory_md"]["tenant_id"], "legacy_tenant");
        assert_eq!(result["memory_md"]["project_id"], "legacy_project");
        assert_eq!(std::fs::read(&legacy_path).unwrap(), original);
        assert!(!project_dir.join(".memd/project_scope.json").exists());
        assert!(project_dir.join("memory.md").exists());
    }

    #[tokio::test]
    async fn legacy_project_without_tenant_remains_invalid() {
        let store = MemoryStore::new();
        let dir = tempdir().unwrap();
        let project_dir = dir.path().join("legacy-repo");
        std::fs::create_dir_all(project_dir.join(".memd")).unwrap();
        let legacy_path = project_dir.join(".memd/config.json");
        let original = b"{\"project_id\":\"must_not_be_replaced\"}\n";
        std::fs::write(&legacy_path, original).unwrap();

        let result = run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: project_dir.clone(),
            },
            enabled_inputs("would_mask_routing"),
        )
        .await
        .unwrap();

        assert_eq!(result["skipped"], "invalid_project_scope");
        assert_eq!(result["project_scope"], legacy_path.display().to_string());
        assert!(result["diagnostic"]
            .as_str()
            .unwrap()
            .contains("missing tenant_id"));
        assert_eq!(std::fs::read(&legacy_path).unwrap(), original);
        assert!(!project_dir.join(".memd/project_scope.json").exists());
        assert!(!project_dir.join("memory.md").exists());
    }

    #[test]
    fn auto_scope_create_new_does_not_truncate_existing_file() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        let scope_path = dir.path().join(".memd/project_scope.json");
        let original = b"created by a concurrent startup\n";
        std::fs::write(&scope_path, original).unwrap();

        let outcome = maybe_auto_create_scope(dir.path(), &enabled_inputs("alice")).unwrap();

        assert_eq!(outcome, AutoScopeOutcome::AlreadyExists);
        assert_eq!(std::fs::read(scope_path).unwrap(), original);
    }

    #[tokio::test]
    async fn session_start_uses_central_exposure_ledger() {
        let data = tempdir().unwrap();
        let project = tempdir().unwrap();
        let mut config = PersistentStoreConfig {
            data_dir: data.path().to_path_buf(),
            enable_dense_search: false,
            enable_hybrid_search: false,
            enable_tiered_search: false,
            backfill_hnsw_on_startup: false,
            backfill_canonical_text_on_startup: false,
            ..Default::default()
        };
        let store = PersistentStore::open(config.clone()).unwrap();
        let tenant = TenantId::new("central_tenant").unwrap();
        let project_id = "central_project";
        let chunk_id = store
            .add(
                MemoryChunk::new(
                    tenant.clone(),
                    "Validation: central-only exposure keeps an old startup fact active. \
                     Agent action: Verify session-start reads the store exposure ledger.",
                    ChunkType::Summary,
                )
                .with_project(ProjectId::from(project_id))
                .with_tags(vec!["kind:evidence".to_string()]),
            )
            .await
            .unwrap();
        store
            .metadata()
            .force_timestamp_created(&chunk_id, 1)
            .unwrap();
        record_hits_to_data_dir(
            data.path(),
            &[HitRecord {
                ts_ms: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_millis() as i64,
                chunk_id: chunk_id.to_string(),
                tenant_id: tenant.to_string(),
                project_id: Some(project_id.to_string()),
                query_mode: "generic".to_string(),
                rank: 1,
                score: 1.0,
                rendered: true,
            }],
        );
        std::fs::create_dir_all(project.path().join(".memd")).unwrap();
        let scope = ProjectScopeConfig {
            tenant_id: tenant.to_string(),
            project_id: Some(project_id.to_string()),
            interface: "cli".to_string(),
            cli_command: "memd".to_string(),
            agent_context_output: ".memd/context.md".to_string(),
            project_dir: project.path().display().to_string(),
        };
        std::fs::write(
            project.path().join(".memd/project_scope.json"),
            format!("{}\n", serde_json::to_string_pretty(&scope).unwrap()),
        )
        .unwrap();
        drop(store);
        config.read_only = true;
        let store = PersistentStore::open(config).unwrap();

        run_session_start_inner(
            &store,
            SessionStartOptions {
                project_dir: project.path().to_path_buf(),
            },
            enabled_inputs("ignored"),
        )
        .await
        .unwrap();

        let rendered = std::fs::read_to_string(project.path().join("memory.md")).unwrap();
        assert!(rendered.contains(&chunk_id.to_string()), "{rendered}");
        assert!(
            rendered.contains("priority: `14.0`"),
            "central exposure should prevent the old-chunk penalty:\n{rendered}"
        );
    }
}