Skip to content

fix: git-accurate project root (#120); stop tests leaking /tmp dirs; dev tools - #119

Merged
doublegate merged 6 commits into
mainfrom
fix/v1.6.0-test-tmp-cleanup
Nov 28, 2026
Merged

doublegate merged 6 commits into
mainfrom
fix/v1.6.0-test-tmp-cleanup

Conversation

@doublegate

@doublegate doublegate commented Nov 28, 2026 •

Copy link
Copy Markdown
Owner

Motivation

Every cargo test run left about 30 directories in /tmp, and 6,483 had built up (about 1.2 GB
on a tmpfs /tmp). Separately, the v1.5.x red-team rounds' scratch tooling was about to be lost
to /tmp cleanup; two pieces are worth keeping for the next redactor change and for T-91-003.

Changes

Test hygiene (1a256be)

  • install_cli: each throwaway HOME is a guard removed when the test passes; a failing test
    keeps it for inspection.
  • Daemon stub unit tests join the daemon after its idle exit and remove their workspace.
  • The per-process unit-test sandbox icx_cli_test_roots_<pid> outlives every test, so its setup
    removes the sandboxes of exited test processes (Linux, /proc/<pid>).
  • zstd damaged-frame property test removes each case's directory, not only the file.

Developer tools (6d92736)

  • crates/icx-codec/tests/redact_dev_harness.rs: seeded fragment fuzz and JSON case runner,
    #[ignore]d and report-only (not a gate).
  • scripts/redactor-differential.sh [BASE_REF]: runs the fuzz here and in a temporary worktree of
    the base ref; lists lines that leak on only one side.
  • scripts/measure_fts_index.py <workspace>: read-only FTS5 sizing over stored text (T-91-003).
  • CHANGELOG (Unreleased, Added) and docs/testing-strategy.md section 3a.

Project root lookup (5315ae4, fixes #120)

  • project_root follows git's discovery: a .git directory needs a valid HEAD plus objects
    and refs (in the common dir for a linked worktree), otherwise it is skipped; a .git file
    naming no repository ends the search, as git does. icx trust's in-repo note uses the same check.
  • worktree_root.rs: empty, HEAD-only, bad-gitfile and minimal-valid cases, each asserted against
    git rev-parse --show-toplevel; the test fails on the previous lookup (checked on a HEAD worktree).
  • Fixtures that faked a repository with an empty .git (workspace_trust.rs) now use a minimal
    valid one; the proxy routing test makes each project its own repository.
  • CHANGELOG (Fixed), README, architecture, interfaces, deployment guide and threat model updated.

Fixes #120

Checks run

  • cargo fmt --all -- --check, cargo clippy -p icx-cli -p icx-adapters -p icx-codec --all-targets -- -D warnings: clean.
  • install_cli (25), icx-cli unit tests (59), codex_rollout_zstd_props (4): pass, and add no
    directories to /tmp (counted before and after).
  • redactor-differential.sh --n 20000 main: 0 new, 0 fixed leaks (tree vs itself); temporary
    worktree removed. Case-file mode checked on three cases.
  • measure_fts_index.py on a 592-artifact store: store checksum unchanged.
  • ruff check and format, shellcheck, uvx reuse lint, gitleaks: clean.
  • cargo test --workspace at 5315ae4: 709 passed, 0 failed. cargo clippy --workspace --all-targets -- -D warnings clean. (Before the fix, proxy_routes_each_project_into_its_own_workspace
    failed locally on unmodified main because of a stray empty /tmp/.git; that is Project root lookup accepts any .git, including an empty directory git rejects #120.)

🤖 Generated with Claude Code

Every `cargo test` run left about 30 directories behind, and 6,483 had built up
(about 1.2 GB on a tmpfs /tmp):

- install_cli: each throwaway HOME is now a guard that removes it when the test
  passes (a failing test keeps it for inspection).
- the daemon stub tests join the daemon after its idle exit and remove their
  workspace, as the other daemon tests already did.
- the shared per-process unit-test sandbox (icx_cli_test_roots_<pid>) cannot be
  removed when a test ends, so its setup removes the sandboxes of test processes
  that have exited (Linux, via /proc/<pid>).
- the zstd damaged-frame property test removes each case's directory, not only
  its file.
Kept from the v1.5.x red-team rounds' scratch tooling, rewritten for reuse:

- crates/icx-codec/tests/redact_dev_harness.rs: a seeded fragment fuzz and a
  JSON case-file runner, both ignored and report-only.
- scripts/redactor-differential.sh: runs that fuzz in the working tree and in a
  temporary worktree of a base ref, and lists lines that leak on only one side.
- scripts/measure_fts_index.py: builds throwaway SQLite FTS5 indexes 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).
@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-28T03:14:45.524588Z 6d92736 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Antigravity review (Gemini via Ultra)

Tightens project_root (and adds has_git_repository / inside_work_tree) to match git's own .git discovery with bounded, non-blocking, no-follow control-file reads (#120), stops icx-adapters and icx-cli tests from leaking /tmp directories, and adds developer tooling for differential redactor fuzzing and read-only SQLite FTS5 sizing.

Blocking issues

None found.

Suggestions

  • Shared /tmp race in stale-root cleanup test (crates/icx-cli/src/main.rs, stale_test_roots_of_exited_processes_are_removed_and_nothing_else, lines 4331–4344): The test isolates dead and dead_file per-PID to avoid concurrent-run collisions, but hardcodes the global path /tmp/icx_cli_test_roots_1 for live. Two concurrent cargo test runs on the same host can race on creating and removing icx_cli_test_roots_1 (causing assert!(live.is_dir()) to fail), and an existing file or another user's directory at that path will panic create_dir_all. Extract a remove_stale_test_roots_in(dir: &Path) helper and run the test inside a per-test temp directory so it never mutates shared /tmp state.
  • Linux-only stale-root cleanup (crates/icx-cli/src/main.rs, remove_stale_test_roots, lines 306–329): Checking /proc/{pid} restricts cleanup to #[cfg(target_os = "linux")], so non-Linux Unix test runs still leak icx_cli_test_roots_<pid> directories. Checking liveness via kill(pid, 0) (e.g. rustix::process::test_kill_process, treating EPERM as alive and ESRCH as dead) works across all Unix targets.
  • Docstring vs. behavior for nested repos/worktrees (crates/icx-cli/src/main.rs, inside_work_tree, lines 331–337): The doc comment states that "A work tree's own top, main or linked, is not 'inside' one", but because inside_work_tree checks dir.parent(), a submodule or linked worktree placed inside another repository (e.g., <repo>/.worktrees/agent) returns true. That conservative warning in icx trust is reasonable, so update the comment to reflect nested repositories/worktrees (or short-circuit on has_git_repository(dir) if nested tops are meant to be excluded).
  • --out validation gaps in FTS measurement script (scripts/measure_fts_index.py, lines 122–131, 146–148):
    • args.out.stat().st_mode & 0o077 follows symlinks (stat instead of lstat) and does not check ownership (st_uid == os.getuid()). A broken symlink also passes args.out.exists() == False and later crashes with an unhandled FileExistsError in mkdir().
    • load_texts(db) runs between the existence/mode check and mkdir(), widening the TOCTOU window; validate/create the output directory in one place immediately before writing (or use os.open / lstat after mkdir(exist_ok=True)).
    • Clarify in --out's help text that generated .db files are still deleted unless --keep is also passed.
  • Relative BASE_TARGET_DIR and unvalidated --cases path (scripts/redactor-differential.sh, lines 31, 62):
    • If BASE_TARGET_DIR is relative, cd "$tree" resolves it inside the temporary worktree $wt, which cleanup() deletes on exit—defeating the cross-run build cache. Resolve BASE_TARGET_DIR to an absolute path before entering $wt.
    • cases=$(realpath "$2") does not check that the file exists (realpath -e or [ -f "$cases" ]), so a typo in --cases is only caught after compiling icx-codec in --release mode.

Nitpicks

  • crates/icx-adapters/src/workspace.rs (project_root, dot_git, worktree_main_root): On a linked worktree, .git and commondir are each opened and read twice per project_root call; returning the resolved gitdir from dot_git avoids the redundant I/O on every hook.
  • crates/icx-codec/tests/redact_dev_harness.rs (show, lines 106–114): Replacing ASCII tokens with §, ≡, ¦, etc. is lossy if a CASES fixture tests those Unicode characters directly.
  • scripts/redactor-differential.sh (line 27): usage() prints 6,13p, starting with an empty # comment line instead of the description on line 5.

Automated first-pass review by agy on a self-hosted runner -- not a human review.

Earlier review rounds (newest first)
Round reviewed at 2026-11-28 04:37 UTC

Antigravity review (Gemini via Ultra)

Replaces .git-existence checks in project_root with git-compatible repository discovery (#120), cleans up leaked temporary test directories across icx-adapters and icx-cli, and adds two developer scripts plus an ignored redactor fuzz harness.

Blocking issues

None found.

Suggestions

  • crates/icx-cli/src/main.rs:4281-4306 (stale_test_roots_of_exited_processes_are_removed_and_nothing_else):
    • The test writes fixed names (pid_max + 1, pid_max + 2, parent_id()) directly into env::temp_dir(). Two concurrent test runs under the same user will race on dead_file and live, and a panic before lines 4302-4305 leaks both entries.
    • If the test binary is ever run directly inside a Linux PID namespace whose parent is outside the namespace, parent_id() is 0, /proc/0 does not exist, and assert!(live.is_dir()) fails.
    • In remove_stale_test_roots (crates/icx-cli/src/main.rs:307-329), checking process liveness via kill(pid, 0) (e.g., rustix::process::test_kill_process treating ESRCH as exited) instead of /proc/{pid} would also work on non-Linux Unix targets (macOS/BSD) and not break if /proc is absent.
  • crates/icx-cli/src/main.rs:651-653 (run_trust): When --dir is the root of a linked git worktree, project_root(&canonical) resolves to the main repository root (root != canonical), so run_trust now emits the "inside a git work tree" warning for a linked worktree root even though it stays silent for a main repository root (and the comment says "whose top is above dir"). If the intent is to warn only for subdirectories of a work tree, check canonical.ancestors().skip(1).any(workspace::has_git_repository) (or update the comment/behavior to warn on the work tree root consistently for both main repos and worktrees).
  • crates/icx-adapters/tests/worktree_root.rs:87-109 & 177-223: git_toplevel sets GIT_CEILING_DIRECTORIES to isolate against repositories above TMPDIR, but project_root does not honor GIT_CEILING_DIRECTORIES. If TMPDIR is placed inside a git repository, assert_eq!(project_root(&plain), plain) and the planted_control_files assertions will walk past base and fail. Planting an invalid .git file at base/.git (or running the negative cases under a sub-barrier) stops both git and project_root.
  • crates/icx-adapters/src/workspace.rs:188-191 (gitfile_target) & :225 (is_git_directory):
    • Git's read_gitfile_gently requires "gitdir: " (with a space) and strips only trailing \r/\n, whereas strip_prefix("gitdir:")?.trim() accepts gitdir:/path without a space and strips trailing spaces from a path.
    • r.trim_start() strips Unicode whitespace (e.g., \u{00A0}), while git's validate_headref uses ASCII isspace (trim_start_matches(|c: char| c.is_ascii_whitespace())).
  • scripts/measure_fts_index.py:133-136: args.out.chmod(0o700) unconditionally tightens permissions on an existing directory passed via --out. Passing --out . silently restricts the caller's working directory to 0700, and --out /tmp fails with PermissionError. Create a fresh 0700 subdirectory inside --out or refuse an existing directory with broader permissions instead of mutating it.
  • scripts/measure_fts_index.py:70-75: insert_s / ms_per_artifact measures a single bulk transaction (executemany + one commit()) and excludes optimize/VACUUM. Note in the output/docstring that this reflects backfill cost, not per-tool-call incremental commit latency.
  • scripts/redactor-differential.sh:54,57-62:
    • cp "$repo/$harness" "$wt/$harness" fails if BASE_REF predates crates/icx-codec/tests/; add mkdir -p "$(dirname "$wt/$harness")".
    • Running cargo test --release in the temporary worktree $wt without CARGO_TARGET_DIR rebuilds icx-codec and all dependencies from scratch in /tmp on every invocation and discards the artifacts on exit.
    • In cleanup (:48-51), git worktree prune runs unconditionally even when worktree remove succeeded; restrict it to the || rm -rf "$wt" fallback so it does not prune unrelated worktrees.

Nitpicks

  • crates/icx-codec/tests/redact_dev_harness.rs:2: Verify SPDX-License-Identifier: GPL-3.0-or-later AND AGPL-3.0-or-later (conjunctive AND rather than OR or single license) matches REUSE.toml and passes uvx reuse lint.
  • scripts/redactor-differential.sh:28: ;;& requires Bash 4+ and is a syntax error under stock macOS /bin/bash (3.2).
  • crates/icx-adapters/src/workspace.rs:175: read_to_string rejects non-UTF-8 branch names in HEAD or non-UTF-8 paths in .git/commondir.
  • PR scope: Bundles three unrelated changes (git discovery fix Project root lookup accepts any .git, including an empty directory git rejects #120, test /tmp leak cleanup, and redactor/FTS5 dev tooling) in one PR.

Automated first-pass review by agy on a self-hosted runner -- not a human review.

Round reviewed at 2026-11-28 03:38 UTC

Antigravity review (Gemini via Ultra)

Tightens project_root (and icx trust) to follow git's repository-discovery rules with hardened control-file reads, cleans up leaking /tmp directories across several test suites, and adds two developer harnesses for redactor differential fuzzing and FTS5 index sizing.

Blocking issues

None found.

Suggestions

  • scripts/redactor-differential.sh:47 — [ -f "$wt/$harness" ] || cp "$repo/$harness" "$wt/$harness" skips copying the harness once BASE_REF already contains an older version of redact_dev_harness.rs. As soon as a future PR adds or reorders entries in FRAGMENTS, next() % FRAGMENTS.len() will generate completely different lines on head vs base, making comm -23/comm -13 output noise. Always overwrite $wt/$harness with $repo/$harness (or fail loudly if the two harness files differ).
  • scripts/measure_fts_index.py:97-119 — When --out is omitted and --keep is false, the script deletes individual .db files but leaks the tempfile.mkdtemp(prefix="icx-fts-") directory on every run (and leaks .db files containing workspace text on error or interrupt). When --out is passed—including the docstring's own --out /tmp/fts example—out.mkdir(parents=True, exist_ok=True) uses the default umask (typically 0755), leaving stored workspace text world-readable despite the docstring's privacy warning. Use tempfile.TemporaryDirectory when --out/--keep are unset, wrap builds in try/finally, and set 0o700 on out.
  • scripts/measure_fts_index.py:41,111 — sqlite3.connect(f"file:{db}?mode=ro", uri=True) breaks if db contains ?, #, or % (prefer f"{db.resolve().as_uri()}?mode=ro"), and on a WAL-mode database without immutable=1, SQLite may still create -shm in the workspace directory despite the docstring stating nothing is modified. Separately, if a store has only empty artifacts (texts is non-empty, total == 0), r["bytes"] / total at line 111 raises ZeroDivisionError.
  • crates/icx-adapters/src/workspace.rs:200-204,244-245 — dot_git parses .git files with .lines().next() (accepting multi-line .git files), while worktree_main_root (and git itself) parses the whole trimmed file and rejects extra lines. Share a single .git-file parser between dot_git and worktree_main_root so they agree on malformed/multi-line gitfiles.
  • crates/icx-adapters/tests/worktree_root.rs:150-166 — planted_control_files_cannot_block_or_bloat_the_lookup invokes mkfifo without #[cfg(unix)], even though read_control_file in workspace.rs:167 is guarded with #[cfg(unix)]. Gate the FIFO sub-test with #[cfg(unix)] (or split the oversized-HEAD assertion out).
  • crates/icx-adapters/tests/worktree_root.rs:86-99 — git_toplevel hardcodes cwd.ancestors().nth(3) as GIT_CEILING_DIRECTORIES, which couples the helper to the caller's exact nesting depth (plain gets base.parent(), deep gets base). Passing base explicitly is less fragile.
  • crates/icx-codec/tests/redact_dev_harness.rs:87-89,117-119 — FRAGMENTS includes "pin: ", "otp=", "1234", and "4821", but leaks() only checks for "qqzz" and "aaaa-aaaa", so leaked numeric PIN/OTP values will be reported as non-leaking.
  • crates/icx-cli/src/main.rs:303-323 — remove_stale_test_roots does not check entry.file_type().is_ok_and(|t| t.is_dir()) before calling remove_dir_all, and on Linux hosts with /proc mounted hidepid=1/2, /proc/<pid> is hidden for other users' processes. Checking file_type().is_dir() (and ownership on Unix) narrows cleanup to this user's directories.
  • scripts/redactor-differential.sh:27-29,49-53 — "${wrap[@]}" under set -u fails with unbound variable on Bash < 4.4 (e.g., macOS /bin/bash) when CARGO_WRAP is empty; use ${wrap[@]+"${wrap[@]}"}. Passing --cases, --n, or --out without a following argument also dies with an unbound $2 error instead of calling usage.

Nitpicks

  • crates/icx-adapters/src/workspace.rs:179 — If a control file grows past MAX_CONTROL_FILE between file.metadata() and read_to_string, file.take(MAX_CONTROL_FILE) silently truncates it; reading MAX_CONTROL_FILE + 1 bytes and rejecting > MAX_CONTROL_FILE avoids truncation.
  • crates/icx-adapters/src/workspace.rs:240 — if !std::fs::symlink_metadata(&dot_git).ok()?.is_file() in worktree_main_root is now redundant with read_control_file.
  • crates/icx-cli/src/main.rs:4301-4302,4326-4327 — If an assertion fails before server.join(), the test still leaks &ws (unlike the TempHome RAII guard added in crates/icx-cli/tests/install_cli.rs:15-23).
  • crates/icx-codec/tests/redact_dev_harness.rs:121-123 — env_flag uses var_os(name).is_some(), so LEAKS=0 or ALL=0 still enables the flag.
  • scripts/redactor-differential.sh:60,64-65,73-75 — Prefixing sort/comm/join with LC_ALL=C avoids locale-dependent collation overhead and quirks.
  • docs/interfaces.md:134 — The new public function workspace::has_git_repository (crates/icx-adapters/src/workspace.rs:140) is not listed alongside project_root.

Automated first-pass review by agy on a self-hosted runner -- not a human review.

Round reviewed at 2026-11-28 03:31 UTC

Antigravity review (Gemini via Ultra)

Fixes git-style project-root discovery for #120, reduces test /tmp directory leaks, and adds redactor differential-fuzzing and SQLite FTS5 sizing developer tools.

Blocking issues

  • Unbounded / non-regular file reads in untrusted ancestor directories (crates/icx-adapters/src/workspace.rs:187-199): dot_git() guards .git files with meta.is_file() and meta.len() <= 4096, but is_git_directory() immediately calls std::fs::read_to_string() on HEAD and commondir with neither check. Because project_root() traverses shared ancestor directories such as /tmp (the exact #120 scenario), a local attacker can place a FIFO at /tmp/.git/HEAD (or /tmp/.git/commondir) to hang icx indefinitely, or a symlink to /dev/zero / a multi-GB file to OOM it. Use a shared helper that verifies is_file() and caps reads (e.g., File::open + .take(4096) after checking metadata().is_file(), or O_NONBLOCK on Unix) for .git, HEAD, and commondir.

Suggestions

  • scripts/redactor-differential.sh:47 breaks differential comparisons once redact_dev_harness.rs changes: [ -f "$wt/$harness" ] || cp "$repo/$harness" "$wt/$harness" skips copying the working tree's harness whenever BASE_REF already has the file. As soon as a future PR adds/reorders FRAGMENTS or changes leaks(), head and base will generate different xorshift64 inputs (next() % FRAGMENTS.len()) and produce meaningless comm diffs. Unconditionally overwrite $wt/$harness in the throwaway worktree so both sides always run the same corpus and leak check.
  • scripts/measure_fts_index.py:93-119 has three bugs:
    • Division by zero: line 94 checks if not texts, not total == 0. A store with empty artifacts crashes at line 111 (r["bytes"] / total).
    • Leaks /tmp/icx-fts-* directory and leaves data behind on failure: tempfile.mkdtemp() at line 97 is never removed after unlinking the .db files (ironic given the PR title), and any exception inside build() leaves un-deleted .db files containing workspace text on disk. When --keep is set without --out, the script also never prints the out path. Use tempfile.TemporaryDirectory when not args.out and not args.keep, and print out when --keep is set.
    • Permissions and URI escaping: the docstring warns to keep output directories private and gives --out /tmp/fts as an example, yet out.mkdir(parents=True, exist_ok=True) uses default umask (0755/0644 files) instead of 0o700. Also f"file:{db}?mode=ro" (line 41) breaks on paths containing ?, #, or % (f"{db.resolve().as_uri()}?mode=ro" avoids this).
  • scripts/measure_fts_index.py:63 measures content-bearing FTS5 tables: CREATE VIRTUAL TABLE x USING fts5(body, ...) stores a full copy of body inside FTS5 in addition to the inverted index, adding ~1.0x overhead to every ratio_to_text. If grep_cold will use external-content or contentless FTS5 (content='') backed by the existing chunks table, add or switch to content='' so T-91-003 sizing evidence is not skewed.
  • crates/icx-codec/tests/redact_dev_harness.rs:87-89,117-119 ignores "4821" leaks: FRAGMENTS includes "pin: ", "otp=", and "4821", but leaks() only checks for qqzz and aaaa-aaaa, so surviving pin: 4821 or otp=4821 values are silently classified as non-leaking.
  • crates/icx-cli/src/main.rs:302-323 still leaks the current run's /tmp dir and only cleans up on Linux: remove_stale_test_roots() removes earlier exited processes' directories only when /proc/self exists, so the final cargo test run always leaves icx_cli_test_roots_<pid> behind (and non-Linux hosts never clean up any). Also check entry.file_type().is_ok_and(|t| t.is_dir()) before remove_dir_all.
  • crates/icx-cli/src/main.rs:4300-4302,4325-4327 leaks daemon temp dirs on assertion failure: if an assertion panics before server.join() and fs::remove_dir_all(&ws), the workspace directory is not cleaned up; wrapping it in an RAII guard (like TempHome in install_cli.rs) avoids this.
  • crates/icx-cli/src/main.rs:649 diverges from project_root on invalid .git files: canonical.ancestors().skip(1).any(workspace::has_git_repository) keeps walking past a DotGit::InvalidFile instead of stopping as project_root() and git do.
  • crates/icx-adapters/src/workspace.rs:170-176,189 minor divergences from git's discovery: text.lines().next() accepts a multi-line .git file that git rejects, and h.starts_with("ref: refs/") accepts a multi-line HEAD file. Both also fail on non-UTF-8 Unix paths in gitdir: or commondir.
  • crates/icx-adapters/tests/worktree_root.rs:107-111 can fail when TMPDIR is inside a git repo: git_toplevel(&plain) sets GIT_CEILING_DIRECTORIES, whereas project_root(&plain) has no ceiling and will walk into an enclosing repo if TMPDIR sits inside one.
  • PR title / Conventional Commit scope: the title starts with test:, but the diff changes production workspace resolution (workspace.rs, main.rs) and updates CHANGELOG.md and docs/ for #120. Split the #120 fix out or retitle as fix(...).

Nitpicks

  • crates/icx-codec/tests/redact_dev_harness.rs:121-123: env_flag uses var_os(name).is_some(), so LEAKS=0 or ALL=0 enables the flag.
  • scripts/redactor-differential.sh:25-33: passing --cases, --n, or --out without a value hits $2: unbound variable under set -u instead of printing usage.
  • scripts/redactor-differential.sh:49,52,60-75: set LC_ALL=C around sort/comm/join for locale-independent collation, and use ${wrap[@]+"${wrap[@]}"} if Bash < 4.4 (e.g. stock macOS /bin/bash) matters.
  • crates/icx-codec/tests/redact_dev_harness.rs:2: verify GPL-3.0-or-later AND AGPL-3.0-or-later matches REUSE.toml and other files in crates/icx-codec/ (the two new scripts use GPL-3.0-or-later alone).

Automated first-pass review by agy on a self-hosted runner -- not a human review.

Round reviewed at 2026-11-28 03:17 UTC

Antigravity review (Gemini via Ultra)

This PR reduces /tmp directory leaks across CLI and adapter tests and adds developer harnesses/scripts for differential redactor fuzzing and read-only SQLite FTS5 index sizing.

Blocking issues

  • Differential fuzz silently compares different input streams once the harness evolves (scripts/redactor-differential.sh:47): [ -f "$wt/$harness" ] || cp "$repo/$harness" "$wt/$harness" only copies the harness when BASE_REF predates it. After this PR merges, any future PR that adds a fragment to FRAGMENTS or changes show()/leaks() will run the modified harness on head and the old harness on base; because next() % FRAGMENTS.len() diverges immediately, comm will diff two unrelated sets of lines and produce invalid new-leaks.txt/fixed-leaks.txt output. Copy $repo/$harness over $wt/$harness unconditionally (so both sides always run the same generator and formatter) or fail if the files differ.
  • FTS sizing script leaks its temp directory, leaves .db files on failure, and crashes on 0-byte stores (scripts/measure_fts_index.py:93-98, 111, 118-119):
    • When --out is omitted and --keep is not set, tempfile.mkdtemp(prefix="icx-fts-") creates a temp directory that is never removed—leaking an empty /tmp/icx-fts-* directory on every run.
    • If build() fails partway (e.g., KeyboardInterrupt, disk full, or a SQLite build without trigram), the partially built .db file containing stored workspace text is left behind instead of cleaned up in a try/finally or TemporaryDirectory context manager.
    • If a store contains one or more empty artifacts (texts non-empty, total == 0), r["bytes"] / total at line 111 raises ZeroDivisionError.

Suggestions

  • Clear current process's test root before reuse (crates/icx-cli/src/main.rs:283-286, 319): Because roots() leaves icx_cli_test_roots_<pid> on disk after process exit (which makes sense under unsafe_code = "forbid" without an atexit hook) and remove_stale_test_roots() skips pid == std::process::id(), PID reuse (common in CI containers) will silently inherit stale state/config from an earlier dead run. Call let _ = fs::remove_dir_all(&base); inside the OnceLock initializer before returning WorkspaceRoots. Also note remove_stale_test_roots() is a no-op on non-Linux hosts and can delete a live sandbox if two PID namespaces share /tmp.
  • Use a drop guard for daemon test workspaces (crates/icx-cli/src/main.rs:4300-4302, 4325-4327): If any assertion or .unwrap() panics before server.join() / remove_dir_all(&ws), the workspace directory still leaks. Also verify that joining server (waiting out the daemon idle timeout on both tests) does not noticeably regress cargo test wall time compared to an explicit shutdown signal.
  • Clean up proptest dirs on failure/shrinking (crates/icx-adapters/tests/codex_rollout_zstd_props.rs:94-95): prop_assert! returns early on failure, skipping remove_dir_all(&d) for both the failing case and every proptest shrink attempt. Wrap d in a small RAII guard (like TempHome in install_cli.rs).
  • Missing leak detection for PIN/OTP placeholder and env_flag semantics (crates/icx-codec/tests/redact_dev_harness.rs:88-90, 117-123):
    • FRAGMENTS includes "pin: ", "otp=", "4821", yet leaks() only checks "qqzz" and "aaaa-aaaa", so leaked pin: 4821 / otp=4821 cases go unreported. Either add "4821" to leaks() (and document it) or clarify if it is intentionally a non-secret distractor.
    • env_flag() uses var_os(name).is_some(), so LEAKS=0 or ALL=0 unexpectedly evaluates to true.
  • Harden measure_fts_index.py paths, permissions, and memory (scripts/measure_fts_index.py:41-55, 97-98):
    • sqlite3.connect(f"file:{db}?mode=ro", uri=True) breaks if db contains ?, #, or %; use f"{db.resolve().as_uri()}?mode=ro".
    • out.mkdir(parents=True, exist_ok=True) creates --out (including the docstring's /tmp/fts example) with default umask (0755), contradicting the docstring's warning to keep the directory private; pass mode=0o700 (or os.chmod).
    • When --keep is passed without --out, print out so the user knows where the kept .db files live.
    • load_texts() materializes the entire chunks table and all decoded texts in RAM simultaneously; fetching chunks per artifact (or streaming directly into FTS5) avoids OOM on large workspaces.
  • Argument parsing and build reuse in scripts/redactor-differential.sh:27-30, 44, 49-53:
    • Passing --cases, --n, or --out without a value fails with an opaque set -u unbound $2 error instead of printing usage; extra positional arguments silently overwrite base.
    • If cleanup() falls back to rm -rf "$wt", run git -C "$repo" worktree prune so .git/worktrees does not accumulate stale metadata.
    • "${wrap[@]}" with an empty array fails under set -u on Bash < 4.4 (e.g., stock macOS Bash).
    • Compiling inside $wt rebuilds icx-codec dependencies from scratch into a throwaway target dir unless CARGO_TARGET_DIR is shared.

Nitpicks

  • crates/icx-codec/tests/redact_dev_harness.rs:2 uses SPDX-License-Identifier: GPL-3.0-or-later AND AGPL-3.0-or-later while the two new scripts use GPL-3.0-or-later; confirm this matches REUSE.toml and passes uvx reuse lint.
  • The PR bundles unrelated /tmp test fixes with two new developer tools; splitting them into separate commits or PRs would keep history and CHANGELOG.md cleaner.

Automated first-pass review by agy on a self-hosted runner -- not a human review.

@doublegate

Copy link
Copy Markdown
Owner Author

The local proxy_projects failure noted under Checks run is resolved: after removing the stray empty /tmp/.git the test passes here (2 passed). The lookup issue it exposed is filed as #120 (v1.6.0).

@codecov

codecov Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.36306% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/icx-cli/src/main.rs 98.80% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

project_root took the nearest ancestor where `.git` existed, so one stray
empty `/tmp/.git` resolved every project under /tmp to /tmp and merged their
recall, folded outputs and proxy cache ledgers into one workspace.

It now follows git's discovery: a `.git` directory counts only with a valid
HEAD and `objects` and `refs` directories (in the common directory for a
linked worktree), and is otherwise skipped; a `.git` file that names no
repository ends the search, as git stops there. The trust warning in `icx
trust` uses the same check.

Tests: worktree_root adds the empty, HEAD-only, bad-gitfile and minimal-valid
cases, each checked against `git rev-parse --show-toplevel`; it fails on the
previous lookup. The trust fixtures use a minimal valid `.git`, and the proxy
routing test makes each project its own repository so the host /tmp cannot
change the result.
@doublegate doublegate changed the title test: stop tests leaking /tmp dirs; redactor and FTS dev tools fix: git-accurate project root (#120); stop tests leaking /tmp dirs; dev tools Nov 28, 2026
The #120 lookup read `HEAD` and `commondir` with read_to_string. project_root
runs on every hook and walks every ancestor of the cwd, so a FIFO planted as
`HEAD` in a shared parent blocked the hook, and a large file was read whole.

All control files (`.git` file, `HEAD`, `commondir`, worktree `gitdir`) now go
through one reader: a regular file by symlink_metadata, opened NONBLOCK and
NOFOLLOW, the handle re-checked, at most 4 KiB read (the pattern the agy
transcript reader uses). A symlinked `HEAD` is refused, as other control files
already were (ICX-AUD-018).

Test: a FIFO `HEAD` resolves within a timeout and is not a repository; an
oversized `HEAD` is not a repository.
Workspace lookup:
- `.git` files are parsed by one helper shared with the worktree check:
  the whole file must be one `gitdir:` line, as git's read_gitfile needs.
- `HEAD` is checked as git's validate_headref does (only how it starts:
  `ref:` then `refs/`, or a SHA-1/SHA-256 name); every case is asserted
  against `git rev-parse`.
- Control-file reads take one byte past the limit and reject a file that
  grew after the size check instead of truncating it.
- `icx trust`'s in-repo note uses project_root's answer, so an invalid
  `.git` file ends the search there too.

Tests: stale sandbox cleanup only removes this user's directories of exited
processes (Linux), and clears a reused PID's sandbox; new unit test. The git
oracle helper takes its ceiling explicitly; the FIFO test is unix-gated and
covers a FIFO `.git`.

Dev tools: redactor-differential.sh always copies this tree's harness into
the base worktree, validates its arguments, sorts in the C locale, prunes
the worktree and works on bash < 4.4; the harness counts the `4821` PIN
placeholder and treats `LEAKS=0` as off. measure_fts_index.py uses a private
temp directory removed on exit, a 0700 `--out`, a URI-safe read-only open,
streams chunks per artifact, refuses an empty store and adds contentless
configurations.
@doublegate

Copy link
Copy Markdown
Owner Author

Review rounds addressed in 6ecf811 and 5580d1a.

Blocking (03:31 round): FIFO/unbounded control-file reads. Fixed in 6ecf811: every git control file (.git file, HEAD, commondir, worktree gitdir) goes through one reader (regular file by symlink_metadata, opened NONBLOCK|NOFOLLOW, handle re-checked, at most 4 KiB). Test: a FIFO HEAD resolves within a timeout and is not a repository; an oversized HEAD is not either.

Acted on (5580d1a):

  • redactor-differential.sh: this tree's harness is always copied over the base worktree's; --cases/--n/--out without a value, a non-numeric --n or a second positional print usage; LC_ALL=C; ${wrap[@]+...} for bash < 4.4; git worktree prune after cleanup.
  • measure_fts_index.py: TemporaryDirectory when neither --out nor --keep; --out created and set 0700; --keep without --out prints the path; URI from Path.as_uri(); empty store refused (no division by zero); chunks fetched per artifact; -contentless (content='') configurations added; the docstring now says the store's contents are unchanged and that SQLite may touch a WAL store's -shm.
  • One shared .git-file parser for dot_git and worktree_main_root (one gitdir: line only). HEAD now follows git's validate_headref (only the start is checked); multi-line HEAD, ref: without a space, a bare object name and a ref: outside refs/ are each asserted against git rev-parse.
  • Reads take MAX + 1 and reject a file that grew after the check; the redundant symlink_metadata in worktree_main_root is gone.
  • icx trust note: uses project_root's answer, so it agrees with project_root (and git) on an invalid .git file.
  • Tests: FIFO test #[cfg(unix)] (and covers a FIFO .git); git_toplevel takes base for its ceiling; has_git_repository covered and listed in docs/interfaces.md.
  • remove_stale_test_roots: directories owned by this uid only, Linux-gated, and the process clears its own sandbox first so a reused PID starts clean; new unit test.
  • Harness: leaks() counts 4821; env_flag treats empty and 0 as off.
  • Patch coverage measured locally at 99.2% (122 of 123 changed lines).

Declined:

  • RAII guards for the daemon unit-test workspaces and the zstd proptest directory: a failing test keeps its directory on purpose, the same rule as TempHome in install_cli.rs (it skips removal while panicking), so the failing case can be inspected. Passing runs clean up.
  • Splitting the PR: the owner asked for Project root lookup accepts any .git, including an empty directory git rejects #120 in this PR; the title is fix: and the commits are separate.

Checks at 5580d1a: cargo test --workspace 711 passed, 0 failed; clippy -D warnings and fmt clean; shellcheck, ruff, markdownlint and gitleaks clean.

- icx trust: the in-work-tree note no longer fires for a linked worktree's
  own top, which 5580d1a had introduced. inside_work_tree() asks whether the
  parent resolves to a repository; a unit test covers a repository top, a
  linked worktree top and a subdirectory of each against real git.
- `.git` files need `gitdir: ` with the space and keep the path's trailing
  spaces, as git's read_gitfile_gently does; `HEAD` skips ASCII whitespace
  only after `ref:`. The no-space case is asserted against git.
- Stale sandbox test: per-process names, and PID 1 as the running process
  (present in every PID namespace).
- measure_fts_index.py never changes an existing `--out` directory's mode:
  it refuses one that others can access, before reading the store; insert
  time is documented as a bulk backfill.
- redactor-differential.sh: no `;;&` (bash 3.2), mkdir before copying the
  harness, prune only after a failed `worktree remove`, and a kept
  `target/redactor-diff-base` so the base is not rebuilt on every run.
@doublegate

Copy link
Copy Markdown
Owner Author

Round at 04:37 UTC (5580d1a) addressed in 575564c.

Acted on:

  • run_trust note: right, 5580d1a made it fire for a linked worktree's own top. Now inside_work_tree() asks whether dir's parent resolves to a repository; a unit test with real git covers a repository top, a linked worktree top, and a subdirectory of each.
  • gitfile_target requires gitdir: with the space and strips only trailing \r/\n; HEAD skips ASCII whitespace only. The no-space case is asserted against git rev-parse (git rejects it too).
  • Stale-sandbox test: names derived from the test's own PID (no cross-run race), and PID 1 as the running process, present in every PID namespace.
  • measure_fts_index.py: never changes an existing --out directory's mode; one that group or others can access is refused before the store is read. The docstring says insert time is one bulk transaction (backfill), with optimize/VACUUM untimed.
  • redactor-differential.sh: mkdir -p before copying the harness; worktree prune only after a failed worktree remove; base builds go to a kept target/redactor-diff-base (override BASE_TARGET_DIR); no ;;&.

Declined:

  • kill(pid, 0) for non-Linux: the cleanup is deliberately Linux-only; elsewhere it does nothing, which is the safe failure.
  • TMPDIR inside a git repository: every test in worktree_root.rs and proxy_projects.rs already assumes a temp directory outside any repository; planting a .git at base would hide exactly the ancestor behaviour these tests check.
  • Non-UTF-8 HEAD/.git/commondir content: such a directory is not treated as a repository (fails closed to the cwd). Rare on the supported platforms; not a regression.
  • SPDX GPL-3.0-or-later AND AGPL-3.0-or-later: the same expression as the other files under crates/ (REUSE.toml); uvx reuse lint passes.
  • PR scope: three separate commits, bundled at the owner's request.

At 575564c: cargo test --workspace 712 passed, 0 failed; clippy -D warnings, fmt, shellcheck, ruff and gitleaks clean.

@doublegate
doublegate merged commit acdcbb5 into main Nov 28, 2026
15 checks passed
@doublegate
doublegate deleted the fix/v1.6.0-test-tmp-cleanup branch November 28, 2026 04:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Project root lookup accepts any .git, including an empty directory git rejects

1 participant