llmenv 1.0.7

Universal scope-aware environment for AI coding agents
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
use crate::config::{HostScope, NetworkScope, UserScope};
use serde::Deserialize;
use std::collections::BTreeMap;

/// Resolved project (discovered from `.llmenv.yaml` walking upward from cwd).
/// All fields default permissively; malformed YAML is logged as a warning
/// and yields a minimal project with defaults (cwd folder name for id/name).
#[derive(Debug, Clone)]
pub struct ResolvedProject {
    pub root: std::path::PathBuf,
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub tags: Vec<String>,
    pub enable_bundles: Vec<String>,
    /// Keys from the marker file not matching any declared field.
    pub unknown_fields: Vec<String>,
}

/// Schema for the body of `.llmenv.yaml` (project marker file).
/// All fields optional; an empty file is valid.
#[derive(Debug, Default, Deserialize)]
struct ProjectFile {
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(default)]
    enable_bundles: Vec<String>,
    /// Capture unknown fields for warning emission.
    #[serde(flatten)]
    extra: BTreeMap<String, serde_yaml::Value>,
}

#[derive(Debug, Clone)]
pub struct Env {
    pub hostname: String,
    pub user: String,
    pub cwd: String,
    pub gateway_mac: Option<String>,
    /// User's home directory. The `.llmenv.yaml` discovery walk stops at
    /// this boundary so a marker file dropped above $HOME (e.g. `/tmp` on a
    /// shared host) cannot be picked up.
    pub home: Option<std::path::PathBuf>,
}

impl Env {
    #[must_use]
    pub fn empty() -> Self {
        Self {
            hostname: String::new(),
            user: String::new(),
            cwd: String::new(),
            gateway_mac: None,
            home: None,
        }
    }

    #[must_use]
    pub fn detect() -> Self {
        let hostname = detect_hostname().unwrap_or_else(|| {
            tracing::warn!("hostname detection failed; host-scope matching disabled");
            String::new()
        });
        let user = std::env::var("USER").unwrap_or_else(|_| {
            tracing::warn!("$USER unset; user-scope matching disabled");
            String::new()
        });
        let cwd = std::env::current_dir()
            .ok()
            .and_then(|p| p.to_str().map(String::from))
            .unwrap_or_else(|| {
                tracing::warn!("current_dir() unavailable; project-scope matching disabled");
                String::new()
            });
        let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
        Self {
            // Hostname comparison is case-insensitive — `hostname(1)` and
            // /etc/hostname may differ in case across hosts.
            hostname: hostname.to_ascii_lowercase(),
            user,
            cwd,
            gateway_mac: super::network::detect_gateway_mac(),
            home,
        }
    }
}

fn detect_hostname() -> Option<String> {
    super::capture_stdout("hostname detection", "hostname", &[]).map(|s| s.trim().to_string())
}

#[must_use]
pub fn matches_network(s: &NetworkScope, env: &Env) -> bool {
    let Some(want) = s.r#match.gateway_mac.as_deref() else {
        // ssid/cidr are not yet supported for matching; without gateway_mac we cannot match.
        return false;
    };
    env.gateway_mac
        .as_deref()
        .is_some_and(|got| got.eq_ignore_ascii_case(want))
}

#[must_use]
pub fn matches_host(s: &HostScope, env: &Env) -> bool {
    s.r#match
        .hostname
        .as_deref()
        .is_some_and(|h| h.eq_ignore_ascii_case(&env.hostname))
}

#[must_use]
pub fn matches_user(s: &UserScope, env: &Env) -> bool {
    s.r#match.user.as_deref().is_some_and(|u| u == env.user)
}

