openlatch-client 0.6.19

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! SessionStart event enrichment.
//!
//! The daemon intercepts session_start hook events from Claude Code (via the
//! existing /hooks endpoint), walks the in-memory `ContentHashCache`, and
//! injects `openlatch.declared_*` fields into the `data` payload before
//! forwarding to cloud. The cloud's session_start handler reads these fields,
//! does cache lookup for each declared source, and returns the aggregate
//! verdict (per design §4.10 / Phase-2 §2).
//!
//! Enrichment is best-effort: any failure logs `OL-2007` and the un-enriched
//! envelope continues through the normal pipeline (fail-open).

use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::Mutex;

use serde::Serialize;
use sha2::{Digest, Sha256};
use tokio::sync::mpsc;

use super::cache::ContentHashCache;
use super::monitor::ConfigChangeRequest;

/// Bound on the recent-cwd cache. Discover-project-root walks up to 25
/// `stat()` calls per hook event; a process typically sees a handful of
/// distinct cwds across its session, so a tiny ring is enough.
const PROJECT_ROOT_CACHE_CAP: usize = 32;

type ProjectRootCache = Mutex<VecDeque<(String, Option<PathBuf>)>>;

/// (cwd_string, resolved_project_root) pairs in FIFO order. A small
/// `Mutex<VecDeque>` outperforms an `LruCache` crate for this size and
/// keeps the dependency footprint flat.
static PROJECT_ROOT_CACHE: std::sync::LazyLock<ProjectRootCache> =
    std::sync::LazyLock::new(|| Mutex::new(VecDeque::with_capacity(PROJECT_ROOT_CACHE_CAP)));

/// One declared config source attached to a session_start payload. The cloud
/// resolves `(source_id, content_hash)` against its verdict cache.
#[derive(Debug, Clone, Serialize)]
pub struct DeclaredSource {
    /// `{agent}:{kind}:{path_hash}` — opaque to the client.
    pub source_id: String,
    /// Hex SHA-256 of the canonical content (matches `configcontenthash` on
    /// the corresponding `ai.openlatch.config.*` event).
    pub content_hash: String,
    /// Hex SHA-256 of the absolute path (privacy-preserving — never the
    /// path itself).
    pub path_hash: String,
}

/// Errors returned by [`enrich_session_start`]. The daemon logs them under
/// `ERR_INVENTORY_ENRICH_FAILED` and continues fail-open.
#[derive(thiserror::Error, Debug)]
pub enum EnrichError {
    #[error("cwd missing from session_start payload")]
    CwdMissing,
}

