From 1ba5f3c68257fbd0895435802fe8dd98b4fbace1 Mon Sep 17 00:00:00 2001 From: AI Date: Mon, 12 Oct 2026 01:39:31 -0700 Subject: [PATCH 1/2] tier2: per-worktree session baselines; one-call session-start snapshot Builders in linked worktrees of one git store (anton-go: TT-sales, TT-marketing, V2-D2S0, ...) were halted with E4 against another worktree's HEAD (75a4cfb, V2-D2S0), and two merged that unrelated branch to satisfy the gate (e799c02, 7e48b06). Cause: get_or_set_session_baseline keyed its git-ref layer by session only (refs/hardtruth/baseline/). Refs live in the git common dir shared by every linked worktree, and is_valid_commit only checks the shared object store, so a ref or cached SHA recorded in one worktree was returned as another's baseline. Hook payloads without a session id normalise to "unknown", so all such sessions shared one ref and one cache file (~/.hardtruth/halts/baseline_unknown_*.json held TT-marketing's 7e48b06). - Baseline ref is now per (session, worktree realpath): baseline_ref_name, used by get_or_set_session_baseline and check_manifest_tampering. The legacy shared name is never read. - The session cache file's single baseline is used only for the tree its workspace_path names (hook and tier2_runner). - No baseline is recorded or read for an id-less ("unknown"/"default") session. - E4 messages tell the agent not to merge, rebase or cherry-pick other branches to satisfy the check, and to report a wrong baseline. Also fixes the PR #3 session-start snapshot, which recorded 0 repos in all 67 production SessionStarts since install: the daemon resolves each new key by scanning its 113k-line ledger (~0.9s, serialized), so 2 registrations per repo never fit the budget. The snapshot is now a manifest {realpath: head, stash} in the halt dir whose sha256 is registered in ONE daemon call; Stop trusts it only if the digest matches. Linked worktrees of every discovered repo are included with their own HEAD. Live: 94 trees in 5.2s, TT-sales and V2-D2S0 each at their own HEAD. Co-Authored-By: Claude Opus 5.5 --- client/hardtruth_hook.py | 186 ++++++++++++------ daemon/tier2_runner.py | 37 +++- tests/test_tier2_out_of_workspace_roots.py | 212 +++++++++++++++++++-- 3 files changed, 356 insertions(+), 79 deletions(-) diff --git a/client/hardtruth_hook.py b/client/hardtruth_hook.py index daa92cd..903a30a 100755 --- a/client/hardtruth_hook.py +++ b/client/hardtruth_hook.py @@ -77,14 +77,25 @@ run_independent_verification = None try: - from daemon.tier2_runner import resolve_tier2_targets, git_toplevel_for_file, check_manifest_tampering + from daemon.tier2_runner import resolve_tier2_targets, git_toplevel_for_file, check_manifest_tampering, \ + baseline_ref_name, is_valid_conversation_id except ImportError: try: - from tier2_runner import resolve_tier2_targets, git_toplevel_for_file, check_manifest_tampering + from tier2_runner import resolve_tier2_targets, git_toplevel_for_file, check_manifest_tampering, \ + baseline_ref_name, is_valid_conversation_id except ImportError: try: - from hardtruth.tier2_runner import resolve_tier2_targets, git_toplevel_for_file, check_manifest_tampering + from hardtruth.tier2_runner import resolve_tier2_targets, git_toplevel_for_file, check_manifest_tampering, \ + baseline_ref_name, is_valid_conversation_id except ImportError: + def baseline_ref_name(conv_id, repo_root): + conv_hash = hashlib.sha256(str(conv_id).encode("utf-8")).hexdigest()[:16] + wt_hash = hashlib.sha256(os.path.realpath(repo_root).encode("utf-8")).hexdigest()[:12] + return f"refs/hardtruth/baseline/{conv_hash}-{wt_hash}" + + def is_valid_conversation_id(conv_id): + return bool(conv_id) and str(conv_id).strip().lower() not in {"", "unknown", "default", "none", "null"} + def resolve_tier2_targets(ws, mod=None, cid=None, baseline_lookup=None): r = resolve_target_project_dir(ws, mod, cid) return {"targets": [{"root": r, "outside": False, "repo_root": None, "baseline": None}] if r else [], @@ -631,12 +642,19 @@ def get_or_set_session_baseline(workspace_dir: str, conv_id: str) -> Optional[st Records and returns the git commit SHA at the start of the session. Enforces multi-layer baseline persistence: 1. Isolated Daemon (tamper-evident, survives local rm -rf ~/.hardtruth/halts) - 2. Git internal ref (refs/hardtruth/baseline/) - 3. Local cache file (~/.hardtruth/halts/baseline_*.json) + 2. Git internal ref, one per (session, worktree) -- see baseline_ref_name + 3. Local cache file (~/.hardtruth/halts/baseline_*.json), only for the tree it records Defeats the 'commit & run' and baseline reset exploits completely. + + Every layer is keyed by the working tree itself: linked worktrees share one object store + and one refs namespace, so a commit or ref from a sibling worktree passes is_valid_commit + and must never be returned as this tree's baseline. Sessions without an id get no + baseline at all rather than one shared with every other id-less session. """ if not workspace_dir or not os.path.exists(os.path.join(workspace_dir, ".git")): return None + if not is_valid_conversation_id(conv_id): + return None safe_slug = re.sub(r"[^a-zA-Z0-9_-]", "_", str(conv_id))[:32] ws_norm = os.path.abspath(workspace_dir) @@ -675,10 +693,10 @@ def get_or_set_session_baseline(workspace_dir: str, conv_id: str) -> Optional[st except Exception: pass - # 2. Check local git ref (refs/hardtruth/baseline/) + # 2. Check this worktree's git ref (see baseline_ref_name) try: ref_proc = subprocess.run( - ["git", "rev-parse", f"refs/hardtruth/baseline/{conv_hash}"], + ["git", "rev-parse", "--verify", "-q", baseline_ref_name(conv_id, workspace_dir)], cwd=workspace_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, @@ -720,7 +738,9 @@ def get_or_set_session_baseline(workspace_dir: str, conv_id: str) -> Optional[st with open(baseline_file, "r") as f: data = json.load(f) cached_sha = data.get("baseline_sha") - if cached_sha and is_valid_commit(cached_sha, workspace_dir): + cached_ws = data.get("workspace_path") + same_tree = bool(cached_ws) and os.path.realpath(cached_ws) == os.path.realpath(workspace_dir) + if cached_sha and same_tree and is_valid_commit(cached_sha, workspace_dir): call_system_one("v1/session/baseline", { "conversationId": conv_id, "workspace_path": ws_norm, @@ -762,7 +782,7 @@ def get_or_set_session_baseline(workspace_dir: str, conv_id: str) -> Optional[st # Store in git ref try: subprocess.run( - ["git", "update-ref", f"refs/hardtruth/baseline/{conv_hash}", sha], + ["git", "update-ref", baseline_ref_name(conv_id, workspace_dir), sha, ""], cwd=workspace_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, @@ -815,8 +835,7 @@ def get_or_set_session_baseline(workspace_dir: str, conv_id: str) -> Optional[st # workspace without such a snapshot fails closed. # --------------------------------------------------------------------------- -SESSION_START_HEAD_NS = "/__hardtruth_session_start_head__" -SESSION_START_STASH_NS = "/__hardtruth_session_start_stash__" +SESSION_SNAPSHOT_NS = "/__hardtruth_session_snapshot__" DEFAULT_BASELINE_ROOTS = ("~/dev", "~/workspace", "~/code", "~/src", "~/projects", "~/repos") @@ -849,26 +868,59 @@ def get_baseline_roots() -> List[str]: return out -def snapshot_repos_at_session_start(conv_id: str, cwd: str, time_budget_sec: float = 5.0, max_repos: int = 200) -> int: - """Registers HEAD and refs/stash of every candidate repository in the daemon under the - session-start namespace, session directory first. Returns the number of repositories - snapshotted by the deadline. Registrations not started by then are cancelled, so the hook - outlives the budget by at most one in-flight call (1.5s timeout) and stays inside the - SessionStart hook timeout; a repository left without a snapshot fails closed at Stop. - Values are read before the agent's first tool call, so an in-flight registration that - lands after the deadline still records the session-start state.""" - import concurrent.futures +def _linked_worktrees(repo: str) -> List[str]: + """Top-levels of every working tree of repo's repository (main checkout and linked + worktrees), each of which has its own HEAD.""" + rc, out = _git_out(repo, ["worktree", "list", "--porcelain"], timeout=1.0) + if rc != 0: + return [] + return [line[len("worktree "):].strip() for line in out.splitlines() if line.startswith("worktree ")] + + +def session_snapshot_file(conv_id: str) -> str: + conv_hash = hashlib.sha256(str(conv_id).encode("utf-8")).hexdigest()[:16] + return os.path.join(get_halt_counter_dir(), f"session_snapshot_{conv_hash}.json") + + +def _snapshot_bytes(repos: Dict[str, Dict[str, str]]) -> bytes: + return json.dumps({"repos": repos}, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def snapshot_repos_at_session_start(conv_id: str, cwd: str, time_budget_sec: float = 5.0, max_repos: int = 300) -> int: + """ + Records HEAD and refs/stash of every candidate working tree -- the session directory, + its child repositories, repositories directly under HARDTRUTH_BASELINE_ROOTS, and every + linked worktree of each of those -- keyed by each tree's own realpath top-level. + + The manifest is written to the halt dir (agent-writable) and its sha256 is registered + in the daemon in ONE call (first write wins), so the cost does not grow with the number + of repositories: the daemon resolves each new key by scanning its whole ledger, which + made one registration per repository time out in practice. At Stop the manifest is + trusted only if its digest matches the daemon's value. Returns the number of working + trees recorded, or 0 if the digest could not be registered. + """ + if not is_valid_conversation_id(conv_id): + return 0 deadline = time.time() + time_budget_sec seen: Set[str] = set() candidates: List[str] = [] + + def _add(path: str) -> None: + top = os.path.realpath(path) + if top not in seen and os.path.isdir(top): + seen.add(top) + candidates.append(top) + for base in [cwd] + get_baseline_roots(): for repo in _discover_relevant_git_repos(base, max_repos=max_repos, time_budget_sec=time_budget_sec / 3): - top = os.path.realpath(repo) - if top not in seen: - seen.add(top) - candidates.append(top) + _add(repo) + for repo in list(candidates): + if time.time() > deadline or len(candidates) >= max_repos: + break + for wt in _linked_worktrees(repo): + _add(wt) - states: List[Tuple[str, str, str]] = [] + repos: Dict[str, Dict[str, str]] = {} for top in candidates[:max_repos]: if time.time() > deadline: break @@ -877,43 +929,67 @@ def snapshot_repos_at_session_start(conv_id: str, cwd: str, time_budget_sec: flo if rc != 0 or not head: continue # no commits yet: nothing to anchor, edits there fail closed rc, stash = _git_out(top, ["rev-parse", "-q", "--verify", "refs/stash"], timeout=1.0) - states.append((top, head, stash.strip() if rc == 0 and stash.strip() else "none")) - - def _register(state: Tuple[str, str, str]) -> bool: - top, head, stash = state - r1 = call_system_one("v1/session/baseline", { - "conversationId": conv_id, "workspace_path": SESSION_START_HEAD_NS + top, "commit_sha": head - }, timeout=1.5) - r2 = call_system_one("v1/session/baseline", { - "conversationId": conv_id, "workspace_path": SESSION_START_STASH_NS + top, "commit_sha": stash - }, timeout=1.5) - return bool(r1 and r2) - - if not states: + repos[top] = {"head": head, "stash": stash.strip() if rc == 0 and stash.strip() else "none"} + + body = _snapshot_bytes(repos) + digest = hashlib.sha256(body).hexdigest() + try: + path = session_snapshot_file(conv_id) + os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) + if not os.path.exists(path): + with open(path, "wb") as f: + f.write(body) + except Exception: + return 0 + resp = call_system_one("v1/session/baseline", { + "conversationId": conv_id, "workspace_path": SESSION_SNAPSHOT_NS, "commit_sha": digest + }, timeout=max(1.0, deadline - time.time() + 2.0)) + if not resp or resp.get("baseline_sha") != digest: return 0 - pool = concurrent.futures.ThreadPoolExecutor(max_workers=min(16, len(states))) - futures = [pool.submit(_register, st) for st in states] - done, _ = concurrent.futures.wait(futures, timeout=max(0.5, deadline - time.time())) - pool.shutdown(wait=False, cancel_futures=True) - return sum(1 for f in done if not f.exception() and f.result()) + return len(repos) -def _session_start_value(ns: str, repo_root: str, conv_id: str) -> Optional[str]: +_snapshot_cache: Dict[str, Optional[Dict[str, Dict[str, str]]]] = {} + + +def load_trusted_session_snapshot(conv_id: str) -> Optional[Dict[str, Dict[str, str]]]: + """The session-start snapshot {realpath: {"head", "stash"}}, or None unless the manifest + on disk hashes to the digest the daemon recorded at session start.""" + if not is_valid_conversation_id(conv_id): + return None + if conv_id in _snapshot_cache: + return _snapshot_cache[conv_id] + result = None try: resp = call_system_one("v1/session/baseline", { - "conversationId": conv_id, "workspace_path": ns + os.path.realpath(repo_root) - }, timeout=1.0) - return (resp or {}).get("baseline_sha") or None + "conversationId": conv_id, "workspace_path": SESSION_SNAPSHOT_NS + }, timeout=5.0) + digest = (resp or {}).get("baseline_sha") + if digest: + with open(session_snapshot_file(conv_id), "rb") as f: + body = f.read() + if hashlib.sha256(body).hexdigest() == digest: + result = json.loads(body.decode("utf-8")).get("repos") or {} except Exception: + result = None + if result is not None: + _snapshot_cache[conv_id] = result + return result + + +def _session_start_entry(repo_root: str, conv_id: str) -> Optional[Dict[str, str]]: + snap = load_trusted_session_snapshot(conv_id) + if not snap or not repo_root: return None + return snap.get(os.path.realpath(repo_root)) def trusted_repo_baseline(repo_root: str, conv_id: str) -> Optional[str]: - """HEAD of repo_root as snapshotted in the daemon at session start, or None. Never - records anything and never consults agent-writable stores.""" - if not repo_root or not conv_id: - return None - sha = _session_start_value(SESSION_START_HEAD_NS, repo_root, conv_id) + """HEAD of repo_root's own working tree at session start, from the daemon-anchored + snapshot, or None. Never records anything and never consults agent-writable stores + except the manifest whose digest the daemon holds.""" + entry = _session_start_entry(repo_root, conv_id) + sha = (entry or {}).get("head") if sha and is_valid_commit(sha, repo_root): return sha return None @@ -959,9 +1035,9 @@ def check_outside_repo_integrity(target: Dict[str, Any], conv_id: str) -> Option rc, _ = _git_out(repo_root, ["merge-base", "--is-ancestor", baseline, "HEAD"], timeout=5.0) if rc != 0: return (f"🚨 HARDTRUTH GATE HALTED (EVASION E4 DETECTED): HEAD of {repo_root} is not a descendant of " - f"session baseline commit {baseline[:10]}. Branch switching or history rewrites to hide changes are forbidden.") + f"session baseline commit {baseline[:10]}. Branch switching or history rewrites to hide changes are forbidden. Do not merge, rebase or cherry-pick other branches to satisfy this check; if the baseline commit is not one this branch should descend from (for example another worktree's or branch's HEAD), stop and report it to the operator.") - start_stash = _session_start_value(SESSION_START_STASH_NS, repo_root, conv_id) + start_stash = (_session_start_entry(repo_root, conv_id) or {}).get("stash") if not start_stash: return f"🚨 HARDTRUTH UNDETERMINED: no session-start stash snapshot for {repo_root}. HardTruth fails closed." rc, stash = _git_out(repo_root, ["rev-parse", "-q", "--verify", "refs/stash"], timeout=1.0) @@ -2749,7 +2825,7 @@ def fail_halt(reason: str, remediable: bool = True) -> dict: timeout=5.0 ) if anc_res.returncode != 0: - return fail_halt(f"🚨 HARDTRUTH GATE HALTED (EVASION E4 DETECTED): Current HEAD is not a descendant of session baseline commit {baseline_sha[:10]}. Branch switching or history rewrites to hide changes are forbidden.") + return fail_halt(f"🚨 HARDTRUTH GATE HALTED (EVASION E4 DETECTED): Current HEAD is not a descendant of session baseline commit {baseline_sha[:10]}. Branch switching or history rewrites to hide changes are forbidden. Do not merge, rebase or cherry-pick other branches to satisfy this check; if the baseline commit is not one this branch should descend from (for example another worktree's or branch's HEAD), stop and report it to the operator.") except subprocess.TimeoutExpired: return fail_halt("🚨 HARDTRUTH UNDETERMINED: Git merge-base lineage check timed out. HardTruth fails closed.", remediable=False) except Exception as e: diff --git a/daemon/tier2_runner.py b/daemon/tier2_runner.py index 44ce3b9..eab1ae4 100644 --- a/daemon/tier2_runner.py +++ b/daemon/tier2_runner.py @@ -146,6 +146,30 @@ def _manifest_patterns_for(repo_root: str, workspace_path: str) -> List[str]: return patterns +INVALID_CONVERSATION_IDS = {"", "unknown", "default", "none", "null"} + + +def is_valid_conversation_id(conv_id: Optional[str]) -> bool: + """A hook payload without a session id is normalised to "unknown"; every such + invocation would share one baseline key, ref and cache file, so baselines are never + recorded or read for it.""" + return bool(conv_id) and str(conv_id).strip().lower() not in INVALID_CONVERSATION_IDS + + +def baseline_ref_name(conv_id: str, repo_root: str) -> str: + """Git ref holding the session baseline for one working tree. Refs live in the git + common dir, which every linked worktree of a repository shares, so the name carries the + worktree's own top-level as well as the session; a ref recorded in one worktree is never + read as the baseline of another.""" + conv_hash = hashlib.sha256(str(conv_id).encode("utf-8")).hexdigest()[:16] + wt_hash = hashlib.sha256(os.path.realpath(repo_root).encode("utf-8")).hexdigest()[:12] + return f"refs/hardtruth/baseline/{conv_hash}-{wt_hash}" + + +def _same_path(a: Optional[str], b: Optional[str]) -> bool: + return bool(a) and bool(b) and os.path.realpath(a) == os.path.realpath(b) + + def check_manifest_tampering( workspace_path: str, conv_id: Optional[str] = None, @@ -198,7 +222,7 @@ def check_manifest_tampering( return True, [f""] # 2. Check committed modifications against session baseline commit - if not baseline_sha and conv_id: + if not baseline_sha and is_valid_conversation_id(conv_id): safe_slug = re.sub(r"[^a-zA-Z0-9_-]", "_", str(conv_id))[:32] conv_hash = hashlib.sha256(str(conv_id).encode("utf-8")).hexdigest()[:16] @@ -216,11 +240,11 @@ def check_manifest_tampering( except Exception: pass - # Check git ref refs/hardtruth/baseline/ + # Check this worktree's git ref (see baseline_ref_name) if not baseline_sha: try: proc_ref = subprocess.run( - git_base + ["rev-parse", f"refs/hardtruth/baseline/{conv_hash}"], + git_base + ["rev-parse", "--verify", "-q", baseline_ref_name(conv_id, repo_root)], cwd=repo_root, env=env, stdout=subprocess.PIPE, @@ -240,7 +264,12 @@ def check_manifest_tampering( if os.path.exists(baseline_file): try: with open(baseline_file, "r") as f: - baseline_sha = json.load(f).get("baseline_sha") + cached = json.load(f) + # The session file holds ONE baseline; use it only for the tree it was + # recorded for (any commit of a shared object store would pass cat-file). + if _same_path(cached.get("workspace_path"), repo_root) or \ + _same_path(cached.get("workspace_path"), workspace_path): + baseline_sha = cached.get("baseline_sha") except Exception: pass diff --git a/tests/test_tier2_out_of_workspace_roots.py b/tests/test_tier2_out_of_workspace_roots.py index f08ed2f..8bf1da4 100644 --- a/tests/test_tier2_out_of_workspace_roots.py +++ b/tests/test_tier2_out_of_workspace_roots.py @@ -543,30 +543,56 @@ def test_daemon_unreachable_at_stop_halts(self): self.assertNotEqual(res.get("decision"), "allow", res) self.assertEqual(self.handed_off, []) - def test_snapshot_budget_cancels_queued_registrations(self): - """With a stalling daemon, registrations not started by the deadline are cancelled - (the SessionStart hook has a 10s timeout), and repos left without a snapshot fail - closed rather than being trusted.""" - repos = [self._repo(f"r{i}") for i in range(20)] # more than the 16 workers + def test_snapshot_is_one_daemon_call_regardless_of_repo_count(self): + """The daemon resolves each new key by scanning its whole ledger (~0.9s on this host), + so one registration per repository never fit the SessionStart budget. The snapshot + registers a single manifest digest.""" + for i in range(12): + self._repo(f"r{i}") calls = [] - def slow(endpoint, data, timeout=None): - time.sleep(0.6) - calls.append(data["workspace_path"]) + def counting(endpoint, data, timeout=None): + calls.append(endpoint) return self._fake_call(endpoint, data, timeout) - with mock.patch.object(hardtruth_hook, "call_system_one", side_effect=slow): - t0 = time.time() - n = hardtruth_hook.snapshot_repos_at_session_start(self.conv, self.workspace, time_budget_sec=1.0) - elapsed = time.time() - t0 - time.sleep(1.0) # let in-flight calls finish; cancelled ones must never run - self.assertLess(elapsed, 2.0) - self.assertLess(n, len(repos)) - self.assertLess(len(calls), 2 * len(repos)) - missing = [r for r in repos if (self.conv, hardtruth_hook.SESSION_START_HEAD_NS + r) not in self.daemon] - self.assertTrue(missing) - _write(os.path.join(missing[0], "app.py"), "def f():\n return 2\n") - res = self._stop([os.path.join(missing[0], "app.py")]) + with mock.patch.object(hardtruth_hook, "call_system_one", side_effect=counting): + n = hardtruth_hook.snapshot_repos_at_session_start(self.conv, self.workspace) + self.assertEqual(n, 12) + self.assertEqual(calls, ["v1/session/baseline"]) + + def test_daemon_down_at_session_start_fails_closed(self): + repo = self._repo("r") + self.daemon_up = False + self._session_start() + self.daemon_up = True + _write(os.path.join(repo, "app.py"), "def f():\n return 2\n") + res = self._stop([os.path.join(repo, "app.py")]) + self.assertIn("no session-start snapshot", res.get("reason", "")) + self.assertEqual(self.handed_off, []) + + def test_edited_snapshot_manifest_is_not_trusted(self): + """The manifest lives in the agent-writable halt dir; rewriting it to bless a tampered + HEAD breaks its digest, and the repository fails closed.""" + repo = self._repo("r") + self._session_start() + tampered = self._tamper_conftest(repo) + path = hardtruth_hook.session_snapshot_file(self.conv) + with open(path) as f: + snap = json.load(f) + snap["repos"][repo]["head"] = tampered + with open(path, "w") as f: + json.dump(snap, f) + _write(os.path.join(repo, "app.py"), "def f():\n return 'broken'\n") + res = self._stop([os.path.join(repo, "app.py")]) + self.assertIn("no session-start snapshot", res.get("reason", "")) + self.assertEqual(self.handed_off, []) + + def test_deleted_snapshot_manifest_fails_closed(self): + repo = self._repo("r") + self._session_start() + os.remove(hardtruth_hook.session_snapshot_file(self.conv)) + _write(os.path.join(repo, "app.py"), "def f():\n return 2\n") + res = self._stop([os.path.join(repo, "app.py")]) self.assertIn("no session-start snapshot", res.get("reason", "")) def test_outside_repo_invisible_to_verifier_halts(self): @@ -580,6 +606,152 @@ def test_outside_repo_invisible_to_verifier_halts(self): self.assertIn("could not see", res.get("reason", "")) +class TestLinkedWorktreeBaselines(unittest.TestCase): + """One git store, several linked worktrees on different branches (the 2026-10-12 + builders): no worktree may be held to another worktree's HEAD.""" + + def setUp(self): + self.test_dir = _real(tempfile.mkdtemp(prefix="hardtruth-wt-")) + self.halt_dir = os.path.join(self.test_dir, "halts") + os.makedirs(self.halt_dir, mode=0o700) + self._env = { + "HARDTRUTH_HALT_DIR": self.halt_dir, + "HARDTRUTH_API_KEY": os.path.join(self.test_dir, "no-such-key"), + "HARDTRUTH_URL": "http://127.0.0.1:9", + "HARDTRUTH_BASELINE_ROOTS": "", + } + self._old = {k: os.environ.get(k) for k in list(self._env) + ["HARDTRUTH_SKIP_TIER2", "HARDTRUTH_LEDGER_PATH"]} + os.environ.update(self._env) + os.environ["HARDTRUTH_SKIP_TIER2"] = "1" + os.environ.pop("HARDTRUTH_LEDGER_PATH", None) + self.conv = f"wt-{uuid.uuid4().hex}" + self.daemon = {} + self.daemon_up = False + + self.main = os.path.join(self.test_dir, "anton-go") + _git_init(self.main) + _write(os.path.join(self.main, "pytest.ini"), "[pytest]\n") + _write(os.path.join(self.main, "tests", "test_app.py"), TEST_BODY) + _write(os.path.join(self.main, "app.py"), "def f():\n return 1\n") + self.root_commit = _commit(self.main) + self.wt = {} + for name in ("TT-sales", "V2-D2S0"): + path = os.path.join(self.test_dir, "worktrees", name) + subprocess.run(["git", "worktree", "add", "-q", "-b", f"build/{name}", path], cwd=self.main, check=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + _write(os.path.join(path, f"{name}.py"), f"NAME = {name!r}\n") + self.wt[name] = (_real(path), _commit(path, name)) + + def tearDown(self): + for k, v in self._old.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + shutil.rmtree(self.test_dir, ignore_errors=True) + + def _fake_call(self, endpoint, data, timeout=None): + if not self.daemon_up: + return None + if endpoint == "v1/session/baseline": + key = (data["conversationId"], data["workspace_path"]) + if key not in self.daemon and data.get("commit_sha"): + self.daemon[key] = data["commit_sha"] + return {"baseline_sha": self.daemon.get(key)} + return None + + def _baseline(self, path, conv=None): + with mock.patch.object(hardtruth_hook, "call_system_one", side_effect=self._fake_call): + return hardtruth_hook.get_or_set_session_baseline(path, conv or self.conv) + + def test_each_worktree_gets_its_own_head_via_the_ref_layer(self): + """Daemon down: the ref layer is what persists. Refs are shared by linked worktrees, + so before the fix the second worktree read the first one's ref.""" + sales, sales_head = self.wt["TT-sales"] + v2, v2_head = self.wt["V2-D2S0"] + self.assertEqual(self._baseline(v2), v2_head) + self.assertEqual(self._baseline(sales), sales_head) + self.assertEqual(self._baseline(v2), v2_head) # stable on re-read + + def test_session_cache_file_is_not_reused_for_another_worktree(self): + sales, sales_head = self.wt["TT-sales"] + v2, v2_head = self.wt["V2-D2S0"] + with open(hardtruth_hook.get_session_start_baseline_file(self.conv), "w") as f: + json.dump({"baseline_sha": v2_head, "workspace_path": v2}, f) + self.assertEqual(self._baseline(sales), sales_head) + + def test_legacy_shared_ref_is_ignored(self): + """refs/hardtruth/baseline/ (pre-fix name) pointing at a sibling's HEAD.""" + sales, sales_head = self.wt["TT-sales"] + _, v2_head = self.wt["V2-D2S0"] + conv_hash = hashlib.sha256(self.conv.encode("utf-8")).hexdigest()[:16] + subprocess.run(["git", "update-ref", f"refs/hardtruth/baseline/{conv_hash}", v2_head], cwd=self.main, check=True) + self.assertEqual(self._baseline(sales), sales_head) + + def test_sessions_without_an_id_get_no_baseline(self): + sales, _ = self.wt["TT-sales"] + v2, _ = self.wt["V2-D2S0"] + self.assertIsNone(self._baseline(v2, conv="unknown")) + self.assertIsNone(self._baseline(sales, conv="unknown")) + refs = subprocess.run(["git", "for-each-ref", "refs/hardtruth"], cwd=self.main, stdout=subprocess.PIPE, text=True).stdout + self.assertEqual(refs.strip(), "") + + def test_tamper_check_does_not_use_a_sibling_worktree_baseline(self): + """check_manifest_tampering must not diff one worktree against another's baseline: + a legacy shared ref at the root commit would flag TT-sales' own committed history.""" + sales, _ = self.wt["TT-sales"] + _write(os.path.join(sales, "pytest.ini"), "[pytest]\naddopts = -q\n") + _commit(sales, "pre-session pytest.ini change on this branch") + conv_hash = hashlib.sha256(self.conv.encode("utf-8")).hexdigest()[:16] + subprocess.run(["git", "update-ref", f"refs/hardtruth/baseline/{conv_hash}", self.root_commit], cwd=self.main, check=True) + self.assertEqual(check_manifest_tampering(sales, conv_id=self.conv), (False, [])) + + def test_stop_in_one_worktree_is_not_held_to_a_sibling_head(self): + """End to end: a session that touched V2-D2S0 first and then stops in TT-sales is not + halted with E4 against V2-D2S0's HEAD.""" + sales, _ = self.wt["TT-sales"] + v2, _ = self.wt["V2-D2S0"] + self._baseline(v2) + res = self._stop(sales) + self.assertNotIn("EVASION E4", res.get("reason", ""), res) + + def test_e4_message_tells_agents_not_to_merge_other_branches(self): + sales, _ = self.wt["TT-sales"] + _, v2_head = self.wt["V2-D2S0"] + subprocess.run(["git", "update-ref", hardtruth_hook.baseline_ref_name(self.conv, sales), v2_head], cwd=sales, check=True) + res = self._stop(sales) + self.assertIn("EVASION E4", res.get("reason", "")) + self.assertIn("Do not merge", res.get("reason", "")) + + def test_snapshot_records_every_linked_worktree_with_its_own_head(self): + """A session started in the main checkout snapshots each linked worktree's HEAD.""" + self.daemon_up = True + with mock.patch.object(hardtruth_hook, "call_system_one", side_effect=self._fake_call): + hardtruth_hook.handle_session_start({"conversationId": self.conv, "cwd": self.main, "source": "startup"}) + for name, (path, head) in self.wt.items(): + self.assertEqual(hardtruth_hook.trusted_repo_baseline(path, self.conv), head, name) + + def _stop(self, workspace): + transcript = os.path.join(self.test_dir, "t.jsonl") + with open(transcript, "w") as f: + f.write(json.dumps({"type": "assistant", "message": {"role": "assistant", + "content": [{"type": "text", "text": "Done."}]}}) + "\n") + premise = { + "tampered": False, "conversationId": self.conv, "premise": "MODIFIED FILES: x.py.", + "source_files_modified": 1, "doc_files_modified": 0, + "modified_file_paths": [os.path.join(workspace, "TT-sales.py")], + "verification_commands_executed": 1, "test_commands_executed": 1, + "last_source_mod_step": 1, "last_test_step": 2, "unresolved_failures": [], + } + payload = {"conversationId": self.conv, "transcriptPath": transcript, "cwd": workspace, + "workspace_path": workspace, "executionNum": 1} + with mock.patch.object(hardtruth_hook, "HARNESS", "claude_code"), \ + mock.patch.object(hardtruth_hook, "get_local_ledger", return_value=_FakeLedger(premise)), \ + mock.patch.object(hardtruth_hook, "get_git_modified_source_files", return_value=([], [], [])), \ + mock.patch.object(hardtruth_hook, "call_system_one", side_effect=self._fake_call): + return hardtruth_hook.handle_stop(payload) + + class _FakeLedger: def __init__(self, premise): self._premise = premise From 6f90a0696d2f574fe86d0e89c7e4cb9d99f51941 Mon Sep 17 00:00:00 2001 From: AI Date: Mon, 12 Oct 2026 01:48:35 -0700 Subject: [PATCH 2/2] stop: fail closed for sessions without a session id An id-less Stop (conversationId "unknown"/"default", e.g. Antigravity `agy -p`, whose hook payload carries no session_id) gets no session-scoped baseline, so the Phase 5 lineage and stash checks were skipped and the Stop was allowed: a fail-open path. It now halts (non-remediable) with: "this session has no session id; HardTruth cannot verify lineage ... Ask the operator; do NOT merge, rebase or cherry-pick to work around this." Tests: direct ("unknown", "default", "") and through normalize_payload; both return allow without the change. Co-Authored-By: Claude Opus 5.5 --- client/hardtruth_hook.py | 11 +++++++++++ tests/test_tier2_out_of_workspace_roots.py | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/client/hardtruth_hook.py b/client/hardtruth_hook.py index 903a30a..9a7c575 100755 --- a/client/hardtruth_hook.py +++ b/client/hardtruth_hook.py @@ -2502,6 +2502,17 @@ def fail_halt(reason: str, remediable: bool = True) -> dict: if _IMPORT_DEGRADED: return fail_halt(f"🚨 HARDTRUTH INTEGRITY ERROR: {_IMPORT_DEGRADED}. Install layout degraded, cannot verify truth safely. HardTruth fails closed.", remediable=False) + # Without a session id there is no session-scoped baseline (see get_or_set_session_baseline) + # and every id-less call would share one ledger premise, so lineage, stash and tamper checks + # cannot run against this session's own history. Skipping them would fail open. + if not is_valid_conversation_id(conv_id): + return fail_halt( + "🚨 HARDTRUTH UNDETERMINED: this session has no session id; HardTruth cannot verify lineage " + "(the hook payload carried no session_id). Ask the operator; do NOT merge, rebase or " + "cherry-pick to work around this.", + remediable=False + ) + # Phase 1: Extract agent's final text from transcript (fail closed on unreadable or empty transcript) p1_wall = time.perf_counter() p1_cpu = time.process_time() diff --git a/tests/test_tier2_out_of_workspace_roots.py b/tests/test_tier2_out_of_workspace_roots.py index 8bf1da4..b33be6f 100644 --- a/tests/test_tier2_out_of_workspace_roots.py +++ b/tests/test_tier2_out_of_workspace_roots.py @@ -723,6 +723,28 @@ def test_e4_message_tells_agents_not_to_merge_other_branches(self): self.assertIn("EVASION E4", res.get("reason", "")) self.assertIn("Do not merge", res.get("reason", "")) + def test_stop_without_a_session_id_fails_closed(self): + """An id-less Stop (e.g. Antigravity `agy -p`, whose hook payload has no session_id) + cannot have its lineage verified; it halts instead of skipping the checks.""" + sales, _ = self.wt["TT-sales"] + for conv in ("unknown", "default", ""): + self.conv = conv + res = self._stop(sales) + self.assertEqual(res.get("decision"), "block", (conv, res)) + self.assertIn("no session id", res.get("reason", ""), conv) + self.assertIn("do NOT merge, rebase or cherry-pick", res.get("reason", ""), conv) + + def test_stop_without_a_session_id_through_the_cli_payload_fails_closed(self): + """The real entry point: normalize_payload turns a payload with no session_id into + conversationId "unknown".""" + sales, _ = self.wt["TT-sales"] + payload = hardtruth_hook.normalize_payload({"cwd": sales, "hook_event_name": "Stop"}) + self.assertEqual(payload.get("conversationId"), "unknown") + with mock.patch.object(hardtruth_hook, "HARNESS", "claude_code"), \ + mock.patch.object(hardtruth_hook, "call_system_one", side_effect=self._fake_call): + res = hardtruth_hook.handle_stop(payload) + self.assertIn("no session id", res.get("reason", ""), res) + def test_snapshot_records_every_linked_worktree_with_its_own_head(self): """A session started in the main checkout snapshots each linked worktree's HEAD.""" self.daemon_up = True