/// Discover project by walking cwd upward looking for `.llmenv.yaml`.
/// When found, parse and return a `ResolvedProject` with all fields resolved
/// (defaults applied, unknown fields collected). If YAML is malformed, log a
/// warning and return a minimal `ResolvedProject` with id/name from the
/// folder basename.
///
/// The walk is bounded at `$HOME`: a marker at `~/.llmenv.yaml` activates,
/// but the walk does not ascend above home. This prevents a hostile marker
/// dropped in e.g. `/tmp` (on a shared host) or `/Volumes/...` from being
/// picked up. When `$HOME` is unknown, only the cwd itself is checked.
#[must_use]
pub fn discover_project(env: &Env) -> Option<ResolvedProject> {
    let mut cur = std::path::PathBuf::from(&env.cwd);
    loop {
        let marker_path = cur.join(".llmenv.yaml");
        if marker_path.exists() {
            let pf = read_project_file(&marker_path);
            let basename = cur
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("llmenv")
                .to_string();
            let id = pf.id.unwrap_or_else(|| basename.clone());
            let name = pf.name.unwrap_or_else(|| basename.clone());
            let unknown_fields: Vec<String> = pf
                .extra
                .keys()
                .filter(|k| {
                    !matches!(
                        k.as_str(),
                        "id" | "name" | "description" | "tags" | "enable_bundles"
                    )
                })
                .cloned()
                .collect();
            return Some(ResolvedProject {
                root: cur,
                id,
                name,
                description: pf.description,
                tags: pf.tags,
                enable_bundles: pf.enable_bundles,
                unknown_fields,
            });
        }
        // Stop the walk once we've checked $HOME (or if home is unknown,
        // after checking only cwd). This blocks markers above home from
        // activating.
        match &env.home {
            Some(h) if cur == *h => break,
            None => break,
            _ => {}
        }
        if !cur.pop() {
            break;
        }
    }
    None
}

/// Maximum length (in bytes) for the project description. Anything longer
/// is truncated and a warning is logged. The description is surfaced into
/// LLM context chunks; a hard cap prevents a malformed or hostile marker
/// from bloating every prompt.
const MAX_DESCRIPTION_BYTES: usize = 1024;