/// Enrich a session_start `data` payload in place. Adds
/// `openlatch.declared_mcp_sources`, `openlatch.declared_skills`,
/// `openlatch.declared_rules_hash`, and `openlatch.cwd` (path hash). When
/// `monitor_tx` is provided and a project root is discovered above the
/// cwd, dispatches a `ProjectScopeRegister` so project-scope manifest
/// paths get scanned.
///
/// Operates directly on the envelope's `data: Option<Value>` slot to
/// avoid a `serde_json::to_value` + `from_value` round-trip per session.
pub async fn enrich_session_start(
    data: &mut Option<serde_json::Value>,
    cache: &ContentHashCache,
    monitor_tx: Option<&mpsc::Sender<ConfigChangeRequest>>,
) -> Result<(), EnrichError> {
    // By shape, like every other agent read: Claude Code says `cwd`, Cline
    // sends `workspaceRoots` and no `cwd` at all.
    let cwd = data
        .as_ref()
        .and_then(crate::core::envelope::normalize::cwd_of)
        .ok_or(EnrichError::CwdMissing)?
        .into_owned();

    if let Some(data) = data.as_ref() {
        let _ = try_register_project_for(data, monitor_tx).await;
    }

    let mut mcp_sources: Vec<DeclaredSource> = Vec::new();
    let mut skill_sources: Vec<DeclaredSource> = Vec::new();
    let mut rules_pairs: Vec<([u8; 32], [u8; 32])> = Vec::new();

    for entry in cache.snapshot() {
        let path_hash_hex = hex::encode(entry.path_hash);
        let source_id = format!("{}:{}:{}", entry.agent, entry.kind, path_hash_hex);
        let declared = DeclaredSource {
            source_id,
            content_hash: hex::encode(entry.content_hash),
            path_hash: path_hash_hex,
        };
        match entry.kind.as_str() {
            "mcp" => mcp_sources.push(declared),
            "skill" => skill_sources.push(declared),
            "rules" => rules_pairs.push((entry.path_hash, entry.content_hash)),
            _ => {}
        }
    }

    rules_pairs.sort_by_key(|a| a.0);
    let mut combined = Sha256::new();
    for (ph, ch) in &rules_pairs {
        combined.update(ph);
        combined.update(ch);
    }
    let rules_hash_hex = hex::encode(combined.finalize());
    let cwd_hash_hex = hex::encode(Sha256::digest(cwd.as_bytes()));

    if let Some(obj) = data.as_mut().and_then(|v| v.as_object_mut()) {
        obj.insert(
            "openlatch.declared_mcp_sources".into(),
            serde_json::to_value(&mcp_sources).unwrap_or_default(),
        );
        obj.insert(
            "openlatch.declared_skills".into(),
            serde_json::to_value(&skill_sources).unwrap_or_default(),
        );
        obj.insert(
            "openlatch.declared_rules_hash".into(),
            serde_json::Value::String(rules_hash_hex),
        );
        obj.insert(
            "openlatch.cwd".into(),
            serde_json::Value::String(cwd_hash_hex),
        );
    }

    let bucket = match mcp_sources.len() + skill_sources.len() + rules_pairs.len() {
        0..=5 => "1-5",
        6..=20 => "6-20",
        21..=50 => "21-50",
        _ => "50+",
    };
    crate::telemetry::capture_global(crate::telemetry::Event::config_session_start_enriched(
        "claude-code",
        bucket,
    ));

    Ok(())
}

/// Walk up from `cwd`, discover a project root, and (if `monitor_tx` is
/// connected) dispatch a `ProjectScopeRegister`. Returns the discovered
/// root (or `None` if no project markers are nearby) so callers that need
/// it for further enrichment can reuse the result.
///
/// The monitor's `registered_projects: HashSet<PathBuf>` already dedupes
/// repeat registrations, so this is safe to call on every hook event that
/// carries a `cwd` — not just SessionStart. That closes the daemon-
/// started-mid-session timing window described in the inventory plan.
pub async fn try_register_project_from_cwd(
    cwd: &str,
    monitor_tx: Option<&mpsc::Sender<ConfigChangeRequest>>,
) -> Option<PathBuf> {
    let project_root = cached_project_root(cwd);
    if let (Some(root), Some(tx)) = (&project_root, monitor_tx) {
        let _ = tx
            .send(ConfigChangeRequest::ProjectScopeRegister {
                project_root: root.clone(),
                start: None,
            })
            .await;
    }
    project_root
}

