Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<first 16 hex of blake3(project root)>`, 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/<first 16 hex of blake3(project root)>`, 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.

Expand Down
146 changes: 128 additions & 18 deletions crates/icx-adapters/src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<main>/.git/worktrees/<name>`) 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 `<main>/.git/worktrees/<name>`) 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<String> {
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.
Expand All @@ -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<PathBuf> {
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<String> {
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()?;
Expand Down
3 changes: 2 additions & 1 deletion crates/icx-adapters/tests/codex_rollout_zstd_props.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
13 changes: 11 additions & 2 deletions crates/icx-adapters/tests/workspace_trust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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();
Expand All @@ -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!(
Expand Down
150 changes: 149 additions & 1 deletion crates/icx-adapters/tests/worktree_root.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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<PathBuf> {
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);
}
Loading