/// Parse `.llmenv.yaml` file into a `ProjectFile`. Empty file → all defaults.
/// Malformed YAML → log warning and return defaults. The `description`
/// field is truncated to `MAX_DESCRIPTION_BYTES` if oversized.
fn read_project_file(path: &std::path::Path) -> ProjectFile {
    let Ok(body) = std::fs::read_to_string(path) else {
        return ProjectFile::default();
    };
    if body.trim().is_empty() {
        return ProjectFile::default();
    }
    match serde_yaml::from_str::<ProjectFile>(&body) {
        Ok(mut pf) => {
            if let Some(desc) = pf.description.as_mut()
                && desc.len() > MAX_DESCRIPTION_BYTES
            {
                tracing::warn!(
                    "project marker file {} has description >{} bytes; truncating",
                    path.display(),
                    MAX_DESCRIPTION_BYTES
                );
                // Truncate at a char boundary so the result remains valid UTF-8.
                let mut cut = MAX_DESCRIPTION_BYTES;
                while cut > 0 && !desc.is_char_boundary(cut) {
                    cut -= 1;
                }
                desc.truncate(cut);
            }
            pf
        }
        Err(e) => {
            tracing::warn!(
                "project marker file {} is not valid YAML: {e}; using defaults",
                path.display()
            );
            ProjectFile::default()
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::{Env, discover_project};
    use proptest::prelude::*;
    use std::path::Path;

    fn write_project_file(temp_dir: &Path, body: &str) {
        let path = temp_dir.join(".llmenv.yaml");
        std::fs::write(&path, body).expect("write .llmenv.yaml");
    }

    /// Build an `Env` with cwd inside `temp_dir`, treating `temp_dir`'s
    /// parent as $HOME so the walk reaches markers at `temp_dir` (and
    /// upward as long as we're under the boundary).
    fn env_in(cwd: &Path, home: &Path) -> Env {
        Env {
            hostname: String::new(),
            user: String::new(),
            cwd: cwd.to_string_lossy().to_string(),
            gateway_mac: None,
            home: Some(home.to_path_buf()),
        }
    }

    #[test]
    fn discovers_project_with_all_fields() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let yaml =
            "id: myapp\nname: MyApp\ndescription: Test app\ntags: [a, b]\nenable_bundles: [base]\n";
        write_project_file(temp_dir.path(), yaml);

        let env = env_in(temp_dir.path(), temp_dir.path());

        let project = discover_project(&env).expect("discover");
        assert_eq!(project.id, "myapp");
        assert_eq!(project.name, "MyApp");
        assert_eq!(project.description, Some("Test app".to_string()));
        assert_eq!(project.tags, vec!["a", "b"]);
        assert_eq!(project.enable_bundles, vec!["base"]);
        assert!(project.unknown_fields.is_empty());
    }

    #[test]
    fn empty_file_uses_defaults() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        write_project_file(temp_dir.path(), "");

        let env = env_in(temp_dir.path(), temp_dir.path());

        let project = discover_project(&env).expect("discover");
        let basename = temp_dir.path().file_name().unwrap().to_string_lossy();
        assert_eq!(project.id, basename.as_ref());
        assert_eq!(project.name, basename.as_ref());
        assert_eq!(project.description, None);
        assert!(project.tags.is_empty());
        assert!(project.enable_bundles.is_empty());
    }

    #[test]
    fn walks_upward_to_find_marker() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let root = temp_dir.path();
        let subdir = root.join("a").join("b");
        std::fs::create_dir_all(&subdir).expect("mkdir");
        write_project_file(root, "id: found\n");

        let env = env_in(&subdir, root);

        let project = discover_project(&env).expect("discover");
        assert_eq!(project.id, "found");
        assert_eq!(project.root, root);
    }

    #[test]
    fn walk_stops_at_home_boundary() {
        // Marker is above $HOME (in an ancestor of home) — must not be
        // picked up even when cwd is below home.
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let above_home = temp_dir.path();
        let home = above_home.join("home");
        let workdir = home.join("project");
        std::fs::create_dir_all(&workdir).expect("mkdir");
        // Hostile marker above home.
        write_project_file(above_home, "id: hostile\n");

        let env = env_in(&workdir, &home);
        assert!(
            discover_project(&env).is_none(),
            "marker above $HOME must not activate"
        );
    }

    #[test]
    fn walk_finds_marker_at_home() {
        // Marker exactly at $HOME — must activate (boundary is inclusive).
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let home = temp_dir.path();
        let workdir = home.join("project");
        std::fs::create_dir_all(&workdir).expect("mkdir");
        write_project_file(home, "id: home-project\n");

        let env = env_in(&workdir, home);
        let project = discover_project(&env).expect("discover");
        assert_eq!(project.id, "home-project");
        assert_eq!(project.root, home);
    }

    #[test]
    fn no_walk_above_cwd_when_home_unknown() {
        // With no HOME, only cwd itself is checked — no upward walk.
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let root = temp_dir.path();
        let subdir = root.join("sub");
        std::fs::create_dir_all(&subdir).expect("mkdir");
        write_project_file(root, "id: parent\n");

        let env = Env {
            hostname: String::new(),
            user: String::new(),
            cwd: subdir.to_string_lossy().to_string(),
            gateway_mac: None,
            home: None,
        };
        assert!(
            discover_project(&env).is_none(),
            "without HOME, walk must not ascend"
        );
    }

    #[test]
    fn returns_none_when_no_marker_found() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let env = env_in(temp_dir.path(), temp_dir.path());

        let project = discover_project(&env);
        assert!(project.is_none());
    }

    #[test]
    fn malformed_yaml_uses_defaults() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        write_project_file(temp_dir.path(), "not: [valid: yaml");

        let env = env_in(temp_dir.path(), temp_dir.path());

        let project = discover_project(&env).expect("discover");
        let basename = temp_dir.path().file_name().unwrap().to_string_lossy();
        assert_eq!(project.id, basename.as_ref());
        assert_eq!(project.name, basename.as_ref());
    }

    #[test]
    fn long_description_is_truncated() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let huge = "a".repeat(super::MAX_DESCRIPTION_BYTES + 500);
        write_project_file(temp_dir.path(), &format!("description: \"{huge}\"\n"));

        let env = env_in(temp_dir.path(), temp_dir.path());
        let project = discover_project(&env).expect("discover");
        let desc = project.description.expect("description");
        assert!(
            desc.len() <= super::MAX_DESCRIPTION_BYTES,
            "description must be capped"
        );
    }

    #[test]
    fn captures_unknown_fields() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        write_project_file(
            temp_dir.path(),
            "id: test\nunknown_field: value\nanother: 42\n",
        );

        let env = env_in(temp_dir.path(), temp_dir.path());

        let project = discover_project(&env).expect("discover");
        assert_eq!(project.unknown_fields.len(), 2);
        assert!(
            project
                .unknown_fields
                .contains(&"unknown_field".to_string())
        );
        assert!(project.unknown_fields.contains(&"another".to_string()));
    }

    proptest! {
        // discover_project never panics on arbitrary cwd paths.
        #[test]
        fn discover_arbitrary_path_never_panics(cwd in r"/[a-z/]*") {
            let env = Env {
                hostname: String::new(),
                user: String::new(),
                cwd,
                gateway_mac: None,
                home: None,
            };
            let _ = discover_project(&env);
        }

        // Malformed YAML never panics; always degrades to defaults.
        #[test]
        fn malformed_yaml_never_panics(body in r"\PC*") {
            let temp_dir = tempfile::TempDir::new().expect("tempdir");
            write_project_file(temp_dir.path(), &body);
            let env = env_in(temp_dir.path(), temp_dir.path());
            let _ = discover_project(&env);
        }

        // Property test #165: Unicode-safe basename derivation.
        // Derived project id/name must be valid UTF-8 and handle special chars.
        #[test]
        fn unicode_safe_basename_derivation(
            name_part in r"[^\x00/\.]|[^\x00/][^\x00/]*[^\x00/.]"
        ) {
            let temp_dir = tempfile::TempDir::new().expect("tempdir");
            let root = temp_dir.path();
            let sub = root.join(&name_part);
            // Reject test cases where directory creation fails.
            prop_assume!(std::fs::create_dir_all(&sub).is_ok());

            write_project_file(&sub, "");
            let env = env_in(&sub, root);
            let project = discover_project(&env).expect("discover");

            // id and name must be valid UTF-8 (already guaranteed by String).
            // Both must be non-empty (basename fallback is "llmenv").
            prop_assert!(!project.id.is_empty());
            prop_assert!(!project.name.is_empty());
            // name_part is guaranteed non-empty, no leading/trailing dots
            prop_assert_eq!(project.id, name_part.clone());
            prop_assert_eq!(project.name, name_part);
        }

        // Property test #166: discover_project walk termination with deep nesting.
        // Walk must not descend infinitely; should terminate at home boundary or root.
        #[test]
        fn walk_terminates_at_home_boundary(
            depth in 1..32usize,
        ) {
            let temp_dir = tempfile::TempDir::new().expect("tempdir");
            let root = temp_dir.path();
            let mut deep_path = root.to_path_buf();
            for i in 0..depth {
                deep_path.push(format!("d{i}"));
            }
            let _ = std::fs::create_dir_all(&deep_path);

            // Place marker at root; walk from deep_path should find it.
            write_project_file(root, "id: root-marker\n");

            let env = env_in(&deep_path, root);
            let project = discover_project(&env).expect("discover at depth");
            prop_assert_eq!(project.id, "root-marker");
            prop_assert_eq!(project.root, root);

            // Now test walk stops at home: place hostile marker above home.
            let temp_dir2 = tempfile::TempDir::new().expect("tempdir2");
            let above_home = temp_dir2.path();
            let home = above_home.join("home");
            let mut deep_work = home.to_path_buf();
            for i in 0..depth {
                deep_work.push(format!("w{i}"));
            }
            let _ = std::fs::create_dir_all(&deep_work);
            write_project_file(above_home, "id: hostile\n");

            let env2 = env_in(&deep_work, &home);
            let result = discover_project(&env2);
            // Hostile marker above home must not be found, even at depth.
            prop_assert!(result.is_none(), "hostile marker above home must not activate");
        }

        // Property test #167: ProjectFile unknown-fields filtering correctness.
        // Unknown fields must be captured; known fields must not appear in unknown_fields.
        #[test]
        fn project_file_unknown_fields_filtering(
            unknown_count in 0..10usize,
            known_id in "[a-z0-9]+",
        ) {
            let temp_dir = tempfile::TempDir::new().expect("tempdir");

            // Build YAML with known fields + unknown fields.
            let mut yaml = format!("id: {}\n", known_id);
            yaml.push_str("name: TestName\n");
            yaml.push_str("tags: [a, b, c]\n");

            // Append arbitrary unknown fields.
            for i in 0..unknown_count {
                yaml.push_str(&format!("field_{}: value_{}\n", i, i));
            }

            write_project_file(temp_dir.path(), &yaml);
            let env = env_in(temp_dir.path(), temp_dir.path());
            let project = discover_project(&env).expect("discover");

            // Verify known fields were parsed.
            prop_assert_eq!(project.id, known_id);
            prop_assert_eq!(project.name, "TestName");
            prop_assert_eq!(project.tags, vec!["a", "b", "c"]);

            // Verify unknown fields were captured.
            prop_assert_eq!(
                project.unknown_fields.len(),
                unknown_count,
                "all unknown fields must be captured"
            );

            // Verify no known field names appear in unknown_fields.
            for uf in &project.unknown_fields {
                prop_assert!(!matches!(
                    uf.as_str(),
                    "id" | "name" | "description" | "tags" | "enable_bundles"
                ));
            }
        }
    }
}