/// Register the project an event belongs to, from the payload's own shape.
///
/// A workspace root the agent DECLARED (`normalize::declared_workspace_root_of`
/// — Cline's `workspaceRoots`) is the project root as stated: Cline resolves
/// `.clinerules/` and `.cline/rules/` against it whether or not the directory
/// holds a `.git`, so a marker walk that finds none would leave every
/// workspace rule unwatched. Anything else — a bare `cwd` — takes the marker
/// walk, as it always has.
///
/// Never the home directory: there `.cline/skills` is the GLOBAL skills tree,
/// and registering home as a project would report it a second time as
/// project-scoped.
///
/// OpenCode states both ends of its project walk (AGT-6 D-11): its `worktree`
/// is the root and its `directory` the start, so OpenCode run in `repo/a` and
/// then in `repo/b` reads both — a marker walk from the cwd could stop below
/// the worktree. Outside a repository OpenCode reports a worktree of `/`; that,
/// a drive root and home are refused, and nothing is registered.
pub async fn try_register_project_for(
    data: &serde_json::Value,
    monitor_tx: Option<&mpsc::Sender<ConfigChangeRequest>>,
) -> Option<PathBuf> {
    if let Some((worktree, directory)) = opencode_walk_of(data) {
        // Both ends resolved on disk first: a lexical `..` or a symlink could
        // otherwise pass the root refusal (`/tmp/..`) or the containment check
        // (`<root>/sub/../../outside`) and point the walk outside the worktree.
        let root = real_dir(worktree)
            .and_then(|r| declared_project_root(&r.to_string_lossy()))
            .filter(|r| r.parent().is_some() && !is_real_home(r))?;
        let start = directory.and_then(real_dir).filter(|d| {
            crate::path_compat::dedup_key(d).starts_with(crate::path_compat::dedup_key(&root))
        });
        if let Some(tx) = monitor_tx {
            let _ = tx
                .send(ConfigChangeRequest::ProjectScopeRegister {
                    project_root: root.clone(),
                    start,
                })
                .await;
        }
        return Some(root);
    }
    if let Some(declared) = crate::core::envelope::normalize::declared_workspace_root_of(data) {
        // The agent stated its root, so no marker walk second-guesses it — not
        // even when the root is refused (home, not a directory): a walk from
        // home finds `~/.openlatch` and would register home all the same.
        let root = declared_project_root(declared)?;
        if let Some(tx) = monitor_tx {
            let _ = tx
                .send(ConfigChangeRequest::ProjectScopeRegister {
                    project_root: root.clone(),
                    start: None,
                })
                .await;
        }
        return Some(root);
    }
    let cwd = crate::core::envelope::normalize::cwd_of(data)?;
    try_register_project_from_cwd(&cwd, monitor_tx).await
}

/// OpenCode's `worktree` and `directory`, when the payload is OpenCode-shaped
/// and names a worktree.
fn opencode_walk_of(data: &serde_json::Value) -> Option<(&str, Option<&str>)> {
    if !crate::core::envelope::normalize::is_opencode_shape(data) {
        return None;
    }
    let text = |key: &str| {
        data.get(key)
            .and_then(serde_json::Value::as_str)
            .filter(|s| !s.is_empty())
    };
    Some((text("worktree")?, text("directory")))
}

/// `raw` resolved on disk — `..` and symlinks followed — when it is an absolute
/// path to an existing directory, without Windows' verbatim prefix.
fn real_dir(raw: &str) -> Option<PathBuf> {
    let path = PathBuf::from(raw);
    if !path.is_absolute() {
        return None;
    }
    let real = std::fs::canonicalize(&path).ok()?;
    real.is_dir()
        .then(|| PathBuf::from(crate::path_compat::display_path(&real)))
}

/// Whether `dir` is the home directory once both are resolved on disk.
fn is_real_home(dir: &Path) -> bool {
    dirs::home_dir()
        .and_then(|h| std::fs::canonicalize(h).ok())
        .is_some_and(|home| {
            crate::path_compat::dedup_key(&home) == crate::path_compat::dedup_key(dir)
        })
}

/// The declared workspace root, when it is a directory that is not home.
fn declared_project_root(declared: &str) -> Option<PathBuf> {
    let root = PathBuf::from(declared);
    if !root.is_absolute() || !root.is_dir() {
        return None;
    }
    let is_home = dirs::home_dir().is_some_and(|home| {
        crate::path_compat::dedup_key(&home) == crate::path_compat::dedup_key(&root)
    });
    (!is_home).then_some(root)
}

