From 1a256be81ccf88e73fba94197e127c2e8645579d Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Fri, 27 Nov 2026 22:13:04 -0500 Subject: [PATCH 1/6] test: remove the temp directories tests leave in /tmp 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_) cannot be removed when a test ends, so its setup removes the sandboxes of test processes that have exited (Linux, via /proc/). - the zstd damaged-frame property test removes each case's directory, not only its file. --- .../tests/codex_rollout_zstd_props.rs | 3 +- crates/icx-cli/src/main.rs | 40 +++++++++++++++++-- crates/icx-cli/tests/install_cli.rs | 38 ++++++++++++++++-- 3 files changed, 73 insertions(+), 8 deletions(-) diff --git a/crates/icx-adapters/tests/codex_rollout_zstd_props.rs b/crates/icx-adapters/tests/codex_rollout_zstd_props.rs index f0d98534..d8eb2b9c 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-cli/src/main.rs b/crates/icx-cli/src/main.rs index e8c657d4..10ad1d83 100644 --- a/crates/icx-cli/src/main.rs +++ b/crates/icx-cli/src/main.rs @@ -281,6 +281,9 @@ 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. + remove_stale_test_roots(); WorkspaceRoots { state_dir: base.join("state"), config_dir: base.join("config"), @@ -294,6 +297,31 @@ fn roots() -> &'static WorkspaceRoots { }) } +/// Removes `icx_cli_test_roots_` sandboxes whose process no longer exists. Linux only (it +/// checks `/proc/`); a live process's sandbox, including one whose PID was reused, is kept. +#[cfg(test)] +fn remove_stale_test_roots() { + if !Path::new("/proc/self").exists() { + return; + } + let Ok(entries) = fs::read_dir(env::temp_dir()) else { + return; + }; + for entry in entries.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; + }; + if pid != std::process::id() && !Path::new(&format!("/proc/{pid}")).exists() { + let _ = fs::remove_dir_all(entry.path()); + } + } +} + /// An MMU that MAC-stamps every save and rejects stores not written by this install. fn workspace_mmu() -> InfinityContextMmu { let mut mmu = InfinityContextMmu::default(); @@ -4250,7 +4278,7 @@ mod tests { 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 +4297,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 +4307,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 +4322,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 a92a85aa..5da186d0 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] From 6d927362a5a852be45eefb03dae4dffa690f10c2 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Fri, 27 Nov 2026 22:13:04 -0500 Subject: [PATCH 2/6] feat(dev): redactor differential harness and FTS index probe 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). --- CHANGELOG.md | 4 + crates/icx-codec/tests/redact_dev_harness.rs | 206 +++++++++++++++++++ docs/testing-strategy.md | 13 ++ scripts/measure_fts_index.py | 126 ++++++++++++ scripts/redactor-differential.sh | 76 +++++++ 5 files changed, 425 insertions(+) create mode 100644 crates/icx-codec/tests/redact_dev_harness.rs create mode 100755 scripts/measure_fts_index.py create mode 100755 scripts/redactor-differential.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index e3461adc..5f150348 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,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/crates/icx-codec/tests/redact_dev_harness.rs b/crates/icx-codec/tests/redact_dev_harness.rs new file mode 100644 index 00000000..5b153c68 --- /dev/null +++ b/crates/icx-codec/tests/redact_dev_harness.rs @@ -0,0 +1,206 @@ +// 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 and `aaaa-aaaa` for a UUID-shaped one. A `qqzz` 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 and not the other. +//! +//! ```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(' ', "␠") +} + +fn leaks(redacted: &str) -> bool { + redacted.contains("qqzz") || redacted.contains("aaaa-aaaa") +} + +fn env_flag(name: &str) -> bool { + std::env::var_os(name).is_some() +} + +#[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/testing-strategy.md b/docs/testing-strategy.md index 910a2523..8f9d81d0 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 00000000..0917504d --- /dev/null +++ b/scripts/measure_fts_index.py @@ -0,0 +1,126 @@ +#!/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). + +Reads a workspace's `icx.sqlite3` read-only, reassembles each artifact's text from its chunks, +and builds one throwaway FTS5 index per tokenizer configuration in an output directory, reporting +index size against the stored text and the insert time per artifact. It is the evidence step for +choosing a `grep_cold` index: nothing in the workspace is modified, and the indexes it writes +hold stored (already redacted) text, so keep the output directory private and delete it after. + +Usage: + python3 scripts/measure_fts_index.py ~/.local/state/icx/workspaces/ + python3 scripts/measure_fts_index.py path/to/icx.sqlite3 --out /tmp/fts --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", + "trigram": "tokenize='trigram'", + "trigram-detail-none": "tokenize='trigram', detail=none", +} + + +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"file:{db}?mode=ro", uri=True) + try: + chunks = dict(src.execute("SELECT id, bytes FROM chunks")) + texts = [] + for (meta,) in src.execute("SELECT meta FROM artifacts ORDER BY id"): + ids = json.loads(meta).get("chunk_ids", []) + missing = [c for c in ids if db_id(c) not in chunks] + if missing: + raise SystemExit( + f"artifact references {len(missing)} missing chunk(s); store damaged?" + ) + body = b"".join(chunks[db_id(c)] for c in ids) + texts.append(body.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 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 throwaway indexes (default: 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 + texts = load_texts(db) + total = sum(len(t.encode()) for t in texts) + if not texts: + print("the store holds no artifacts", file=sys.stderr) + return 2 + out = args.out or Path(tempfile.mkdtemp(prefix="icx-fts-")) + out.mkdir(parents=True, exist_ok=True) + + 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})" + ) + for name, options in CONFIGS.items(): + path = out / f"{name}.db" + r = build(texts, path, options) + 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)" + ) + if not args.keep: + path.unlink() + 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 00000000..a544902e --- /dev/null +++ b/scripts/redactor-differential.sh @@ -0,0 +1,76 @@ +#!/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 `qqzz` is a leak only after a sensitive key, so read new-leaks.txt by hand; it is a +# review aid, not a gate. The harness is copied into the base worktree when BASE_REF predates it. +# +# Environment: +# CARGO_WRAP command prefix for cargo, e.g. "agent-workstation resource --wait 1800 build --" +# CARGO_BUILD_JOBS is passed through as usual. +set -euo pipefail + +usage() { sed -n '6,13p' "$0" >&2; exit 2; } +cases="" n=200000 out="" base="main" +while [ $# -gt 0 ]; do + case "$1" in + --cases) cases=$(realpath "$2"); shift 2 ;; + --n) n=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + -h|--help) usage ;; + -*) usage ;; + *) base=$1; shift ;; + esac +done + +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"; } +trap cleanup EXIT +git -C "$repo" worktree add --detach --quiet "$wt" "$base" +[ -f "$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 + (cd "$tree" && env "$@" "${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 From 5315ae4755f41d8836105ffa6157814093490bd0 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Fri, 27 Nov 2026 22:28:48 -0500 Subject: [PATCH 3/6] fix(workspace): find the project root as git does (#120) 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. --- CHANGELOG.md | 4 + README.md | 2 +- crates/icx-adapters/src/workspace.rs | 88 +++++++++++++++++-- crates/icx-adapters/tests/workspace_trust.rs | 13 ++- crates/icx-adapters/tests/worktree_root.rs | 65 ++++++++++++++ crates/icx-cli/src/main.rs | 2 +- crates/icx-cli/tests/proxy_projects.rs | 8 ++ docs/architecture.md | 4 +- .../deployment-and-agent-integration-guide.md | 2 +- docs/interfaces.md | 2 +- docs/security-and-threat-model.md | 2 +- 11 files changed, 177 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f150348..5e0f82f6 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 diff --git a/README.md b/README.md index 9388e77a..f365ee78 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 070e0384..dd7e0e3a 100644 --- a/crates/icx-adapters/src/workspace.rs +++ b/crates/icx-adapters/src/workspace.rs @@ -112,15 +112,91 @@ 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, +} + +fn dot_git(dir: &Path) -> DotGit { + let dot_git = dir.join(".git"); + 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 = meta.len() <= 4096 + && std::fs::read_to_string(&dot_git).is_ok_and(|text| { + text.lines() + .next() + .and_then(|l| l.strip_prefix("gitdir:")) + .map(str::trim) + .is_some_and(|g| !g.is_empty() && 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 { + let head_ok = std::fs::read_to_string(gitdir.join("HEAD")).is_ok_and(|h| { + let h = h.trim_end(); + h.starts_with("ref: refs/") + || ((h.len() == 40 || h.len() == 64) && h.bytes().all(|b| b.is_ascii_hexdigit())) + }); + if !head_ok { + return false; + } + let common = match std::fs::read_to_string(gitdir.join("commondir")) { + Ok(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. diff --git a/crates/icx-adapters/tests/workspace_trust.rs b/crates/icx-adapters/tests/workspace_trust.rs index dcf98f18..ee7fc2cf 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 3213961f..6df8e84a 100644 --- a/crates/icx-adapters/tests/worktree_root.rs +++ b/crates/icx-adapters/tests/worktree_root.rs @@ -81,3 +81,68 @@ 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. +fn git_toplevel(cwd: &Path) -> Option { + let out = Command::new("git") + .current_dir(cwd) + .env( + "GIT_CEILING_DIRECTORIES", + cwd.ancestors().nth(3).unwrap_or(cwd), + ) + .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(&plain), None); + assert_eq!(project_root(&plain), plain); + + // 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"]); + std::fs::create_dir_all(mid.join(".git")).unwrap(); + assert_eq!(git_toplevel(&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(&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(&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(&deep), Some(mid.clone())); + assert_eq!(project_root(&deep), mid); + let _ = std::fs::remove_dir_all(&base); +} diff --git a/crates/icx-cli/src/main.rs b/crates/icx-cli/src/main.rs index 10ad1d83..66278d50 100644 --- a/crates/icx-cli/src/main.rs +++ b/crates/icx-cli/src/main.rs @@ -646,7 +646,7 @@ fn run_trust(args: &[String]) -> Result<(), String> { && canonical .ancestors() .skip(1) - .any(|p| p.join(".git").exists()) + .any(workspace::has_git_repository) { eprintln!( "icx trust: note: {} is inside a git work tree; anything committed there can be replaced by a pull. \ diff --git a/crates/icx-cli/tests/proxy_projects.rs b/crates/icx-cli/tests/proxy_projects.rs index c58904dc..93a2eef0 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/docs/architecture.md b/docs/architecture.md index 321b1e02..31f0f3c2 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 a14dc429..5e61a4b5 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 3706a8b7..4ea7860f 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -131,7 +131,7 @@ 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 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 3d41fa34..f431f924 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` | From 6ecf8119a584f501137a5f9316eeb171e3d12876 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Fri, 27 Nov 2026 22:34:31 -0500 Subject: [PATCH 4/6] fix(workspace): bounded, non-blocking reads of git control files 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. --- crates/icx-adapters/src/workspace.rs | 60 +++++++++++++++------- crates/icx-adapters/tests/worktree_root.rs | 36 +++++++++++++ 2 files changed, 77 insertions(+), 19 deletions(-) diff --git a/crates/icx-adapters/src/workspace.rs b/crates/icx-adapters/src/workspace.rs index dd7e0e3a..29d26667 100644 --- a/crates/icx-adapters/src/workspace.rs +++ b/crates/icx-adapters/src/workspace.rs @@ -151,8 +151,38 @@ enum DotGit { 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(); + file.take(MAX_CONTROL_FILE).read_to_string(&mut text).ok()?; + Some(text) +} + 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; }; @@ -166,14 +196,13 @@ fn dot_git(dir: &Path) -> DotGit { if !meta.is_file() { return DotGit::None; } - let names_repository = meta.len() <= 4096 - && std::fs::read_to_string(&dot_git).is_ok_and(|text| { - text.lines() - .next() - .and_then(|l| l.strip_prefix("gitdir:")) - .map(str::trim) - .is_some_and(|g| !g.is_empty() && is_git_directory(&dir.join(g))) - }); + let names_repository = read_control_file(&dot_git).is_some_and(|text| { + text.lines() + .next() + .and_then(|l| l.strip_prefix("gitdir:")) + .map(str::trim) + .is_some_and(|g| !g.is_empty() && is_git_directory(&dir.join(g))) + }); if names_repository { DotGit::Repository } else { @@ -184,7 +213,7 @@ fn dot_git(dir: &Path) -> DotGit { /// 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 { - let head_ok = std::fs::read_to_string(gitdir.join("HEAD")).is_ok_and(|h| { + let head_ok = read_control_file(&gitdir.join("HEAD")).is_some_and(|h| { let h = h.trim_end(); h.starts_with("ref: refs/") || ((h.len() == 40 || h.len() == 64) && h.bytes().all(|b| b.is_ascii_hexdigit())) @@ -192,8 +221,8 @@ fn is_git_directory(gitdir: &Path) -> bool { if !head_ok { return false; } - let common = match std::fs::read_to_string(gitdir.join("commondir")) { - Ok(rel) if !rel.trim().is_empty() => gitdir.join(rel.trim()), + let common = match read_control_file(&gitdir.join("commondir")) { + Some(rel) if !rel.trim().is_empty() => gitdir.join(rel.trim()), _ => gitdir.to_path_buf(), }; common.join("objects").is_dir() && common.join("refs").is_dir() @@ -211,14 +240,7 @@ fn worktree_main_root(root: &Path) -> Option { 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 = std::fs::canonicalize(root.join(gitdir)).ok()?; diff --git a/crates/icx-adapters/tests/worktree_root.rs b/crates/icx-adapters/tests/worktree_root.rs index 6df8e84a..04017ea8 100644 --- a/crates/icx-adapters/tests/worktree_root.rs +++ b/crates/icx-adapters/tests/worktree_root.rs @@ -146,3 +146,39 @@ fn a_git_directory_git_rejects_does_not_make_a_project_root() { assert_eq!(project_root(&deep), mid); let _ = std::fs::remove_dir_all(&base); } + +#[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"); + + 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); +} From 5580d1af6dbbd73e2f8b05b4c4c985de8b6dc8bc Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Fri, 27 Nov 2026 23:33:03 -0500 Subject: [PATCH 5/6] fix: review round on #119 (git parity, script hardening, coverage) 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. --- crates/icx-adapters/src/workspace.rs | 40 +++++---- crates/icx-adapters/tests/worktree_root.rs | 63 +++++++++++--- crates/icx-cli/src/main.rs | 66 ++++++++++---- crates/icx-codec/tests/redact_dev_harness.rs | 15 ++-- docs/interfaces.md | 1 + scripts/measure_fts_index.py | 90 +++++++++++++------- scripts/redactor-differential.sh | 21 +++-- 7 files changed, 206 insertions(+), 90 deletions(-) diff --git a/crates/icx-adapters/src/workspace.rs b/crates/icx-adapters/src/workspace.rs index 29d26667..66b616d0 100644 --- a/crates/icx-adapters/src/workspace.rs +++ b/crates/icx-adapters/src/workspace.rs @@ -176,8 +176,18 @@ fn read_control_file(path: &Path) -> Option { return None; } let mut text = String::new(); - file.take(MAX_CONTROL_FILE).read_to_string(&mut text).ok()?; - Some(text) + // 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: its whole content must be one `gitdir: ` line, as git's +/// `read_gitfile` requires (a second line would become part of the path and name nothing). +fn gitfile_target(text: &str) -> Option<&str> { + let path = text.trim_end().strip_prefix("gitdir:")?.trim(); + (!path.is_empty() && !path.contains('\n')).then_some(path) } fn dot_git(dir: &Path) -> DotGit { @@ -196,13 +206,8 @@ fn dot_git(dir: &Path) -> DotGit { if !meta.is_file() { return DotGit::None; } - let names_repository = read_control_file(&dot_git).is_some_and(|text| { - text.lines() - .next() - .and_then(|l| l.strip_prefix("gitdir:")) - .map(str::trim) - .is_some_and(|g| !g.is_empty() && is_git_directory(&dir.join(g))) - }); + 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 { @@ -213,10 +218,16 @@ fn dot_git(dir: &Path) -> DotGit { /// 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| { - let h = h.trim_end(); - h.starts_with("ref: refs/") - || ((h.len() == 40 || h.len() == 64) && h.bytes().all(|b| b.is_ascii_hexdigit())) + h.strip_prefix("ref:") + .is_some_and(|r| r.trim_start().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; @@ -237,12 +248,9 @@ fn is_git_directory(gitdir: &Path) -> bool { /// 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; - } 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/worktree_root.rs b/crates/icx-adapters/tests/worktree_root.rs index 04017ea8..3288cf43 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; @@ -82,14 +82,12 @@ fn worktrees_resolve_to_the_main_repository_and_forgeries_do_not() { let _ = std::fs::remove_dir_all(&base); } -/// git's own answer for `cwd`: the work tree top, or `None` outside any repository. -fn git_toplevel(cwd: &Path) -> Option { +/// 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", - cwd.ancestors().nth(3).unwrap_or(cwd), - ) + .env("GIT_CEILING_DIRECTORIES", base.parent().unwrap_or(base)) .args(["rev-parse", "--show-toplevel"]) .output() .unwrap(); @@ -107,8 +105,9 @@ fn a_git_directory_git_rejects_does_not_make_a_project_root() { 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(&plain), None); + 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. @@ -117,11 +116,12 @@ fn a_git_directory_git_rejects_does_not_make_a_project_root() { 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(&deep), Some(repo.clone())); + 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(&deep), Some(repo.clone())); + 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 @@ -133,7 +133,7 @@ fn a_git_directory_git_rejects_does_not_make_a_project_root() { format!("gitdir: {}\n", base.join("not-a-repo").display()), ) .unwrap(); - assert_eq!(git_toplevel(&deep), None); + 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. @@ -142,11 +142,37 @@ fn a_git_directory_git_rejects_does_not_make_a_project_root() { 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(&deep), Some(mid.clone())); + 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"); 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, @@ -171,6 +197,19 @@ fn planted_control_files_cannot_block_or_bloat_the_lookup() { .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"] { diff --git a/crates/icx-cli/src/main.rs b/crates/icx-cli/src/main.rs index 66278d50..f750523b 100644 --- a/crates/icx-cli/src/main.rs +++ b/crates/icx-cli/src/main.rs @@ -283,7 +283,10 @@ fn roots() -> &'static WorkspaceRoots { 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"), @@ -297,17 +300,17 @@ fn roots() -> &'static WorkspaceRoots { }) } -/// Removes `icx_cli_test_roots_` sandboxes whose process no longer exists. Linux only (it -/// checks `/proc/`); a live process's sandbox, including one whose PID was reused, is kept. -#[cfg(test)] +/// 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() { - if !Path::new("/proc/self").exists() { - return; - } - let Ok(entries) = fs::read_dir(env::temp_dir()) else { - return; - }; - for entry in entries.flatten() { + 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() @@ -316,7 +319,10 @@ fn remove_stale_test_roots() { else { continue; }; - if pid != std::process::id() && !Path::new(&format!("/proc/{pid}")).exists() { + 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()); } } @@ -642,12 +648,9 @@ 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(workspace::has_git_repository) - { + // The same answer `project_root` (and git) gives: inside a work tree whose top is above `dir`. + let root = workspace::project_root(&canonical); + if root != canonical && workspace::has_git_repository(&root) { 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.", @@ -4273,6 +4276,35 @@ mod tests { } } + #[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(); + let dead = env::temp_dir().join(format!("icx_cli_test_roots_{}", pid_max + 1)); + let dead_file = env::temp_dir().join(format!("icx_cli_test_roots_{}", pid_max + 2)); + let live = env::temp_dir().join(format!( + "icx_cli_test_roots_{}", + std::os::unix::process::parent_id() + )); + 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() { diff --git a/crates/icx-codec/tests/redact_dev_harness.rs b/crates/icx-codec/tests/redact_dev_harness.rs index 5b153c68..e0181261 100644 --- a/crates/icx-codec/tests/redact_dev_harness.rs +++ b/crates/icx-codec/tests/redact_dev_harness.rs @@ -6,9 +6,9 @@ //! 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 and `aaaa-aaaa` for a UUID-shaped one. A `qqzz` 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 and not the other. +//! `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 @@ -114,12 +114,17 @@ fn show(s: &str) -> String { .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 { - redacted.contains("qqzz") || redacted.contains("aaaa-aaaa") + ["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() + std::env::var_os(name).is_some_and(|v| !v.is_empty() && v != "0") } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index 4ea7860f..a91531c9 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -132,6 +132,7 @@ pub struct WorkspaceRoots { pub state_dir: PathBuf, pub config_dir: PathBuf, pub impl WorkspaceRoots { pub fn from_env() -> Self; } // absolute paths only; empty root => fail closed 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/scripts/measure_fts_index.py b/scripts/measure_fts_index.py index 0917504d..c66c64e0 100755 --- a/scripts/measure_fts_index.py +++ b/scripts/measure_fts_index.py @@ -3,15 +3,19 @@ # 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). -Reads a workspace's `icx.sqlite3` read-only, reassembles each artifact's text from its chunks, -and builds one throwaway FTS5 index per tokenizer configuration in an output directory, reporting -index size against the stored text and the insert time per artifact. It is the evidence step for -choosing a `grep_cold` index: nothing in the workspace is modified, and the indexes it writes -hold stored (already redacted) text, so keep the output directory private and delete it after. +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. Usage: python3 scripts/measure_fts_index.py ~/.local/state/icx/workspaces/ - python3 scripts/measure_fts_index.py path/to/icx.sqlite3 --out /tmp/fts --json results.json + python3 scripts/measure_fts_index.py path/to/icx.sqlite3 --json results.json """ from __future__ import annotations @@ -27,8 +31,10 @@ 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=''", } @@ -38,19 +44,21 @@ def db_id(chunk_id: int) -> int: def load_texts(db: Path) -> list[str]: - src = sqlite3.connect(f"file:{db}?mode=ro", uri=True) + src = sqlite3.connect(f"{db.resolve().as_uri()}?mode=ro", uri=True) try: - chunks = dict(src.execute("SELECT id, bytes FROM chunks")) texts = [] for (meta,) in src.execute("SELECT meta FROM artifacts ORDER BY id"): - ids = json.loads(meta).get("chunk_ids", []) - missing = [c for c in ids if db_id(c) not in chunks] - if missing: - raise SystemExit( - f"artifact references {len(missing)} missing chunk(s); store damaged?" - ) - body = b"".join(chunks[db_id(c)] for c in ids) - texts.append(body.decode("utf-8", "replace")) + 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() @@ -73,13 +81,32 @@ def build(texts: list[str], path: Path, options: str) -> dict: 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 throwaway indexes (default: temp)" + "--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") @@ -91,11 +118,9 @@ def main() -> int: return 2 texts = load_texts(db) total = sum(len(t.encode()) for t in texts) - if not texts: - print("the store holds no artifacts", file=sys.stderr) + if total == 0: + print("the store holds no text", file=sys.stderr) return 2 - out = args.out or Path(tempfile.mkdtemp(prefix="icx-fts-")) - out.mkdir(parents=True, exist_ok=True) results = { "artifacts": len(texts), @@ -105,18 +130,17 @@ def main() -> int: print( f"artifacts={len(texts)} text={total / 1e6:.1f} MB (SQLite {sqlite3.sqlite_version})" ) - for name, options in CONFIGS.items(): - path = out / f"{name}.db" - r = build(texts, path, options) - 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)" - ) - if not args.keep: - path.unlink() + if args.out: + args.out.mkdir(mode=0o700, parents=True, exist_ok=True) + args.out.chmod(0o700) + 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 diff --git a/scripts/redactor-differential.sh b/scripts/redactor-differential.sh index a544902e..5759d956 100755 --- a/scripts/redactor-differential.sh +++ b/scripts/redactor-differential.sh @@ -12,26 +12,30 @@ # 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 `qqzz` is a leak only after a sensitive key, so read new-leaks.txt by hand; it is a -# review aid, not a gate. The harness is copied into the base worktree when BASE_REF predates it. +# 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 --" # 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" +cases="" n=200000 out="" base="main" positional=0 while [ $# -gt 0 ]; do case "$1" in + --cases|--n|--out) [ $# -ge 2 ] || usage ;;& --cases) cases=$(realpath "$2"); shift 2 ;; --n) n=$2; shift 2 ;; --out) out=$2; shift 2 ;; -h|--help) usage ;; -*) usage ;; - *) base=$1; shift ;; + *) [ "$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 @@ -41,15 +45,18 @@ git -C "$repo" rev-parse --verify --quiet "$base^{commit}" > /dev/null \ 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"; } +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" -[ -f "$wt/$harness" ] || cp "$repo/$harness" "$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 - (cd "$tree" && env "$@" "${wrap[@]}" cargo test -q --release -p icx-codec \ + (cd "$tree" && env "$@" ${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; } } From 575564cade28e88de1174a46f95fa7649096e961 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Fri, 27 Nov 2026 23:43:28 -0500 Subject: [PATCH 6/6] fix: second review round on #119 (trust note, git parity, scripts) - 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. --- crates/icx-adapters/src/workspace.rs | 26 +++++----- crates/icx-adapters/tests/worktree_root.rs | 8 +++ crates/icx-cli/src/main.rs | 57 ++++++++++++++++++---- scripts/measure_fts_index.py | 19 ++++++-- scripts/redactor-differential.sh | 18 ++++--- 5 files changed, 98 insertions(+), 30 deletions(-) diff --git a/crates/icx-adapters/src/workspace.rs b/crates/icx-adapters/src/workspace.rs index 66b616d0..a925ee30 100644 --- a/crates/icx-adapters/src/workspace.rs +++ b/crates/icx-adapters/src/workspace.rs @@ -183,11 +183,14 @@ fn read_control_file(path: &Path) -> Option { (text.len() as u64 <= MAX_CONTROL_FILE).then_some(text) } -/// The path a `.git` file names: its whole content must be one `gitdir: ` line, as git's -/// `read_gitfile` requires (a second line would become part of the path and name nothing). +/// 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.trim_end().strip_prefix("gitdir:")?.trim(); - (!path.is_empty() && !path.contains('\n')).then_some(path) + 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 { @@ -221,13 +224,14 @@ 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().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) - }) + 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; diff --git a/crates/icx-adapters/tests/worktree_root.rs b/crates/icx-adapters/tests/worktree_root.rs index 3288cf43..7ad095a0 100644 --- a/crates/icx-adapters/tests/worktree_root.rs +++ b/crates/icx-adapters/tests/worktree_root.rs @@ -169,6 +169,14 @@ fn a_git_directory_git_rejects_does_not_make_a_project_root() { .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); } diff --git a/crates/icx-cli/src/main.rs b/crates/icx-cli/src/main.rs index f750523b..1dbd095a 100644 --- a/crates/icx-cli/src/main.rs +++ b/crates/icx-cli/src/main.rs @@ -328,6 +328,14 @@ fn remove_stale_test_roots() { } } +/// 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(); @@ -648,9 +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()); - // The same answer `project_root` (and git) gives: inside a work tree whose top is above `dir`. - let root = workspace::project_root(&canonical); - if root != canonical && workspace::has_git_repository(&root) { + 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.", @@ -4276,6 +4282,38 @@ 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() { @@ -4285,12 +4323,13 @@ mod tests { .trim() .parse() .unwrap(); - let dead = env::temp_dir().join(format!("icx_cli_test_roots_{}", pid_max + 1)); - let dead_file = env::temp_dir().join(format!("icx_cli_test_roots_{}", pid_max + 2)); - let live = env::temp_dir().join(format!( - "icx_cli_test_roots_{}", - std::os::unix::process::parent_id() - )); + // 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(); diff --git a/scripts/measure_fts_index.py b/scripts/measure_fts_index.py index c66c64e0..b4ea0323 100755 --- a/scripts/measure_fts_index.py +++ b/scripts/measure_fts_index.py @@ -11,7 +11,9 @@ (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. +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/ @@ -116,6 +118,17 @@ def main() -> int: 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: @@ -131,8 +144,8 @@ def main() -> int: f"artifacts={len(texts)} text={total / 1e6:.1f} MB (SQLite {sqlite3.sqlite_version})" ) if args.out: - args.out.mkdir(mode=0o700, parents=True, exist_ok=True) - args.out.chmod(0o700) + 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 diff --git a/scripts/redactor-differential.sh b/scripts/redactor-differential.sh index 5759d956..7a3e6f2f 100755 --- a/scripts/redactor-differential.sh +++ b/scripts/redactor-differential.sh @@ -18,6 +18,8 @@ # # 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 @@ -26,10 +28,9 @@ 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|--n|--out) [ $# -ge 2 ] || usage ;;& - --cases) cases=$(realpath "$2"); shift 2 ;; - --n) n=$2; shift 2 ;; - --out) out=$2; shift 2 ;; + --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 ;; @@ -46,17 +47,20 @@ 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 + 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 - (cd "$tree" && env "$@" ${wrap[@]+"${wrap[@]}"} cargo test -q --release -p icx-codec \ + 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; } }