diff --git a/CHANGELOG.md b/CHANGELOG.md index e3461ad..5e0f82f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Fixed +- Project root lookup follows git's own discovery: a `.git` directory git rejects (empty, or + without `HEAD`, `objects` and `refs`) no longer makes a project root, and a `.git` file that + names no repository ends the search as git does. One stray empty `/tmp/.git` had merged every + project under `/tmp` into one workspace (#120). - `icx proxy`: folded history now renders the same bytes on every request, so the provider's prompt cache survives concurrent conversations. Before, a subagent's traffic made the proxy rebuild the main conversation's folded packets with history-dependent hologram bytes. In the @@ -42,6 +46,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - `icx proxy` adds an explicit `prompt_cache_breakpoint` at the epoch boundary of GPT-5.6 and later requests, and sets `prompt_cache_options.ttl` from `ICX_OPENAI_CACHE_TTL` (`30m` or `12h`). Other models are unchanged (T-81-001). +- Developer tools: `scripts/redactor-differential.sh` compares the redactor against a base ref on + a seeded fragment fuzz (`crates/icx-codec/tests/redact_dev_harness.rs`, ignored and + report-only), and `scripts/measure_fts_index.py` sizes SQLite FTS5 indexes over a workspace's + stored text, read only (T-91-003 evidence). ### Changed diff --git a/README.md b/README.md index 9388e77..f365ee7 100644 --- a/README.md +++ b/README.md @@ -507,7 +507,7 @@ icx --help # every subcommand and option ### Workspace Location & Trust -- With no `--dir`, icx uses a private per-project workspace: `$XDG_STATE_HOME/icx/workspaces/`, where the project root is the nearest ancestor containing `.git` (else the current directory). The resolution order is `--dir`, then `ICX_DIR`, then that default. `ICX_STATE_HOME` and `ICX_CONFIG_HOME` override the state and config roots; only absolute paths are honoured, and icx refuses to run rather than fall back to `/tmp` when it cannot determine them. +- With no `--dir`, icx uses a private per-project workspace: `$XDG_STATE_HOME/icx/workspaces/`, where the project root is the top of the enclosing git work tree, found by git's own rules (else the current directory). The resolution order is `--dir`, then `ICX_DIR`, then that default. `ICX_STATE_HOME` and `ICX_CONFIG_HOME` override the state and config roots; only absolute paths are honoured, and icx refuses to run rather than fall back to `/tmp` when it cannot determine them. - A workspace is one SQLite file (`icx.sqlite3`) in a `0700` directory with `0600` files, sealed with a keyed BLAKE3 MAC derived from the per-install key `$XDG_CONFIG_HOME/icx/install.key`. icx refuses a workspace that is not owned by the current user, is group- or world-accessible, or fails its owner seal or store MAC. - **Upgrading from v1.0.x:** a repository-local `.icx/` is never loaded implicitly, because a cloned repository could ship a poisoned one. icx prints a one-time warning that it is ignored. To keep the data, adopt it explicitly; this sets `0700`, rewrites its `.gitignore` to `*`, writes an owner seal and reseals the store, and warns if the directory is inside a git work tree. v1.0.x JSON workspace files are migrated to SQLite on first load without being deleted. diff --git a/crates/icx-adapters/src/workspace.rs b/crates/icx-adapters/src/workspace.rs index 070e038..a925ee3 100644 --- a/crates/icx-adapters/src/workspace.rs +++ b/crates/icx-adapters/src/workspace.rs @@ -112,15 +112,135 @@ fn io_err(e: impl std::fmt::Display) -> TrustError { TrustError::Io(e.to_string()) } -/// Nearest ancestor of `cwd` containing `.git`, else `cwd`. A linked git worktree (`.git` is a -/// file naming `
/.git/worktrees/`) resolves to its main repository, so an agent -/// working in a worktree shares the project's workspace (v1.3.2, #37). +/// Nearest ancestor of `cwd` that is the top of a git work tree, else `cwd`. A linked git +/// worktree (`.git` is a file naming `
/.git/worktrees/`) resolves to its main +/// repository, so an agent working in a worktree shares the project's workspace (v1.3.2, #37). +/// +/// The search follows git's own discovery (#120), so one stray `.git` in a shared parent such +/// as `/tmp` cannot merge every project below it: a `.git` directory git would reject (empty, or +/// missing `HEAD`, `objects` or `refs`) is skipped and the search goes on upward, and a `.git` +/// file naming no repository ends it, as git stops there with "not a git repository", leaving +/// `cwd` its own project. pub fn project_root(cwd: &Path) -> PathBuf { let start = std::fs::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()); - let Some(found) = start.ancestors().find(|p| p.join(".git").exists()) else { - return start.clone(); + for dir in start.ancestors() { + match dot_git(dir) { + DotGit::Repository => { + return worktree_main_root(dir).unwrap_or_else(|| dir.to_path_buf()); + } + DotGit::InvalidFile => break, + DotGit::None => {} + } + } + start +} + +/// Whether `dir/.git` is a repository git would accept: a git directory, or a file whose +/// `gitdir:` line names one (a linked worktree or a submodule). +pub fn has_git_repository(dir: &Path) -> bool { + matches!(dot_git(dir), DotGit::Repository) +} + +/// What `dir/.git` is to git's repository discovery. +enum DotGit { + /// A repository: discovery stops here. + Repository, + /// Absent, or a directory git rejects: discovery goes on to the parent. + None, + /// A file that names no repository: git reports an error and stops. + InvalidFile, +} + +/// The largest git control file (`.git` file, `HEAD`, `commondir`, `gitdir`) icx reads. +const MAX_CONTROL_FILE: u64 = 4096; + +/// A small git control file, or `None`. It must be a regular file, not a symlink (ICX-AUD-018), +/// of at most [`MAX_CONTROL_FILE`] bytes. The open is non-blocking and no-follow and the handle is +/// re-checked, so a FIFO or device planted in any ancestor of the cwd cannot block a hook and a +/// large file is never read whole (`project_root` runs on every hook). +fn read_control_file(path: &Path) -> Option { + if !std::fs::symlink_metadata(path).ok()?.file_type().is_file() { + return None; + } + let mut opts = std::fs::OpenOptions::new(); + opts.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + let flags = rustix::fs::OFlags::NONBLOCK | rustix::fs::OFlags::NOFOLLOW; + opts.custom_flags(flags.bits().cast_signed()); + } + let file = opts.open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.file_type().is_file() || meta.len() > MAX_CONTROL_FILE { + return None; + } + let mut text = String::new(); + // One byte over the limit tells a file that grew after the check from one that fits. + file.take(MAX_CONTROL_FILE + 1) + .read_to_string(&mut text) + .ok()?; + (text.len() as u64 <= MAX_CONTROL_FILE).then_some(text) +} + +/// The path a `.git` file names, read as git's `read_gitfile_gently` does: `gitdir: ` (with the +/// space), then the path up to trailing line ends, which must be the whole file (a second line +/// would become part of the path and name nothing). +fn gitfile_target(text: &str) -> Option<&str> { + let path = text + .strip_prefix("gitdir: ")? + .trim_end_matches(['\r', '\n']); + (!path.is_empty() && !path.contains(['\r', '\n'])).then_some(path) +} + +fn dot_git(dir: &Path) -> DotGit { + let dot_git = dir.join(".git"); + // A `.git` directory may be a symlink (git follows it); a `.git` file may not. + let Ok(meta) = std::fs::metadata(&dot_git) else { + return DotGit::None; + }; + if meta.is_dir() { + return if is_git_directory(&dot_git) { + DotGit::Repository + } else { + DotGit::None + }; + } + if !meta.is_file() { + return DotGit::None; + } + let names_repository = read_control_file(&dot_git) + .is_some_and(|text| gitfile_target(&text).is_some_and(|g| is_git_directory(&dir.join(g)))); + if names_repository { + DotGit::Repository + } else { + DotGit::InvalidFile + } +} + +/// git's `is_git_directory`: a valid `HEAD`, plus `objects` and `refs` directories in the common +/// directory (`commondir` names it for a linked worktree's git directory). +fn is_git_directory(gitdir: &Path) -> bool { + // git's `validate_headref` looks only at how `HEAD` starts: `ref:` then a name under `refs/`, + // or a SHA-1 or SHA-256 object name. Whatever follows is not checked. + let head_ok = read_control_file(&gitdir.join("HEAD")).is_some_and(|h| { + h.strip_prefix("ref:").is_some_and(|r| { + r.trim_start_matches(|c: char| c.is_ascii_whitespace()) + .starts_with("refs/") + }) || [40, 64].iter().any(|&n| { + h.len() >= n + && h.as_bytes()[..n].iter().all(u8::is_ascii_hexdigit) + && h.as_bytes().get(n).is_none_or(u8::is_ascii_whitespace) + }) + }); + if !head_ok { + return false; + } + let common = match read_control_file(&gitdir.join("commondir")) { + Some(rel) if !rel.trim().is_empty() => gitdir.join(rel.trim()), + _ => gitdir.to_path_buf(), }; - worktree_main_root(found).unwrap_or_else(|| found.to_path_buf()) + common.join("objects").is_dir() && common.join("refs").is_dir() } /// The main repository of the linked worktree at `root`, or `None` when `root` is not one. @@ -132,19 +252,9 @@ pub fn project_root(cwd: &Path) -> PathBuf { /// Submodules (`gitdir` under `.git/modules/`) have no `commondir` and stay their own project. fn worktree_main_root(root: &Path) -> Option { let dot_git = root.join(".git"); - if !std::fs::symlink_metadata(&dot_git).ok()?.is_file() { - return None; - } - // `symlink_metadata`: a symlinked control file is refused, as for `.git` (ICX-AUD-018). - let read_small = |p: &Path| -> Option { - let meta = std::fs::symlink_metadata(p).ok()?; - if !meta.is_file() || meta.len() > 4096 { - return None; - } - std::fs::read_to_string(p).ok() - }; + let read_small = read_control_file; let gitdir_line = read_small(&dot_git)?; - let gitdir = gitdir_line.trim().strip_prefix("gitdir:")?.trim(); + let gitdir = gitfile_target(&gitdir_line)?; let gitdir = std::fs::canonicalize(root.join(gitdir)).ok()?; let common_rel = read_small(&gitdir.join("commondir"))?; let common = std::fs::canonicalize(gitdir.join(common_rel.trim())).ok()?; diff --git a/crates/icx-adapters/tests/codex_rollout_zstd_props.rs b/crates/icx-adapters/tests/codex_rollout_zstd_props.rs index f0d9853..d8eb2b9 100644 --- a/crates/icx-adapters/tests/codex_rollout_zstd_props.rs +++ b/crates/icx-adapters/tests/codex_rollout_zstd_props.rs @@ -91,6 +91,7 @@ proptest! { if let Ok((_, n)) = ingest_rollout(&p, None, &mut mmu) { prop_assert!(n <= RECORDS_IN_FIXTURE); } - let _ = std::fs::remove_file(&p); + // Each case removes its directory, not only its file, so no run leaves one behind. + let _ = std::fs::remove_dir_all(&d); } } diff --git a/crates/icx-adapters/tests/workspace_trust.rs b/crates/icx-adapters/tests/workspace_trust.rs index dcf98f1..ee7fc2c 100644 --- a/crates/icx-adapters/tests/workspace_trust.rs +++ b/crates/icx-adapters/tests/workspace_trust.rs @@ -17,6 +17,15 @@ fn scratch(tag: &str) -> PathBuf { d } +/// The smallest `.git` git accepts (`HEAD`, `objects`, `refs`): an empty one is not a +/// repository to git, nor to `project_root` (#120). +fn git_dir(repo: &Path) { + for d in ["objects", "refs"] { + std::fs::create_dir_all(repo.join(".git").join(d)).unwrap(); + } + std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap(); +} + fn roots(base: &Path) -> WorkspaceRoots { WorkspaceRoots { state_dir: base.join("state"), @@ -29,7 +38,7 @@ fn roots(base: &Path) -> WorkspaceRoots { fn default_workspace_lives_outside_the_repository_and_is_stable_across_subdirs() { let base = scratch("default"); let repo = base.join("repo"); - std::fs::create_dir_all(repo.join(".git")).unwrap(); + git_dir(&repo); std::fs::create_dir_all(repo.join("src/deep")).unwrap(); let r = roots(&base); let a = workspace::resolve(None, None, &repo, &r).unwrap(); @@ -45,7 +54,7 @@ fn default_workspace_lives_outside_the_repository_and_is_stable_across_subdirs() fn repo_local_icx_is_reported_but_never_selected_by_default() { let base = scratch("legacy"); let repo = base.join("repo"); - std::fs::create_dir_all(repo.join(".git")).unwrap(); + git_dir(&repo); std::fs::create_dir_all(repo.join(".icx")).unwrap(); let ws = workspace::resolve(None, None, &repo, &roots(&base)).unwrap(); assert_eq!( diff --git a/crates/icx-adapters/tests/worktree_root.rs b/crates/icx-adapters/tests/worktree_root.rs index 3213961..7ad095a 100644 --- a/crates/icx-adapters/tests/worktree_root.rs +++ b/crates/icx-adapters/tests/worktree_root.rs @@ -1,6 +1,6 @@ //! v1.3.2 (#37): a linked git worktree belongs to its main repository's project; a planted //! `.git` file or a submodule does not redirect anything. -use icx_adapters::workspace::project_root; +use icx_adapters::workspace::{has_git_repository, project_root}; use std::path::{Path, PathBuf}; use std::process::Command; @@ -81,3 +81,151 @@ fn worktrees_resolve_to_the_main_repository_and_forgeries_do_not() { assert_eq!(project_root(&wt), wt, "symlinked back-link"); let _ = std::fs::remove_dir_all(&base); } + +/// git's own answer for `cwd`: the work tree top, or `None` outside any repository. Discovery +/// stops at `base`'s parent, so a repository above the test's temp directory cannot answer. +fn git_toplevel(base: &Path, cwd: &Path) -> Option { + let out = Command::new("git") + .current_dir(cwd) + .env("GIT_CEILING_DIRECTORIES", base.parent().unwrap_or(base)) + .args(["rev-parse", "--show-toplevel"]) + .output() + .unwrap(); + out.status + .success() + .then(|| std::fs::canonicalize(String::from_utf8_lossy(&out.stdout).trim()).unwrap()) +} + +#[test] +fn a_git_directory_git_rejects_does_not_make_a_project_root() { + // #120: a stray empty `/tmp/.git` captured every project under /tmp into one workspace. + let base = base_dir("stray-dot-git"); + + // An empty `.git` above a plain directory: neither git nor icx sees a repository. + let plain = base.join("outer/plain"); + std::fs::create_dir_all(&plain).unwrap(); + std::fs::create_dir_all(base.join("outer/.git")).unwrap(); + assert_eq!(git_toplevel(&base, &plain), None); + assert_eq!(project_root(&plain), plain); + assert!(!has_git_repository(&base.join("outer"))); + + // An empty, then a partial (`HEAD` only), `.git` between a real repository and the cwd: + // the search skips it and finds the repository, as git does. + let repo = base.join("repo"); + let mid = repo.join("mid"); + let deep = mid.join("x"); + std::fs::create_dir_all(&deep).unwrap(); + git(&repo, &["init", "-q"]); + assert!(has_git_repository(&repo), "a repository git created"); + std::fs::create_dir_all(mid.join(".git")).unwrap(); + assert_eq!(git_toplevel(&base, &deep), Some(repo.clone())); + assert_eq!(project_root(&deep), repo); + std::fs::write(mid.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap(); + assert_eq!(git_toplevel(&base, &deep), Some(repo.clone())); + assert_eq!(project_root(&deep), repo, "HEAD without objects or refs"); + + // A `.git` file naming a directory that is not a repository ends the search: git reports + // "not a git repository" there rather than looking further up, so the cwd is its own project. + std::fs::remove_dir_all(mid.join(".git")).unwrap(); + std::fs::create_dir_all(base.join("not-a-repo")).unwrap(); + std::fs::write( + mid.join(".git"), + format!("gitdir: {}\n", base.join("not-a-repo").display()), + ) + .unwrap(); + assert_eq!(git_toplevel(&base, &deep), None); + assert_eq!(project_root(&deep), deep, ".git file naming no repository"); + + // The smallest directory git accepts (`HEAD`, `objects`, `refs`) is a repository for both. + std::fs::remove_file(mid.join(".git")).unwrap(); + for d in ["objects", "refs"] { + std::fs::create_dir_all(mid.join(".git").join(d)).unwrap(); + } + std::fs::write(mid.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap(); + assert_eq!(git_toplevel(&base, &deep), Some(mid.clone())); + assert_eq!(project_root(&deep), mid); + + // git checks only how `HEAD` starts, so a second line, `ref:` without a space and a bare + // object name are all valid; a `ref:` outside `refs/` is not. + for head in [ + "ref: refs/heads/main\nextra\n", + "ref:refs/heads/main\n", + "0123456789abcdef0123456789abcdef01234567\n", + ] { + std::fs::write(mid.join(".git/HEAD"), head).unwrap(); + assert_eq!(git_toplevel(&base, &deep), Some(mid.clone()), "{head:?}"); + assert_eq!(project_root(&deep), mid, "{head:?}"); + } + std::fs::write(mid.join(".git/HEAD"), "ref: heads/main\n").unwrap(); + assert_eq!(git_toplevel(&base, &deep), Some(repo.clone())); + assert_eq!(project_root(&deep), repo, "ref outside refs/"); + + // A `.git` file must be exactly one `gitdir:` line, even when it names a real repository. + std::fs::remove_dir_all(mid.join(".git")).unwrap(); + std::fs::write( + mid.join(".git"), + format!("gitdir: {}\nextra\n", repo.join(".git").display()), + ) + .unwrap(); + assert_eq!(git_toplevel(&base, &deep), None); + assert_eq!(project_root(&deep), deep, "two-line .git file"); + // ... and git needs the space after `gitdir:`. + std::fs::write( + mid.join(".git"), + format!("gitdir:{}\n", repo.join(".git").display()), + ) + .unwrap(); + assert_eq!(git_toplevel(&base, &deep), None); + assert_eq!(project_root(&deep), deep, "no space after gitdir:"); + let _ = std::fs::remove_dir_all(&base); +} + +#[cfg(unix)] +#[test] +fn planted_control_files_cannot_block_or_bloat_the_lookup() { + // `project_root` runs on every hook: a FIFO named `HEAD` in an ancestor must not block it, + // and an oversized `HEAD` is not read (security review of #119). + let base = base_dir("planted-control-files"); + let cwd = base.join("fifo/work"); + std::fs::create_dir_all(&cwd).unwrap(); + let gitdir = base.join("fifo/.git"); + for d in ["objects", "refs"] { + std::fs::create_dir_all(gitdir.join(d)).unwrap(); + } + let made = Command::new("mkfifo") + .arg(gitdir.join("HEAD")) + .status() + .unwrap(); + assert!(made.success()); + let (tx, rx) = std::sync::mpsc::channel(); + let probe = cwd.clone(); + std::thread::spawn(move || tx.send(project_root(&probe)).unwrap()); + let found = rx + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("project_root blocked on a FIFO HEAD"); + assert_eq!(found, cwd, "a FIFO is not a valid HEAD"); + + // A `.git` that is neither a file nor a directory (here a FIFO) is no repository either. + let odd = base.join("odd"); + std::fs::create_dir_all(odd.join("work")).unwrap(); + assert!( + Command::new("mkfifo") + .arg(odd.join(".git")) + .status() + .unwrap() + .success() + ); + assert!(!has_git_repository(&odd)); + assert_eq!(project_root(&odd.join("work")), odd.join("work")); + + let big = base.join("big"); + std::fs::create_dir_all(big.join("work")).unwrap(); + for d in ["objects", "refs"] { + std::fs::create_dir_all(big.join(".git").join(d)).unwrap(); + } + let mut head = "ref: refs/heads/main\n".to_owned(); + head.push_str(&" ".repeat(8192)); + std::fs::write(big.join(".git/HEAD"), head).unwrap(); + assert_eq!(project_root(&big.join("work")), big.join("work")); + let _ = std::fs::remove_dir_all(&base); +} diff --git a/crates/icx-cli/src/main.rs b/crates/icx-cli/src/main.rs index e8c657d..1dbd095 100644 --- a/crates/icx-cli/src/main.rs +++ b/crates/icx-cli/src/main.rs @@ -281,6 +281,12 @@ fn roots() -> &'static WorkspaceRoots { #[cfg(test)] { let base = env::temp_dir().join(format!("icx_cli_test_roots_{}", std::process::id())); + // The sandbox lives as long as the test process, so it cannot be removed when a test + // ends. Remove the ones left by earlier test processes that have exited instead. + #[cfg(target_os = "linux")] + remove_stale_test_roots(); + // A reused PID must not inherit an earlier run's state. + let _ = fs::remove_dir_all(&base); WorkspaceRoots { state_dir: base.join("state"), config_dir: base.join("config"), @@ -294,6 +300,42 @@ fn roots() -> &'static WorkspaceRoots { }) } +/// Removes this user's `icx_cli_test_roots_` sandbox directories whose process no longer +/// exists. Linux only (it checks `/proc/`); a live process's sandbox, including one whose PID +/// was reused, is kept, and so is anything that is not a directory or belongs to another user. +#[cfg(all(test, target_os = "linux"))] +fn remove_stale_test_roots() { + use std::os::unix::fs::MetadataExt; + for entry in fs::read_dir(env::temp_dir()) + .into_iter() + .flatten() + .flatten() + { + let name = entry.file_name(); + let Some(pid) = name + .to_str() + .and_then(|n| n.strip_prefix("icx_cli_test_roots_")) + .and_then(|p| p.parse::().ok()) + else { + continue; + }; + let mine = entry + .metadata() + .is_ok_and(|m| m.file_type().is_dir() && m.uid() == rustix::process::getuid().as_raw()); + if mine && pid != std::process::id() && !Path::new(&format!("/proc/{pid}")).exists() { + let _ = fs::remove_dir_all(entry.path()); + } + } +} + +/// Whether `dir` lies below the top of a git work tree (main or linked): its parent resolves, as +/// git and `project_root` would, to a repository. A work tree's own top, main or linked, is not +/// "inside" one, and an invalid `.git` file above `dir` ends the search as it does for git. +fn inside_work_tree(dir: &Path) -> bool { + dir.parent() + .is_some_and(|p| workspace::has_git_repository(&workspace::project_root(p))) +} + /// An MMU that MAC-stamps every save and rejects stores not written by this install. fn workspace_mmu() -> InfinityContextMmu { let mut mmu = InfinityContextMmu::default(); @@ -614,12 +656,7 @@ fn run_trust(args: &[String]) -> Result<(), String> { .map_err(|e| format!("icx trust error: cannot seal store: {e}"))?; } let canonical = fs::canonicalize(&dir).unwrap_or_else(|_| dir.clone()); - if workspace::project_root(&canonical) != canonical - && canonical - .ancestors() - .skip(1) - .any(|p| p.join(".git").exists()) - { + if inside_work_tree(&canonical) { eprintln!( "icx trust: note: {} is inside a git work tree; anything committed there can be replaced by a pull. \ The store is MAC-sealed, but the default out-of-repo location (omit --dir) is safer.", @@ -4245,12 +4282,74 @@ mod tests { } } + #[test] + fn inside_work_tree_matches_git_for_repositories_and_linked_worktrees() { + let base = env::temp_dir().join(format!("icx_cli_inside_wt_{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let main = base.join("main"); + fs::create_dir_all(main.join("src")).unwrap(); + let git = |cwd: &Path, args: &[&str]| { + let out = std::process::Command::new("git") + .current_dir(cwd) + .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"]) + .args(["-c", "commit.gpgsign=false"]) + .args(args) + .output() + .unwrap(); + assert!(out.status.success(), "git {args:?}: {out:?}"); + }; + git(&main, &["init", "-q"]); + fs::write(main.join("README"), "x\n").unwrap(); + git(&main, &["add", "README"]); + git(&main, &["commit", "-q", "-m", "init"]); + git(&main, &["worktree", "add", "-q", "../wt", "-b", "agent"]); + let base = fs::canonicalize(&base).unwrap(); + let (main, wt) = (base.join("main"), base.join("wt")); + fs::create_dir_all(wt.join("deep")).unwrap(); + assert!(!inside_work_tree(&main), "a repository's own top"); + assert!(!inside_work_tree(&wt), "a linked worktree's own top"); + assert!(inside_work_tree(&main.join("src"))); + assert!(inside_work_tree(&wt.join("deep"))); + assert!(!inside_work_tree(&base)); + let _ = fs::remove_dir_all(&base); + } + + #[cfg(target_os = "linux")] + #[test] + fn stale_test_roots_of_exited_processes_are_removed_and_nothing_else() { + // A PID above `pid_max` can never be running. + let pid_max: u64 = fs::read_to_string("/proc/sys/kernel/pid_max") + .unwrap() + .trim() + .parse() + .unwrap(); + // Distinct per test process, so concurrent runs do not share these names. + let me = u64::from(std::process::id()); + let dead = env::temp_dir().join(format!("icx_cli_test_roots_{}", pid_max + 1 + 2 * me)); + let dead_file = + env::temp_dir().join(format!("icx_cli_test_roots_{}", pid_max + 2 + 2 * me)); + // PID 1 is running in every PID namespace. + let live = env::temp_dir().join("icx_cli_test_roots_1"); + fs::create_dir_all(dead.join("state")).unwrap(); + fs::write(&dead_file, "not a sandbox").unwrap(); + let live_existed = live.exists(); + fs::create_dir_all(&live).unwrap(); + remove_stale_test_roots(); + assert!(!dead.exists(), "an exited process's sandbox is removed"); + assert!(dead_file.is_file(), "a file with the name is not a sandbox"); + assert!(live.is_dir(), "a running process's sandbox is kept"); + let _ = fs::remove_file(&dead_file); + if !live_existed { + let _ = fs::remove_dir(&live); + } + } + #[cfg(unix)] #[test] fn the_daemon_stubs_only_when_the_caller_asks() { // Stub mode is the hook caller's setting: it travels in the request (version 2), and the // daemon's own environment plays no part (review of #87). - let (_ws, sock, server) = start_daemon("stub_flag"); + let (ws, sock, server) = start_daemon("stub_flag"); let big = (0..400) .map(|i| format!("row {i}: value={}", i * 3)) .collect::>() @@ -4269,7 +4368,9 @@ mod tests { .expect("daemon reply"); assert!(stubbed.contains("ICX:STUB"), "{stubbed}"); assert!(!caller_stub_mode(AgentKind::ClaudeCode)); - drop(server); + // The daemon exits after its idle timeout; join it so the workspace can be removed. + let _ = server.join(); + let _ = fs::remove_dir_all(&ws); } #[cfg(unix)] @@ -4277,7 +4378,7 @@ mod tests { fn a_version_1_request_cannot_ask_for_stubs() { use std::io::{Read, Write}; use std::os::unix::net::UnixStream; - let (_ws, sock, server) = start_daemon("stub_v1"); + let (ws, sock, server) = start_daemon("stub_v1"); let big = (0..400) .map(|i| format!("row {i}: v={}", i * 5)) .collect::>() @@ -4292,7 +4393,9 @@ mod tests { let mut reply = String::new(); stream.read_to_string(&mut reply).unwrap(); assert!(!reply.contains("ICX:STUB"), "{reply}"); - drop(server); + // The daemon exits after its idle timeout; join it so the workspace can be removed. + let _ = server.join(); + let _ = fs::remove_dir_all(&ws); } #[test] diff --git a/crates/icx-cli/tests/install_cli.rs b/crates/icx-cli/tests/install_cli.rs index a92a85a..5da186d 100644 --- a/crates/icx-cli/tests/install_cli.rs +++ b/crates/icx-cli/tests/install_cli.rs @@ -2,17 +2,50 @@ //! a real install backs up and is idempotent, existing icx hooks are not duplicated, unknown keys //! and comments survive, and an unparsable file is never rewritten. +use std::ffi::OsStr; use std::fs; +use std::ops::Deref; use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; const ICX: &str = "/opt/icx/bin/icx"; -fn home(tag: &str) -> PathBuf { +/// A throwaway HOME, removed when the test ends. A failing test keeps it for inspection (the +/// path is in the panic output), so only passing runs clean up after themselves. +struct TempHome(PathBuf); + +impl Drop for TempHome { + fn drop(&mut self) { + if !std::thread::panicking() { + let _ = fs::remove_dir_all(&self.0); + } + } +} + +impl Deref for TempHome { + type Target = Path; + fn deref(&self) -> &Path { + &self.0 + } +} + +impl AsRef for TempHome { + fn as_ref(&self) -> &Path { + &self.0 + } +} + +impl AsRef for TempHome { + fn as_ref(&self) -> &OsStr { + self.0.as_os_str() + } +} + +fn home(tag: &str) -> TempHome { let h = std::env::temp_dir().join(format!("icx-install-{tag}-{}", std::process::id())); let _ = fs::remove_dir_all(&h); fs::create_dir_all(&h).unwrap(); - h + TempHome(h) } fn run(home: &Path, args: &[&str]) -> Output { @@ -290,7 +323,6 @@ fn every_agent_plans_without_error_and_agy_needs_no_wrapper() { .contains("Mcp(icx:icx)") ); assert!(out(&o).contains("claude mcp add --scope user icx")); - let _ = fs::remove_dir_all(&h); } #[test] diff --git a/crates/icx-cli/tests/proxy_projects.rs b/crates/icx-cli/tests/proxy_projects.rs index c58904d..93a2eef 100644 --- a/crates/icx-cli/tests/proxy_projects.rs +++ b/crates/icx-cli/tests/proxy_projects.rs @@ -124,6 +124,14 @@ fn proxy_routes_each_project_into_its_own_workspace() { let b = base.join("project-b"); for p in [&a, &b] { std::fs::create_dir_all(p).unwrap(); + // Each project is its own repository, so a `.git` somewhere above the temp directory + // cannot change which workspace it resolves to (#120). + let init = std::process::Command::new("git") + .args(["init", "-q"]) + .current_dir(p) + .output() + .unwrap(); + assert!(init.status.success(), "git init: {init:?}"); run({ let mut c = icx(&base, p); c.arg("init"); diff --git a/crates/icx-codec/tests/redact_dev_harness.rs b/crates/icx-codec/tests/redact_dev_harness.rs new file mode 100644 index 0000000..e018126 --- /dev/null +++ b/crates/icx-codec/tests/redact_dev_harness.rs @@ -0,0 +1,211 @@ +// SPDX-FileCopyrightText: 2026 DoubleGate +// SPDX-License-Identifier: GPL-3.0-or-later AND AGPL-3.0-or-later + +//! Developer harness for redactor changes: a deterministic fragment fuzz and a case-file runner. +//! Both are `#[ignore]`d and only report; nothing here is a pass/fail gate. They are the tools +//! the v1.5.x red-team and review rounds used, kept so the next redactor change can be compared +//! against its base with `scripts/redactor-differential.sh`. +//! +//! `qqzz` stands for a secret value, `aaaa-aaaa` for a UUID-shaped one and `4821` for a PIN or OTP +//! number. A placeholder that survives is a leak only where a sensitive key precedes it, so a fuzz +//! "leak" line is a candidate: compare two trees, and read the lines that leak on one only. +//! +//! ```text +//! # fragment fuzz: N lines (default 20000) from a fixed seed; LEAKS=1 prints each leaking line +//! FUZZ_N=200000 LEAKS=1 cargo test --release -p icx-codec --test redact_dev_harness fuzz -- --ignored --nocapture +//! # case file: a JSON array of strings; ALL=1 also prints the cases that are fine +//! CASES=cases.json cargo test -p icx-codec --test redact_dev_harness cases -- --ignored --nocapture +//! ``` + +use icx_codec::SecretRedactor; + +/// Fragments the fuzz joins into lines: sensitive keys, separators, quotes, shell and config +/// forms, markers, look-alike characters and placeholder values. +const FRAGMENTS: &[&str] = &[ + "password", + "api_key", + "token", + "session_id", + "secret", + "PASSWORD", + "--token", + "=", + " = ", + ":", + ": ", + "\"", + "'", + "`", + " ", + ",", + ";", + "(", + ")", + "[", + "]", + "{", + "}", + "#", + " #", + "//", + "null", + "None", + "1234", + "$DB_PASSWORD", + "os.environ[\"API_KEY\"]", + "config.x", + "get_token(u)", + "qqzz", + "\\", + "\\\"", + "\n", + " ", + "- ", + "|", + ">", + "&", + "export ", + "let ", + "https://u:", + "@h", + "Bearer ", + "[REDACTED:ENV_SECRET]", + "r\"", + "b'", + "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", + ".", + "=>", + "\r\n", + "[REDACTED:SECRET]", + " String { + s.replace("qqzz", "§") + .replace('=', "≡") + .replace(':', "¦") + .replace('"', "ʺ") + .replace('\'', "ʹ") + .replace('\n', "⏎") + .replace('\r', "␍") + .replace(' ', "␠") +} + +/// A surviving placeholder: `qqzz` (a secret value), `aaaa-aaaa` (a UUID-shaped one) or `4821` +/// (the PIN/OTP number the `pin: `/`otp=` fragments precede). +fn leaks(redacted: &str) -> bool { + ["qqzz", "aaaa-aaaa", "4821"] + .iter() + .any(|p| redacted.contains(p)) +} + +/// Set and not empty or `0`. +fn env_flag(name: &str) -> bool { + std::env::var_os(name).is_some_and(|v| !v.is_empty() && v != "0") +} + +#[test] +#[ignore = "developer harness: reports, never fails"] +fn fuzz() { + let n: usize = std::env::var("FUZZ_N") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(20_000); + let print_leaks = env_flag("LEAKS"); + // xorshift64 from a fixed seed: the same N gives the same lines on every tree and machine. + let mut state: u64 = 0x9e37_79b9_7f4a_7c15; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let (mut leaking, mut non_idempotent) = (0usize, 0usize); + for _ in 0..n { + let parts = 2 + next() % 10; + let mut line = String::new(); + for _ in 0..parts { + let pick = usize::try_from(next() % FRAGMENTS.len() as u64).unwrap_or(0); + line.push_str(FRAGMENTS[pick]); + } + let once = SecretRedactor::redact(&line); + let twice = SecretRedactor::redact(&once); + if leaks(&once) { + leaking += 1; + if print_leaks { + println!("L {}", show(&line)); + } + } + if once != twice { + non_idempotent += 1; + if non_idempotent <= 12 { + println!( + "NONIDEM\n in : {}\n 1st: {}\n 2nd: {}", + show(&line), + show(&once), + show(&twice) + ); + } + } + } + println!( + "fuzz: {n} lines, {leaking} with a surviving placeholder, {non_idempotent} non-idempotent" + ); +} + +#[test] +#[ignore = "developer harness: reports, never fails"] +fn cases() { + let Some(path) = std::env::var_os("CASES") else { + println!("cases: set CASES to a JSON array of strings"); + return; + }; + let text = std::fs::read_to_string(&path).expect("CASES file is readable"); + let cases: Vec = serde_json::from_str(&text).expect("CASES is a JSON array of strings"); + let all = env_flag("ALL"); + for (i, case) in cases.iter().enumerate() { + let once = SecretRedactor::redact(case); + let twice = SecretRedactor::redact(&once); + let tag = match (leaks(&once), once == twice) { + (true, true) => "LEAK", + (true, false) => "LEAK+NONIDEM", + (false, false) => "NONIDEM", + (false, true) => "ok", + }; + if all || tag != "ok" { + println!( + "#{i} {tag}\n in : {}\n out: {}", + show(case), + show(&once) + ); + if once != twice { + println!(" 2nd: {}", show(&twice)); + } + } else { + println!("#{i} ok"); + } + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 321b1e0..31f0f3c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -121,8 +121,8 @@ replacement field; the original native output remains visible. See 1. **Resolve the workspace:** `--dir` > `ICX_DIR` > the per-project default `/workspaces/`, where the project - root is the nearest ancestor containing `.git` and `state_dir` is `ICX_STATE_HOME`, else - `$XDG_STATE_HOME/icx`, else `~/.local/state/icx`. + root is the top of the nearest git work tree, found by git's own discovery rules (#120), and + `state_dir` is `ICX_STATE_HOME`, else `$XDG_STATE_HOME/icx`, else `~/.local/state/icx`. 2. **Verify trust:** the directory must be owned by the effective uid, have no group/other permission bits, and carry a valid `OWNER` seal; a sealed store must carry a valid MAC. A repository-local `.icx/` is never used implicitly (`icx trust --dir ` adopts one). See diff --git a/docs/deployment-and-agent-integration-guide.md b/docs/deployment-and-agent-integration-guide.md index a14dc42..5e61a4b 100644 --- a/docs/deployment-and-agent-integration-guide.md +++ b/docs/deployment-and-agent-integration-guide.md @@ -102,7 +102,7 @@ By default each project gets its own workspace **outside** the repository: $XDG_STATE_HOME/icx/workspaces// ``` -The project root is the nearest ancestor of the current directory that contains `.git` (otherwise the current directory). Resolution order is `--dir ` > `ICX_DIR` > the per-project default. The state root is `ICX_STATE_HOME`, else `$XDG_STATE_HOME/icx`, else `~/.local/state/icx`. Only absolute environment paths are honoured; if no private location can be determined (no `HOME` or XDG variables), `icx` refuses to create a workspace rather than falling back to a shared directory such as `/tmp`. +The project root is the top of the git work tree containing the current directory, found as git finds it (otherwise the current directory): a `.git` that git would reject, such as an empty directory, does not make a project root (#120). Resolution order is `--dir ` > `ICX_DIR` > the per-project default. The state root is `ICX_STATE_HOME`, else `$XDG_STATE_HOME/icx`, else `~/.local/state/icx`. Only absolute environment paths are honoured; if no private location can be determined (no `HOME` or XDG variables), `icx` refuses to create a workspace rather than falling back to a shared directory such as `/tmp`. | File Path (inside the workspace) | Owning Subsystem | Contents & Role | | :--- | :--- | :--- | diff --git a/docs/interfaces.md b/docs/interfaces.md index 3706a8b..a91531c 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -131,7 +131,8 @@ See [docs/wire-protocol-and-shm-bus.md](wire-protocol-and-shm-bus.md) for semant pub struct WorkspaceRoots { pub state_dir: PathBuf, pub config_dir: PathBuf, pub runtime_dir: PathBuf } impl WorkspaceRoots { pub fn from_env() -> Self; } // absolute paths only; empty root => fail closed -pub fn project_root(cwd: &Path) -> PathBuf; // nearest ancestor with `.git` +pub fn project_root(cwd: &Path) -> PathBuf; // nearest git work tree top (git's discovery rules) +pub fn has_git_repository(dir: &Path) -> bool; // `dir/.git` is a repository git accepts pub fn default_workspace_dir(cwd: &Path, roots: &WorkspaceRoots) -> PathBuf; pub fn verify(dir: &Path, roots: &WorkspaceRoots) -> Result<(), TrustError>; // owner, mode, OWNER seal pub fn prepare(dir: &Path, roots: &WorkspaceRoots) -> Result<(), TrustError>; // create + seal diff --git a/docs/security-and-threat-model.md b/docs/security-and-threat-model.md index 3d41fa3..f431f92 100644 --- a/docs/security-and-threat-model.md +++ b/docs/security-and-threat-model.md @@ -57,7 +57,7 @@ the file-backed telepathy ring (`icx-fabric-v1.shm`). | Threat | Control | Implementation | | :--- | :--- | :--- | -| A cloned repository ships a populated `.icx/` that `icx` loads and injects into agent context (ICX-AUD-010). | The default workspace lives outside the repository, at `/workspaces/`; the project root is the nearest ancestor containing `.git`. A repository-local `.icx/` is never loaded implicitly; `icx` prints a one-time warning that it is ignored. | `crates/icx-adapters/src/workspace.rs` (`project_root`, `default_workspace_dir`, `resolve`); `crates/icx-cli/src/main.rs` | +| A cloned repository ships a populated `.icx/` that `icx` loads and injects into agent context (ICX-AUD-010). | The default workspace lives outside the repository, at `/workspaces/`; the project root is the top of the nearest git work tree, found by git's own rules: a `.git` directory git rejects (empty, or without `HEAD`, `objects` and `refs`) is skipped, and a `.git` file naming no repository ends the search (#120). A repository-local `.icx/` is never loaded implicitly; `icx` prints a one-time warning that it is ignored. | `crates/icx-adapters/src/workspace.rs` (`project_root`, `default_workspace_dir`, `resolve`); `crates/icx-cli/src/main.rs` | | A directory selected with `--dir` or `ICX_DIR` was prepared by someone else. | Every workspace must be a directory owned by the effective uid with no group/other permission bits, and must carry a valid `OWNER` seal: a keyed BLAKE3 MAC of its canonical path under the install key. An existing unsealed directory is refused until the user runs `icx trust --dir `, which sets mode `0700`, rewrites `.gitignore` to `*`, writes the seal, re-stamps the store, and warns if the directory is inside a git work tree. A seal does not survive copying or moving the directory. | `workspace.rs` (`verify`, `prepare`, `trust`, `check_dir_security`, `compute_seal`) | | The store file inside a trusted directory is replaced (for example by `git pull` in a directory the user trusted). | Every save MAC-stamps the store: a keyed BLAKE3 MAC over the canonical path, the store `generation`, and a digest of all persisted state (chunk config, graph, MMU state, HDC snapshot and event count, and every artifact id with its full digest). Sealed loads reject a store whose MAC does not verify. | `crates/icx-adapters/src/store.rs` (`state_digest`, `store_seal`) | | No private location can be determined (`HOME` and XDG variables unset or relative). | Only absolute environment paths are honoured. With no usable root, trust operations fail closed; there is no fallback to a shared directory such as `/tmp`. | `WorkspaceRoots::from_env` in `workspace.rs` | diff --git a/docs/testing-strategy.md b/docs/testing-strategy.md index 910a252..8f9d81d 100644 --- a/docs/testing-strategy.md +++ b/docs/testing-strategy.md @@ -125,6 +125,19 @@ All CI jobs use the pinned `1.100.0` toolchain and SHA-pinned actions fractal suffix) and `ICX_MEASURE_STORE= cargo test --release -p icx-adapters --test lexical_index measure -- --ignored --nocapture` (lexical index). +## 3a. v1.6.0 additions: developer harnesses + +- `crates/icx-codec/tests/redact_dev_harness.rs` holds two ignored, report-only tests from the + v1.5.x red-team rounds: `fuzz` joins fixed fragments into lines from a fixed seed (`FUZZ_N`, + `LEAKS=1`) and counts surviving placeholders and non-idempotent results; `cases` runs a JSON + case file (`CASES`). A surviving placeholder is only a candidate leak, so neither is a gate. +- `scripts/redactor-differential.sh [BASE_REF]` runs that fuzz in the working tree and in a + temporary worktree of `BASE_REF` (default `main`) and lists the lines that leak on only one + side. Run it on any redactor change and read `new-leaks.txt` before review. +- `scripts/measure_fts_index.py ` builds throwaway SQLite FTS5 indexes (porter and + trigram, with and without positions) over a workspace's stored text, read only, and reports + size and insert time: the evidence step for the `grep_cold` index (T-91-003). + ## 4. v1.2.0 qualification additions New integration fixtures cover YAML scalar and redaction counterexamples, Profile A framing, diff --git a/scripts/measure_fts_index.py b/scripts/measure_fts_index.py new file mode 100755 index 0000000..b4ea032 --- /dev/null +++ b/scripts/measure_fts_index.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2026 DoubleGate +# SPDX-License-Identifier: GPL-3.0-or-later +"""Size and build time of SQLite FTS5 indexes over a workspace's stored outputs (T-91-003). + +Opens a workspace's `icx.sqlite3` read-only, reassembles each artifact's text from its chunks, +and builds one throwaway FTS5 index per tokenizer configuration, reporting index size against the +stored text and the insert time per artifact. It is the evidence step for choosing a `grep_cold` +index. The store's contents are not changed (SQLite may still touch the `-shm` file of a store in +WAL mode). The indexes hold stored, already redacted text, so they are written to a private +(0700) directory and deleted afterwards unless `--keep` is given. + +Configurations ending in `-contentless` (`content=''`) store the index only, as an index over the +existing `chunks` table would; the others also keep a copy of the text in the FTS5 table. Insert +time is one bulk transaction over the whole store (backfill cost), not the latency of indexing +one output as it is stored; `optimize` and `VACUUM` are not timed. + +Usage: + python3 scripts/measure_fts_index.py ~/.local/state/icx/workspaces/ + python3 scripts/measure_fts_index.py path/to/icx.sqlite3 --json results.json +""" + +from __future__ import annotations + +import argparse +import json +import sqlite3 +import sys +import tempfile +import time +from pathlib import Path + +CONFIGS = { + "porter": "tokenize='porter unicode61 remove_diacritics 2'", + "porter-detail-column": "tokenize='porter unicode61 remove_diacritics 2', detail=column", + "porter-contentless": "tokenize='porter unicode61 remove_diacritics 2', content=''", + "trigram": "tokenize='trigram'", + "trigram-detail-none": "tokenize='trigram', detail=none", + "trigram-contentless": "tokenize='trigram', content=''", +} + + +def db_id(chunk_id: int) -> int: + """The store keeps a u64 `ArtifactId` bit-cast to SQLite's signed 64-bit integer.""" + return chunk_id - (1 << 64) if chunk_id >= 1 << 63 else chunk_id + + +def load_texts(db: Path) -> list[str]: + src = sqlite3.connect(f"{db.resolve().as_uri()}?mode=ro", uri=True) + try: + texts = [] + for (meta,) in src.execute("SELECT meta FROM artifacts ORDER BY id"): + parts = [] + for cid in json.loads(meta).get("chunk_ids", []): + row = src.execute( + "SELECT bytes FROM chunks WHERE id = ?", (db_id(cid),) + ).fetchone() + if row is None: + raise SystemExit( + "an artifact references a missing chunk; store damaged?" + ) + parts.append(row[0]) + texts.append(b"".join(parts).decode("utf-8", "replace")) + return texts + finally: + src.close() + + +def build(texts: list[str], path: Path, options: str) -> dict: + path.unlink(missing_ok=True) + out = sqlite3.connect(path) + try: + out.execute(f"CREATE VIRTUAL TABLE x USING fts5(body, {options})") + start = time.perf_counter() + out.executemany("INSERT INTO x(rowid, body) VALUES (?, ?)", enumerate(texts)) + out.commit() + elapsed = time.perf_counter() - start + out.execute("INSERT INTO x(x) VALUES('optimize')") + out.commit() + out.execute("VACUUM") + finally: + out.close() + return {"bytes": path.stat().st_size, "insert_s": round(elapsed, 3)} + + +def measure(texts: list[str], total: int, out: Path, keep: bool) -> dict: + results: dict = {} + for name, options in CONFIGS.items(): + path = out / f"{name}.db" + try: + r = build(texts, path, options) + finally: + if not keep: + path.unlink(missing_ok=True) + r["ratio_to_text"] = round(r["bytes"] / total, 3) + r["ms_per_artifact"] = round(r["insert_s"] / len(texts) * 1e3, 3) + results[name] = r + print( + f"{name}: {r['bytes'] / 1e6:.1f} MB ({r['ratio_to_text']:.2f}x text), " + f"insert {r['insert_s']:.1f} s ({r['ms_per_artifact']:.2f} ms/artifact)" + ) + return results + + +def main() -> int: + ap = argparse.ArgumentParser( + description="Measure SQLite FTS5 index size over a workspace's stored outputs." + ) + ap.add_argument("store", type=Path, help="workspace directory or its icx.sqlite3") + ap.add_argument( + "--out", type=Path, help="directory for the indexes (default: private temp)" + ) + ap.add_argument("--json", type=Path, help="also write the results as JSON here") + ap.add_argument("--keep", action="store_true", help="keep the index files") + args = ap.parse_args() + + db = args.store / "icx.sqlite3" if args.store.is_dir() else args.store + if not db.is_file(): + print(f"no store at {db}", file=sys.stderr) + return 2 + # Never change an existing directory's mode; refuse one others can read. + if ( + args.out + and args.out.exists() + and (not args.out.is_dir() or args.out.stat().st_mode & 0o077) + ): + print( + f"{args.out} must be a directory only you can access (0700)", + file=sys.stderr, + ) + return 2 + texts = load_texts(db) + total = sum(len(t.encode()) for t in texts) + if total == 0: + print("the store holds no text", file=sys.stderr) + return 2 + + results = { + "artifacts": len(texts), + "text_bytes": total, + "sqlite_version": sqlite3.sqlite_version, + } + print( + f"artifacts={len(texts)} text={total / 1e6:.1f} MB (SQLite {sqlite3.sqlite_version})" + ) + if args.out: + if not args.out.exists(): + args.out.mkdir(mode=0o700, parents=True) + results.update(measure(texts, total, args.out, args.keep)) + elif args.keep: + out = Path(tempfile.mkdtemp(prefix="icx-fts-")) # mkdtemp creates it 0700 + results.update(measure(texts, total, out, keep=True)) + print(f"indexes kept in {out}") + else: + with tempfile.TemporaryDirectory(prefix="icx-fts-") as tmp: + results.update(measure(texts, total, Path(tmp), keep=False)) + if args.json: + args.json.write_text(json.dumps(results, indent=2) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/redactor-differential.sh b/scripts/redactor-differential.sh new file mode 100755 index 0000000..7a3e6f2 --- /dev/null +++ b/scripts/redactor-differential.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: 2026 DoubleGate +# SPDX-License-Identifier: GPL-3.0-or-later +# +# redactor-differential.sh -- compare the redactor in this working tree against a base ref. +# +# scripts/redactor-differential.sh [--cases FILE.json] [--n LINES] [--out DIR] [BASE_REF] +# +# Runs the `redact_dev_harness` fragment fuzz (fixed seed, so both trees see the same lines) in +# this tree and in a temporary detached worktree of BASE_REF (default: main), and reports: +# new-leaks.txt lines whose placeholder survives here but not on BASE_REF (look at these) +# fixed-leaks.txt lines that leak on BASE_REF but not here +# With --cases, it also runs the case file on both trees and prints every case whose tag differs. +# +# A surviving placeholder is a leak only after a sensitive key, so read new-leaks.txt by hand; it +# is a review aid, not a gate. This tree's harness is copied over the base worktree's, so both +# sides always generate the same lines and apply the same leak test. +# +# Environment: +# CARGO_WRAP command prefix for cargo, e.g. "agent-workstation resource --wait 1800 build --" +# BASE_TARGET_DIR cargo target directory for the base tree (default: target/redactor-diff-base +# in this repository, kept between runs so the base is not rebuilt from scratch) +# CARGO_BUILD_JOBS is passed through as usual. +set -euo pipefail +export LC_ALL=C # byte order for sort, comm and join + +usage() { sed -n '6,13p' "$0" >&2; exit 2; } +cases="" n=200000 out="" base="main" positional=0 +while [ $# -gt 0 ]; do + case "$1" in + --cases) [ $# -ge 2 ] || usage; cases=$(realpath "$2"); shift 2 ;; + --n) [ $# -ge 2 ] || usage; n=$2; shift 2 ;; + --out) [ $# -ge 2 ] || usage; out=$2; shift 2 ;; + -h|--help) usage ;; + -*) usage ;; + *) [ "$positional" -eq 0 ] || usage; base=$1; positional=1; shift ;; + esac +done +case "$n" in ''|*[!0-9]*) usage ;; esac + +repo=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) +harness=crates/icx-codec/tests/redact_dev_harness.rs +[ -f "$repo/$harness" ] || { echo "missing $harness in $repo" >&2; exit 1; } +git -C "$repo" rev-parse --verify --quiet "$base^{commit}" > /dev/null \ + || { echo "unknown base ref: $base" >&2; exit 1; } +out=${out:-$(mktemp -d "${TMPDIR:-/tmp}/icx-redactor-diff.XXXXXX")} +mkdir -p "$out" +wt=$(mktemp -d "${TMPDIR:-/tmp}/icx-redactor-base.XXXXXX") +cleanup() { + git -C "$repo" worktree remove --force "$wt" > /dev/null 2>&1 \ + || { rm -rf "$wt"; git -C "$repo" worktree prune; } +} +trap cleanup EXIT +git -C "$repo" worktree add --detach --quiet "$wt" "$base" +mkdir -p "$(dirname "$wt/$harness")" +cp "$repo/$harness" "$wt/$harness" + +read -r -a wrap <<< "${CARGO_WRAP:-}" +run() { # tree label test [env...] + local tree=$1 label=$2 test=$3; shift 3 + local target=() + [ "$label" = base ] && target=(CARGO_TARGET_DIR="${BASE_TARGET_DIR:-$repo/target/redactor-diff-base}") + (cd "$tree" && env ${target[@]+"${target[@]}"} "$@" ${wrap[@]+"${wrap[@]}"} cargo test -q --release -p icx-codec \ + --test redact_dev_harness -- --ignored --nocapture --exact "$test") > "$out/$label.$test.log" 2>&1 \ + || { echo "cargo test failed in $tree; see $out/$label.$test.log" >&2; exit 1; } +} + +for side in head base; do + tree=$repo; [ "$side" = base ] && tree=$wt + run "$tree" "$side" fuzz FUZZ_N="$n" LEAKS=1 + grep '^L ' "$out/$side.fuzz.log" | sort -u > "$out/$side.leaks.txt" || true + if [ -n "$cases" ]; then run "$tree" "$side" cases CASES="$cases" ALL=1; fi +done + +comm -23 "$out/head.leaks.txt" "$out/base.leaks.txt" > "$out/new-leaks.txt" +comm -13 "$out/head.leaks.txt" "$out/base.leaks.txt" > "$out/fixed-leaks.txt" +echo "base: $base ($(git -C "$repo" rev-parse --short "$base")), fuzz lines: $n, results: $out" +grep -h '^fuzz:' "$out/head.fuzz.log" | sed 's/^/ head /' +grep -h '^fuzz:' "$out/base.fuzz.log" | sed 's/^/ base /' +echo " new leaks: $(wc -l < "$out/new-leaks.txt") ($out/new-leaks.txt)" +echo " fixed leaks: $(wc -l < "$out/fixed-leaks.txt") ($out/fixed-leaks.txt)" + +if [ -n "$cases" ]; then + tags() { grep -E '^#[0-9]+ ' "$1" | awk '{print $1, $2}' | sort -k1,1; } + echo "cases whose tag differs (case head base):" + join <(tags "$out/head.cases.log") <(tags "$out/base.cases.log") | awk '$2 != $3' | sort -t'#' -k2 -n +fi