/// Wrap `discover_project_root` with a process-wide FIFO cache keyed by cwd
/// string. Same-cwd repeats become one `Mutex` lookup; cold misses pay the
/// 25-stat walk once.
fn cached_project_root(cwd: &str) -> Option<PathBuf> {
    if let Ok(cache) = PROJECT_ROOT_CACHE.lock() {
        if let Some((_, hit)) = cache.iter().find(|(k, _)| k == cwd) {
            return hit.clone();
        }
        // Drop the guard before doing the filesystem walk so we don't hold
        // it across syscalls that other callers might be racing for.
        drop(cache);
    }
    let resolved = discover_project_root(Path::new(cwd));
    if let Ok(mut cache) = PROJECT_ROOT_CACHE.lock() {
        if !cache.iter().any(|(k, _)| k == cwd) {
            if cache.len() >= PROJECT_ROOT_CACHE_CAP {
                cache.pop_front();
            }
            cache.push_back((cwd.to_string(), resolved.clone()));
        }
    }
    resolved
}

/// Walk up from `cwd` looking for project markers (`.git`, `.hg`, `.svn`,
/// `.openlatch`, `.mcp.json`). Returns `Some(root)` if found within 5 levels.
pub fn discover_project_root(cwd: &Path) -> Option<PathBuf> {
    const MARKERS: &[&str] = &[".git", ".hg", ".svn", ".openlatch", ".mcp.json"];
    let mut current = cwd.to_path_buf();
    for _ in 0..5 {
        for marker in MARKERS {
            if current.join(marker).exists() {
                return Some(current);
            }
        }
        if !current.pop() {
            break;
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::daemon::config_monitor::cache::CacheEntry;
    use std::time::Instant;

    fn cache_entry(path: &str, kind: &str, content: u8) -> CacheEntry {
        CacheEntry {
            path: PathBuf::from(path),
            subpath: None,
            path_hash: Sha256::digest(path.as_bytes()).into(),
            content_hash: [content; 32],
            last_observed: Instant::now(),
            kind: kind.into(),
            agent: "claude-code".into(),
        }
    }

    #[tokio::test]
    async fn enrich_populates_declared_sources_from_cache() {
        let cache = ContentHashCache::new(64);
        cache.insert(cache_entry("/etc/claude/.mcp.json", "mcp", 1));
        cache.insert(cache_entry("/etc/claude/skills/a.md", "skill", 2));
        cache.insert(cache_entry("/etc/claude/CLAUDE.md", "rules", 3));

        let mut data = Some(serde_json::json!({"cwd": "/tmp/test"}));
        enrich_session_start(&mut data, &cache, None).await.unwrap();

        let data = data.unwrap();
        let mcp = data.get("openlatch.declared_mcp_sources").unwrap();
        assert_eq!(mcp.as_array().unwrap().len(), 1);
        assert_eq!(
            mcp[0]["content_hash"].as_str().unwrap(),
            hex::encode([1u8; 32])
        );
        let skills = data.get("openlatch.declared_skills").unwrap();
        assert_eq!(skills.as_array().unwrap().len(), 1);
        let rules_hash = data.get("openlatch.declared_rules_hash").unwrap();
        assert!(rules_hash.is_string());
        assert!(data.get("openlatch.cwd").unwrap().is_string());
    }

    /// Cline names no `cwd`; its `task_start` sends `workspaceRoots`, and the
    /// enrichment reads it by shape like every other agent read.
    #[tokio::test]
    async fn enrich_reads_clines_workspace_root() {
        let cache = ContentHashCache::new(64);
        cache.insert(cache_entry("/etc/claude/.mcp.json", "mcp", 1));
        let mut data = Some(serde_json::json!({
            "taskId": "conv_1",
            "hookName": "TaskStart",
            "workspaceRoots": ["/tmp/work"],
            "taskStart": {"taskMetadata": {}}
        }));
        enrich_session_start(&mut data, &cache, None).await.unwrap();
        let data = data.unwrap();
        assert_eq!(
            data["openlatch.cwd"],
            hex::encode(Sha256::digest(b"/tmp/work"))
        );
        assert_eq!(
            data["openlatch.declared_mcp_sources"]
                .as_array()
                .map(Vec::len),
            Some(1)
        );
    }

    #[tokio::test]
    async fn enrich_returns_err_when_cwd_missing() {
        let cache = ContentHashCache::new(64);
        let mut data = Some(serde_json::json!({}));
        let err = enrich_session_start(&mut data, &cache, None)
            .await
            .unwrap_err();
        assert!(matches!(err, EnrichError::CwdMissing));
    }

    /// Cline's declared workspace root registers as the project, marker or
    /// not; a bare cwd with no marker still registers nothing.
    #[tokio::test]
    async fn a_declared_workspace_root_registers_without_a_marker() {
        let tmp = tempfile::tempdir().unwrap();
        let work = tmp.path().join("work");
        std::fs::create_dir_all(work.join(".clinerules")).unwrap();
        let (tx, mut rx) = mpsc::channel(4);

        let cline = serde_json::json!({"taskId": "t", "workspaceRoots": [work.to_string_lossy()]});
        assert_eq!(
            try_register_project_for(&cline, Some(&tx)).await,
            Some(work.clone())
        );
        match rx.try_recv() {
            Ok(ConfigChangeRequest::ProjectScopeRegister { project_root, .. }) => {
                assert_eq!(project_root, work)
            }
            other => panic!("expected a registration, got {other:?}"),
        }

        let bare = serde_json::json!({"cwd": "/__nonexistent_openlatch_test__/a/b"});
        assert_eq!(try_register_project_for(&bare, Some(&tx)).await, None);
        assert!(rx.try_recv().is_err());

        // Home is never a project: its `.cline/skills` is the global tree.
        if let Some(home) = dirs::home_dir() {
            let at_home = serde_json::json!({"workspaceRoots": [home.to_string_lossy()]});
            assert_eq!(try_register_project_for(&at_home, None).await, None);
        }
    }

    fn opencode_event(worktree: &Path, directory: &Path) -> serde_json::Value {
        serde_json::json!({
            "opencode_hook": "chat.message",
            "opencode_client": "cli",
            "session_id": "ses_1",
            "worktree": worktree.to_string_lossy(),
            "directory": directory.to_string_lossy(),
        })
    }

    /// OpenCode's worktree is the root and its directory the start, marker or
    /// not (AGT-6 D-11).
    #[tokio::test]
    async fn opencode_registers_its_worktree_with_its_directory_as_the_start() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = real_dir(&tmp.path().to_string_lossy())
            .unwrap()
            .join("repo");
        let start = repo.join("a").join("b");
        std::fs::create_dir_all(&start).unwrap();
        let (tx, mut rx) = mpsc::channel(4);

        let event = opencode_event(&repo, &start);
        assert_eq!(
            try_register_project_for(&event, Some(&tx)).await,
            Some(repo.clone())
        );
        match rx.try_recv() {
            Ok(ConfigChangeRequest::ProjectScopeRegister {
                project_root,
                start: got,
            }) => {
                assert_eq!(project_root, repo);
                assert_eq!(got, Some(start.clone()));
            }
            other => panic!("expected a registration, got {other:?}"),
        }

        // A directory outside the worktree is no start.
        let elsewhere = opencode_event(&repo, tmp.path());
        try_register_project_for(&elsewhere, Some(&tx)).await;
        match rx.try_recv() {
            Ok(ConfigChangeRequest::ProjectScopeRegister { start, .. }) => {
                assert_eq!(start, None)
            }
            other => panic!("expected a registration, got {other:?}"),
        }
    }

    /// Outside a repository OpenCode reports `/` as its worktree: refused, as
    /// home is, and no marker walk from the directory second-guesses it.
    #[tokio::test]
    async fn opencode_worktree_of_root_or_home_is_refused() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = std::fs::canonicalize(tmp.path()).unwrap();
        std::fs::create_dir_all(dir.join(".git")).unwrap();
        let (tx, mut rx) = mpsc::channel(4);
        let fs_root = dir.ancestors().last().unwrap().to_path_buf();
        let at_root = opencode_event(&fs_root, &dir);
        assert_eq!(try_register_project_for(&at_root, Some(&tx)).await, None);
        if let Some(home) = dirs::home_dir() {
            let at_home = opencode_event(&home, &home);
            assert_eq!(try_register_project_for(&at_home, Some(&tx)).await, None);
        }
        assert!(rx.try_recv().is_err(), "nothing registered");
    }

    /// A lexical `..` never takes OpenCode's walk outside its worktree, and a
    /// root spelled through `..` is still refused (AGT-6 D-11).
    #[tokio::test]
    async fn opencode_traversal_and_root_aliases_are_resolved_before_the_checks() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = real_dir(&tmp.path().to_string_lossy()).unwrap();
        let repo = dir.join("repo");
        let outside = dir.join("outside");
        std::fs::create_dir_all(repo.join("sub")).unwrap();
        std::fs::create_dir_all(&outside).unwrap();
        let (tx, mut rx) = mpsc::channel(4);

        let escaping = repo.join("sub").join("..").join("..").join("outside");
        let event = opencode_event(&repo, &escaping);
        assert_eq!(
            try_register_project_for(&event, Some(&tx)).await,
            Some(repo.clone())
        );
        match rx.try_recv() {
            Ok(ConfigChangeRequest::ProjectScopeRegister {
                project_root,
                start,
            }) => {
                assert_eq!(project_root, repo);
                assert_eq!(start, None, "a start that resolves outside is no start");
            }
            other => panic!("expected a registration, got {other:?}"),
        }

        // `<repo>/sub/..` is the worktree itself, resolved.
        let dotted = opencode_event(&repo.join("sub").join(".."), &repo.join("sub"));
        assert_eq!(
            try_register_project_for(&dotted, Some(&tx)).await,
            Some(repo.clone())
        );
        let _ = rx.try_recv();

        // The filesystem root spelled `<top>/..` is still the root.
        let top = dir.ancestors().collect::<Vec<_>>();
        let top = top[top.len() - 2];
        let alias = opencode_event(&top.join(".."), &dir);
        assert_eq!(try_register_project_for(&alias, Some(&tx)).await, None);
        assert!(rx.try_recv().is_err(), "nothing registered");
    }

    #[test]
    fn discover_project_root_walks_up_to_git() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("a").join("b").join("c");
        std::fs::create_dir_all(project.join(".git")).unwrap();
        let cwd = project.join("d").join("e");
        std::fs::create_dir_all(&cwd).unwrap();
        let root = discover_project_root(&cwd).unwrap();
        assert_eq!(root, project);
    }

    #[test]
    fn discover_project_root_returns_none_outside_project() {
        // Use a synthetic non-existent path so the walk-up never finds a
        // marker (the cwd's filesystem ancestors are off-limits — they
        // could legitimately contain `.git` from the test runner's repo).
        let synthetic = PathBuf::from("/__nonexistent_openlatch_test__/a/b/c/d");
        assert!(discover_project_root(&synthetic).is_none());
    }

    #[test]
    fn rules_hash_is_order_independent() {
        let cache_a = ContentHashCache::new(64);
        cache_a.insert(cache_entry("/a/CLAUDE.md", "rules", 1));
        cache_a.insert(cache_entry("/b/CLAUDE.md", "rules", 2));
        let cache_b = ContentHashCache::new(64);
        cache_b.insert(cache_entry("/b/CLAUDE.md", "rules", 2));
        cache_b.insert(cache_entry("/a/CLAUDE.md", "rules", 1));

        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let hash_a = runtime.block_on(async {
            let mut data = Some(serde_json::json!({"cwd": "/x"}));
            enrich_session_start(&mut data, &cache_a, None)
                .await
                .unwrap();
            data.unwrap()["openlatch.declared_rules_hash"]
                .as_str()
                .unwrap()
                .to_string()
        });
        let hash_b = runtime.block_on(async {
            let mut data = Some(serde_json::json!({"cwd": "/x"}));
            enrich_session_start(&mut data, &cache_b, None)
                .await
                .unwrap();
            data.unwrap()["openlatch.declared_rules_hash"]
                .as_str()
                .unwrap()
                .to_string()
        });
        assert_eq!(hash_a, hash_b);
    }
}