Add governed directory inventory sight

This commit is contained in:
Meta Vens 2026-08-11 06:56:16 +02:00
commit 31dcd351a2
3 changed files with 229 additions and 21 deletions

View file

@ -1,7 +1,7 @@
use anyhow::{Context, Result, anyhow};
use epiphany_tool_adapter::EpiphanyToolInvocationIntent;
use serde_json::{Value, json};
use std::fs::File;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
@ -19,12 +19,114 @@ pub fn execute_epiphany_source(
}
match intent.tool_name.as_str() {
"read_file" => read_file(cwd, &arguments),
"directory_inventory" => directory_inventory(cwd, &arguments),
"git_show" => git_show(cwd, &arguments),
"read_hands_receipt" => read_hands_receipt(store, &arguments),
other => Err(anyhow!("unknown epiphany_source tool {other:?}")),
}
}
fn directory_inventory(cwd: &Path, arguments: &Value) -> Result<Value> {
let requested = required_string(arguments, "path")?;
let maximum_depth = optional_u64(arguments, "maxDepth")?
.unwrap_or(3)
.clamp(0, 8) as usize;
let maximum_entries = optional_u64(arguments, "maxEntries")?
.unwrap_or(1_024)
.clamp(1, 4_096) as usize;
let maximum_samples = optional_u64(arguments, "maxSamples")?
.unwrap_or(40)
.clamp(1, 100) as usize;
let root = confined_path(cwd, requested)?;
if !root.is_dir() {
return Err(anyhow!("directory inventory path is not a directory"));
}
let mut pending = vec![(root.clone(), 0usize)];
let mut entries = Vec::new();
let mut entry_limit_hit = false;
let mut depth_limit_hit = false;
while let Some((directory, depth)) = pending.pop() {
let mut children = fs::read_dir(&directory)
.with_context(|| format!("reading directory {}", directory.display()))?
.collect::<std::io::Result<Vec<_>>>()?;
children.sort_by_key(|entry| entry.file_name());
for child in children {
if entries.len() == maximum_entries {
entry_limit_hit = true;
break;
}
let path = child.path();
let metadata = fs::symlink_metadata(&path)
.with_context(|| format!("reading metadata for {}", path.display()))?;
let kind = if metadata.file_type().is_symlink() {
"symlink"
} else if metadata.is_dir() {
"directory"
} else if metadata.is_file() {
"file"
} else {
"other"
};
entries.push((path.clone(), kind, metadata.len()));
if kind == "directory" && depth < maximum_depth {
pending.push((path, depth + 1));
} else if kind == "directory"
&& fs::read_dir(&path)
.with_context(|| format!("testing directory depth at {}", path.display()))?
.next()
.transpose()?
.is_some()
{
depth_limit_hit = true;
}
}
if entry_limit_hit {
break;
}
pending.sort_by(|left, right| right.0.cmp(&left.0));
}
entries.sort_by(|left, right| left.0.cmp(&right.0));
let file_count = entries.iter().filter(|entry| entry.1 == "file").count();
let directory_count = entries
.iter()
.filter(|entry| entry.1 == "directory")
.count();
let symlink_count = entries.iter().filter(|entry| entry.1 == "symlink").count();
let total_file_bytes = entries
.iter()
.filter(|entry| entry.1 == "file")
.map(|entry| entry.2)
.sum::<u64>();
let sample = entries
.iter()
.take(maximum_samples)
.map(|(path, kind, bytes)| {
json!({
"path": path.strip_prefix(&root).unwrap_or(path).display().to_string(),
"kind": kind,
"bytes": if *kind == "file" { Some(*bytes) } else { None },
})
})
.collect::<Vec<_>>();
let complete = !entry_limit_hit && !depth_limit_hit;
Ok(json!({
"path": root.display().to_string(),
"maxDepth": maximum_depth,
"maxEntries": maximum_entries,
"complete": complete,
"entryLimitHit": entry_limit_hit,
"depthLimitHit": depth_limit_hit,
"entryCount": entries.len(),
"fileCount": file_count,
"directoryCount": directory_count,
"symlinkCount": symlink_count,
"totalFileBytes": total_file_bytes,
"sample": sample,
}))
}
fn read_file(cwd: &Path, arguments: &Value) -> Result<Value> {
let requested = required_string(arguments, "path")?;
let start = optional_u64(arguments, "startLine")?.unwrap_or(1).max(1) as usize;
@ -230,4 +332,71 @@ mod tests {
assert_eq!(read_retained(&b"abcdef"[..], 3)?, "abc\n...<truncated>");
Ok(())
}
#[test]
fn inventories_workspace_directory_with_deterministic_totals() -> Result<()> {
let dir = tempfile::tempdir()?;
fs::create_dir(dir.path().join("artifacts"))?;
fs::create_dir(dir.path().join("artifacts/pulse-2"))?;
fs::create_dir(dir.path().join("artifacts/pulse-1"))?;
fs::write(dir.path().join("artifacts/pulse-1/a.txt"), b"awake")?;
fs::write(dir.path().join("artifacts/pulse-2/b.txt"), b"machine")?;
let value = execute_epiphany_source(
&intent(
"directory_inventory",
r#"{"path":"artifacts","maxDepth":2,"maxEntries":10,"maxSamples":10}"#,
),
dir.path(),
dir.path(),
)?;
assert_eq!(value["complete"], true);
assert_eq!(value["entryCount"], 4);
assert_eq!(value["directoryCount"], 2);
assert_eq!(value["fileCount"], 2);
assert_eq!(value["totalFileBytes"], 12);
assert_eq!(value["sample"][0]["path"], "pulse-1");
assert!(
execute_epiphany_source(
&intent("directory_inventory", r#"{"path":"../escape"}"#),
dir.path(),
dir.path(),
)
.is_err()
);
Ok(())
}
#[test]
fn directory_inventory_reports_truncation_instead_of_partial_truth() -> Result<()> {
let dir = tempfile::tempdir()?;
fs::create_dir(dir.path().join("artifacts"))?;
for name in ["a", "b", "c"] {
fs::write(dir.path().join("artifacts").join(name), name)?;
}
let value = execute_epiphany_source(
&intent(
"directory_inventory",
r#"{"path":"artifacts","maxEntries":2}"#,
),
dir.path(),
dir.path(),
)?;
assert_eq!(value["complete"], false);
assert_eq!(value["entryCount"], 2);
fs::create_dir(dir.path().join("nested"))?;
fs::create_dir(dir.path().join("nested/child"))?;
fs::write(dir.path().join("nested/child/body"), b"hidden by depth")?;
let depth_limited = execute_epiphany_source(
&intent(
"directory_inventory",
r#"{"path":"nested","maxDepth":0,"maxEntries":10}"#,
),
dir.path(),
dir.path(),
)?;
assert_eq!(depth_limited["complete"], false);
assert_eq!(depth_limited["depthLimitHit"], true);
Ok(())
}
}