diff --git a/CLAUDE.md b/CLAUDE.md index 0d69afb..795545f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -106,6 +106,77 @@ requirements fixed the rest of the design: window are the turn's. Changes between turns are not, provided the prompt hook ran. +**`install` is user-wide by default, and a turn is recorded once.** Three +scopes (`agent::Scope`): the user's own hooks file (the default; Claude Code's +`settings.json` under `claude.config_dir`, Codex's `$CODEX_HOME/hooks.json`), +`--local` (this project on this machine: `.claude/settings.local.json`) and +`--project` (the committed `.claude/settings.json`, the old default, kept +because it is the only way to make recording travel with a repository to +teammates). Codex has no uncommitted project file, so its `--local` and +`--project` are both `.codex/hooks.json`. Codex reads that file only in a +project trusted in `config.toml` (`[projects.""] trust_level = +"trusted"`), on top of the per-hook trust (verified on 0.166 in a scratch +`CODEX_HOME`: an untrusted project's file never fired, the user's did). + +- **A user-wide hook records only in a git repository.** It runs in every + directory an agent does, and the fallback that makes a plain directory a + workspace would otherwise snapshot `~/Downloads`. A repository with no + commits is still recorded (its project id is `dir:`). `hook::applies` + decides this from the event's cwd before a store is opened, so outside a + repository the hook costs one walk up for `.git`. A project-level install + still records a plain directory, since it was asked for there. +- **Each event is handled once, however many of loch's hooks it reaches.** + Claude Code and Codex run every scope's hooks for an event, at once, so a + user-wide hook and a project's own (or an old committed line beside Ness's + local one) would both snapshot a turn and race over its state, the second + `prompt` closing the first's turn as an empty interruption. Each event's + hooks get byte-identical stdin, so `hook::claim` takes a per-session lock + (`~/.loch/events/.last`), and a hook handed the same event that + another finished handling within 2s (timed in milliseconds) does nothing. An event is the hook's + name, its payload and its transcript's length. The payload alone can + repeat: Claude Code stopping twice for one prompt sends identical bytes, + which the first version of this took for a duplicate, losing the second + stop's edits (`stopping_twice_for_one_prompt_is_one_turn` caught it). The + agent waits on these hooks, so every hook for an event sees the same + transcript, and a genuine second event follows output that grew it. + `UserPromptSubmit` also carries a `prompt_id`, and Codex's events a + `turn_id`. The window is narrow because duplicates read the claim within + milliseconds of its being written, while a genuine repeat that hashes the + same (a second `Stop` before the transcript is flushed) follows a model + round trip. A wider window could only drop such an event. A lock that can't be taken + handles the event anyway, since a duplicate record beats a lost turn. +- **The first design guessed, and the guess could lose turns.** It had a + wider scope's hook step aside when a narrower file held loch's hook "and + the agent will run it". Answering that means knowing where the agent reads + a project's settings, whether it trusts them, and whether they changed + after it started (both agents snapshot hooks at startup). For Codex it + meant reading trust keys per group and index out of `config.toml`. Each + wrong answer skipped a hook the agent never ran, so nobody recorded the + turn. Idempotency needs none of those answers. +- **What was verified, on Claude Code 2.1.329 and Codex 0.166** (scratch + `HOME`/`CODEX_HOME`; Claude ran `UserPromptSubmit` before failing on its + missing login, which was enough): two user hooks and a project-local hook + for one event got byte-identical payloads, for both agents. + `UserPromptSubmit`'s keys are `session_id`, `transcript_path`, `cwd`, + `permission_mode`, `hook_event_name`, `prompt` and `prompt_id`. Claude + Code launched in `repo/sub` ran the repo root's `.claude/settings.local.json`, + and gave hooks `CLAUDE_PROJECT_DIR` as `repo/sub`. Claude's `Stop` payload + was not captured, since that needs a model call. If it ever differs + between hooks, the cost is a duplicate record. +- **Only loch's own lines are touched.** `trace::parse_hook_line` recognises a + line `hook_line` wrote, whatever the path to loch. The first loch line for + an event in the target file is rewritten in place if it differs (another + path, another scope) and reported as `replaced`. A second one, which an + older install appended after loch moved, is removed for Claude Code + (`removed`). For Codex it is left where it is and reported as + `duplicates`, since removing a group shifts the positional trust keys of + every group after it, and the claim makes it harmless. Only user-wide lines + name a scope (`--scope user`, the one `hook::applies` acts on), so a + project's committed lines and Ness's local ones are what they always were. +- **The user's file names plain `loch`.** That survives an npm upgrade under + another Node version, at the price of needing loch on the agent's PATH. + `--local` still defaults to the absolute path. + Git is still *read*, never written: for a project's identity (its root commit, the same on every clone and immune to history rewrites), for `list`'s default branch, for a file's earlier names (`git log --follow`, so blame finds @@ -331,7 +402,7 @@ re-derived. point. `install` reports `needsReview` and says to open `/hooks`. Trust is keyed by position, so loch appends its hooks as new groups and leaves every existing entry's position, and so its trust, alone. That is what - keeps Ness's user-level hooks trusted after a `--local` install. + keeps Ness's user-level hooks trusted after a user-wide install. `--dangerously-bypass-hook-trust` exists for automation. The tests used it, and loch never passes it. - **A cancelled turn gets no `Stop`.** Esc mid-turn writes `turn_aborted` @@ -827,11 +898,9 @@ empty. `save` and `list` carry the same signal ahead of time as Codex session rather than reused. `list` and `save` cover every agent unless `--agent` picks one, but **`install` writes Claude Code's hooks alone unless asked** (`--agent codex`, or `--agent all`). Installing Codex's too -by default changed what existing callers did. With `--local`, Ness's -`install --local --command` would have started writing the user-wide -`$CODEX_HOME/hooks.json`, putting loch in every Codex project and a review -prompt in the next TUI. Without it, a `.codex/` would land in every -Claude-only repo. `install`'s top-level `settings`/`added`/`removed` stay +by default would put loch, and a review prompt, in every Codex session on the +machine, or with `--project` a `.codex/` into every Claude-only repo. +`install`'s top-level `scope`/`settings`/`added`/`replaced`/`removed` stay the first agent's (Claude's by default), and `agents` lists each, with `needsReview` true where the agent won't run the hooks just added until a person approves them. A restore of a session whose agent this @@ -914,14 +983,18 @@ which hands most of the hooks' speed back on every Bash call. `bin/loch` with a hardlink to the native binary, so the `loch` on PATH is the binary itself. With `--ignore-scripts`, or on Windows, where npm runs bins through a `.cmd` wrapper anyway, the shim remains and still works. -- **Hooks:** Ness should write the binary's absolute path with `loch install - --local --command ` (settings.local.json, since the path is - machine-specific) rather than rely on PATH. That installs Claude Code's - hooks alone. Codex's need `--agent codex` (or `all`), and with `--local` - that means the user-wide `$CODEX_HOME/hooks.json`, beside Ness's own - status hooks there. Ness should only ask for it with the user's say-so, - and must not rewrite that file wholesale, or loch's hooks go with it. - Codex won't run them until they're trusted in `/hooks`. +- **Hooks:** Ness should keep writing the binary's absolute path with `loch + install --local --cwd --command ` (settings.local.json, + since the path is machine-specific) rather than rely on PATH. It means + "this worktree only", installs Claude Code's hooks alone, and writes the + same lines it always did. A user who also ran a plain `loch install` is + recorded once, since each event is handled once (`hook::claim`). + Codex's need `--agent codex` (or `all`). With `--local` that is the + worktree's `.codex/hooks.json`, which git sees and Codex runs only in a + trusted project. Without it, it is the user's `$CODEX_HOME/hooks.json`, + beside Ness's own status hooks. Either way, Ness should only ask with the + user's say-so and must never rewrite that file wholesale. Codex won't run + the hooks until they're trusted in `/hooks`. **Builds reproduce.** `SOURCE_DATE_EPOCH` fixes `save`'s `createdAt`, the one clock in a bundle's bytes, so the same sessions pack to the same ref. @@ -1196,19 +1269,35 @@ scratch repositories, a temporary store): - **Discovery.** All 70 local rollouts (four CLI versions) are found under their live cwd. A Claude `save` of 100 real sessions gave the same refs before and after the adapter extraction. -- **Install beside Ness.** `install --local` against a copy of this +- **Install beside Ness.** A user-wide install against a copy of this machine's `~/.codex/hooks.json` kept every Ness group byte for byte and in place, and appended loch's. -Not verified: the trust prompt was seen but loch's hooks were never -trusted through it. Every hook run used `--dangerously-bypass-hook-trust` -on a scratch repository, so how the TUI flow and `needsReview` read to a -person is untested. +- **User-wide install, real runs.** In a scratch `HOME`/`CODEX_HOME`, a + user-wide install appended loch's groups after a Ness-style status hook, + and `--local` appended them after a team hook in the repo's + `.codex/hooks.json`. All of it was trusted through the TUI's "Trust all and + continue", and the runs used no bypass flag. Each case below was one + `exec` turn: + - **The reviewer's lost-turn case.** Trust was removed from loch's project + entries and kept on the team hook's. Codex ran the team hook and skipped + loch's project one, and the user-wide hook recorded the turn. The + inference this replaced would have deferred and lost it. + - **Both trusted.** Both loch hooks ran, and the turn was recorded once, + not interrupted, and blamed correctly. + - **A plain directory.** The hooks ran (the status hook fired), and loch + wrote nothing, not even a claim. + + Measured: a user-wide hook outside a repository takes 2.8ms (process + start). The same 2,000-file directory without the gate takes 83ms, and + gets snapshotted. + +The TUI was driven by a script over a pty, so how the prompt and +`needsReview` read to a person is still untested. Codex gaps: `ingest` and `backfill` are Claude-only (SPEC.md §8's converter; -see the tool-call note above); a moved session has no branch; `install ---agent codex --local` installs into the user's hooks file, so loch runs for -every Codex project on the machine (it refuses `/` and home, as always); a +see the tool-call note above); a moved session has no branch; a +`--local` Codex install is a file git sees, since Codex has no other; a fork has no title; `archived_sessions` isn't searched. Also missing: `restore --map` (design intent recorded above, deliberately diff --git a/README.md b/README.md index 44b41c5..2d689f1 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,11 @@ sessions produces a single ref. ## Blame a line back to its conversation ```sh -loch install # once per project: Claude Code hooks, committed in .claude/ +loch install # once per machine: Claude Code hooks in ~/.claude/settings.json, + # recording in every git repository + # --local: this project only (.claude/settings.local.json) + # --project: committed in .claude/settings.json, for everyone + # --agent codex|all: Codex's too (trust them in its /hooks) loch blame src/format.rs # 102-112 2026-11-18 session 37d467e5 "loch-format-v1" — asked: "none of those seem like open questions…" diff --git a/src/agent.rs b/src/agent.rs index 9a91787..00993f7 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -5,7 +5,7 @@ //! What an adapter has to provide comes in tiers, and each tier is useful on //! its own: //! -//! 1. **Attribution** — `id`, `hook_events`, `hooks_file`. Blame and log need +//! 1. **Attribution** — `id`, `hook_events`, `hooks_file` per `Scope`. Blame and log need //! nothing else: a hook at a turn's start and end, carrying a session id //! and a cwd. `current_turn` (what the transcript says the turn was) only //! sharpens the record, and the default says nothing. @@ -55,6 +55,35 @@ pub struct TurnInfo { /// `("UserPromptSubmit", "prompt")`. pub type HookEvent = (&'static str, &'static str); +/// Where `install` puts hooks, from the widest to the narrowest. An agent +/// runs every scope's hooks for an event, and `hook::claim` sees that the +/// event is handled once. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scope { + /// The user's own hooks file: every project on the machine. + User, + /// The project's committed hooks file. + Project, + /// The project's hooks file for this machine alone, where the agent has one. + Local, +} + +impl Scope { + pub fn as_str(self) -> &'static str { + match self { + Scope::User => "user", + Scope::Project => "project", + Scope::Local => "local", + } + } + + pub fn parse(text: &str) -> Option { + [Scope::User, Scope::Project, Scope::Local] + .into_iter() + .find(|scope| scope.as_str() == text) + } +} + pub trait Agent: Sync { /// Stable identifier: edit records, store keys, bundles, `--agent`. fn id(&self) -> &'static str; @@ -65,10 +94,11 @@ pub trait Agent: Sync { /// The events loch hooks, and the subcommand each runs. fn hook_events(&self) -> &'static [HookEvent]; - /// The hooks file `install` writes, for a workspace root. - fn hooks_file(&self, root: &str, local: bool) -> String; + /// The hooks file `install` writes for a scope; `root` is the workspace + /// root, which the user scope ignores. + fn hooks_file(&self, scope: Scope, root: &str) -> String; /// What `install` says after writing, beyond the file it wrote. - fn install_note(&self) -> &'static str; + fn install_note(&self, scope: Scope) -> &'static str; /// Hooks this agent won't run until a person approves them. fn hooks_need_review(&self) -> bool { false diff --git a/src/argparse.rs b/src/argparse.rs index 3492a5a..7dbd505 100644 --- a/src/argparse.rs +++ b/src/argparse.rs @@ -234,6 +234,12 @@ impl Parser { self } + /// A usage error a command found after parsing, such as two flags that + /// exclude each other: `argument --b: not allowed with argument --a`. + pub fn usage_error(&self, message: &str) -> Exit { + self.error(message.into()) + } + fn error(&self, message: String) -> Exit { let prose = format!("{}{}: error: {}\n", self.format_usage(), self.prog, message); Exit::Usage { message, prose } diff --git a/src/claude.rs b/src/claude.rs index 124afba..89d97a5 100644 --- a/src/claude.rs +++ b/src/claude.rs @@ -3,7 +3,7 @@ //! and how a conversation is forked. pub use crate::agent::SessionMeta; -use crate::agent::{Agent, HookEvent, TurnInfo}; +use crate::agent::{Agent, HookEvent, Scope, TurnInfo}; use crate::json::{self, Map, Value}; use crate::object; use crate::py; @@ -521,18 +521,18 @@ impl Agent for ClaudeCode { HOOK_EVENTS } - /// The project's settings file, or with `local` the uncommitted one, since - /// a `--local` command is a machine-specific path. - fn hooks_file(&self, root: &str, local: bool) -> String { - let name = if local { - "settings.local.json" - } else { - "settings.json" - }; - sys::join(&sys::join(root, ".claude"), name) + /// The user's settings under `config_dir` (so `CLAUDE_CONFIG_DIR` picks + /// the account, as it does for transcripts), the project's committed + /// settings, or its uncommitted `settings.local.json`. + fn hooks_file(&self, scope: Scope, root: &str) -> String { + match scope { + Scope::User => sys::join(&config_dir(None), "settings.json"), + Scope::Project => sys::join(&sys::join(root, ".claude"), "settings.json"), + Scope::Local => sys::join(&sys::join(root, ".claude"), "settings.local.json"), + } } - fn install_note(&self) -> &'static str { + fn install_note(&self, _scope: Scope) -> &'static str { "restart Claude Code sessions here to pick them up" } diff --git a/src/cli.rs b/src/cli.rs index fb8e018..0c0397e 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,7 +1,7 @@ //! Every command: each builds one `Outcome` — payload //! and prose together — and `main` renders it. -use crate::agent::{self, Agent}; +use crate::agent::{self, Agent, Scope}; use crate::argparse::{Exit, Nargs, Parser}; use crate::attribution::{self, EditRecord}; use crate::blame_html; @@ -920,9 +920,14 @@ pub fn command_hook(argv: &[String]) -> Run { .and_then(|i| argv.get(i + 1)) .map(String::as_str) .unwrap_or(AGENT); + let scope = argv + .iter() + .position(|a| a == "--scope") + .and_then(|i| argv.get(i + 1)) + .and_then(|s| Scope::parse(s)); let mut stdin = Vec::new(); if std::io::stdin().read_to_end(&mut stdin).is_ok() { - crate::hook::run(name, agent_id, &stdin); + crate::hook::run(name, agent_id, scope, &stdin); } Ok(Outcome::new("hook")) } @@ -954,12 +959,28 @@ pub fn command_install(argv: &[String]) -> Run { let mut p = parser("install"); p.option("--cwd") .flag("--local", None) + .flag("--project", None) .option("--command") .option("--agent"); let args = p.parse(argv)?; + if args.flag("local") && args.flag("project") { + return Err(p + .usage_error("argument --project: not allowed with argument --local") + .into()); + } + // The user's hooks unless asked: one install covers every project, with + // nothing written into any of them. + let scope = if args.flag("local") { + Scope::Local + } else if args.flag("project") { + Scope::Project + } else { + Scope::User + }; // Claude Code's alone unless asked: an install that also wrote Codex's - // hooks would, with --local, put loch in every Codex project on the - // machine, and without it drop a .codex/ into repos that never use Codex. + // hooks would put loch in every Codex session on the machine, or drop a + // .codex/ into repos that never use Codex, and leave a review prompt in + // its next TUI either way. let agents = agents_arg(Some(args.str("agent").as_deref().unwrap_or(AGENT)))?; let cwd = args .str("cwd") @@ -968,34 +989,45 @@ pub fn command_install(argv: &[String]) -> Run { let root = snapshot::workspace_root(&cwd); let command = match args.str("command") { Some(command) => command, - // A machine-specific path, which is why it only goes in the - // uncommitted settings file. - None if args.flag("local") => which("loch") + // A machine-specific path, which is why only the uncommitted settings + // file gets one. The user's file names plain `loch` too, so it keeps + // working when loch moves (an npm upgrade under another Node version), + // at the price of depending on the agent's PATH. + None if scope == Scope::Local => which("loch") .unwrap_or_else(|| sys::abspath(&std::env::args().next().unwrap_or_default())), None => "loch".into(), }; let mut text = String::new(); let mut results = Vec::new(); for adapter in &agents { - let settings = adapter.hooks_file(&root, args.flag("local")); - let installed = trace::install_hooks(&settings, &command, *adapter) + let settings = adapter.hooks_file(scope, &root); + let installed = trace::install_hooks(&settings, &command, *adapter, scope) .map_err(|trace::InstallError::Internal(m)| Failure::Internal(m))?; - if installed.added.is_empty() { + if installed.added.is_empty() && installed.replaced.is_empty() { text.push_str(&format!("loch hooks already installed in {}\n", settings)); } else { + let mut events = installed.added.clone(); + events.extend(installed.replaced.iter().cloned()); text.push_str(&format!( "installed loch hooks ({}) in {}\n", - installed.added.join(", "), + events.join(", "), settings )); } if !installed.removed.is_empty() { text.push_str(&format!( - "removed the old per-command hooks ({})\n", + "removed old and duplicate loch hooks ({})\n", installed.removed.join(", ") )); } - text.push_str(&format!("{}\n", adapter.install_note())); + if !installed.duplicates.is_empty() { + text.push_str(&format!( + "left a second loch hook for {} where it is (each event is still handled once); remove it in {} if you like\n", + installed.duplicates.join(", "), + settings + )); + } + text.push_str(&format!("{}\n", adapter.install_note(scope))); results.push(( adapter.id(), settings, @@ -1003,14 +1035,22 @@ pub fn command_install(argv: &[String]) -> Run { adapter.hooks_need_review(), )); } + text.push_str(match scope { + Scope::User => "they run in every git repository\n", + Scope::Project => "they run for everyone who works in this project\n", + Scope::Local => "they run in this project, on this machine alone\n", + }); // The first agent's at the top level, as before there were several. let (_, settings, installed, _) = &results[0]; let mut payload = object! { + "scope" => scope.as_str(), "settings" => settings.as_str(), // Not `command`, which is the envelope's: the hooks' loch. "hookCommand" => command.as_str(), "added" => strings(&installed.added), + "replaced" => strings(&installed.replaced), "removed" => strings(&installed.removed), + "duplicates" => strings(&installed.duplicates), }; payload.insert( "agents".into(), @@ -1018,14 +1058,18 @@ pub fn command_install(argv: &[String]) -> Run { results .iter() .map(|(id, settings, installed, review)| { + let changed = !installed.added.is_empty() || !installed.replaced.is_empty(); Value::Object(object! { "agent" => *id, + "scope" => scope.as_str(), "settings" => settings.as_str(), "added" => strings(&installed.added), + "replaced" => strings(&installed.replaced), "removed" => strings(&installed.removed), - // The agent won't run a new hook until a person - // approves it; loch never approves its own. - "needsReview" => *review && !installed.added.is_empty(), + "duplicates" => strings(&installed.duplicates), + // The agent won't run a new or changed hook until a + // person approves it; loch never approves its own. + "needsReview" => *review && changed, }) }) .collect(), diff --git a/src/codex.rs b/src/codex.rs index 1c4b29a..40c8f3d 100644 --- a/src/codex.rs +++ b/src/codex.rs @@ -19,7 +19,7 @@ //! - **A turn has an id.** Hooks carry `turn_id` and records name it, so a //! turn's start and end in the transcript are that id, not a record. -use crate::agent::{Agent, HookEvent, SessionMeta, TurnInfo}; +use crate::agent::{Agent, HookEvent, Scope, SessionMeta, TurnInfo}; use crate::claude::{display_summary, home_dir, resolve_cwd}; use crate::json::{self, Map, Value}; use crate::py; @@ -485,20 +485,31 @@ impl Agent for Codex { HOOK_EVENTS } - /// The project's `.codex/hooks.json`, or with `local` the user's - /// `$CODEX_HOME/hooks.json`: Codex has no uncommitted project file, and a - /// `--local` command is a machine-specific path. The user's file applies - /// to every project, which attribution handles — it refuses `/` and home. - fn hooks_file(&self, root: &str, local: bool) -> String { - if local { - sys::join(&codex_home(), "hooks.json") - } else { - sys::join(&sys::join(root, ".codex"), "hooks.json") + /// The user's `$CODEX_HOME/hooks.json`, or the project's + /// `.codex/hooks.json` for both narrower scopes: Codex has no uncommitted + /// project file, so a `--local` install is one git sees. + fn hooks_file(&self, scope: Scope, root: &str) -> String { + match scope { + Scope::User => sys::join(&codex_home(), "hooks.json"), + Scope::Project | Scope::Local => sys::join(&sys::join(root, ".codex"), "hooks.json"), } } - fn install_note(&self) -> &'static str { - "Codex runs new hooks only once trusted: open /hooks in Codex and trust loch's" + fn install_note(&self, scope: Scope) -> &'static str { + match scope { + Scope::User => { + "Codex runs new hooks only once trusted: open /hooks in Codex and trust loch's" + } + Scope::Project => { + "Codex runs a project's hooks only in a project it trusts, and new hooks only \ + once trusted: open /hooks in Codex and trust loch's" + } + Scope::Local => { + "Codex has no uncommitted hooks file, so these are in the project's, which git \ + sees. Codex runs them only in a project it trusts, and only once trusted: open \ + /hooks in Codex and trust loch's" + } + } } fn hooks_need_review(&self) -> bool { diff --git a/src/hook.rs b/src/hook.rs index 773f429..6d54154 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -20,7 +20,7 @@ //! and nothing is written to stdout: a hook that breaks the agent gets //! uninstalled. -use crate::agent::{self, Agent, TurnInfo}; +use crate::agent::{self, Agent, Scope, TurnInfo}; use crate::attribution::{self, EditRecord, TurnRecord}; use crate::json::{self, Map, Value}; use crate::object; @@ -285,6 +285,15 @@ pub fn end(agent: &dyn Agent, event: &Map, store: Option<&dyn Store>) -> Result< pub fn roots() -> Vec { let mut roots = snapshot::workspace_roots(); let now = std::time::SystemTime::now(); + for entry in fs::read_dir(events_dir()).into_iter().flatten().flatten() { + let age = fs::metadata(entry.path()) + .and_then(|m| m.modified()) + .ok() + .and_then(|modified| now.duration_since(modified).ok()); + if age.is_some_and(|age| age > ABANDONED) { + let _ = fs::remove_file(entry.path()); + } + } let Ok(entries) = fs::read_dir(sessions_dir()) else { return roots; }; @@ -335,9 +344,138 @@ pub fn snapshot_transcript( Ok(Some(key)) } +/// Whether a hook installed at `scope` records this event, decided before +/// anything is opened. A user-wide hook runs in every directory the agent +/// does, and records only in a git repository: anywhere else it would +/// snapshot whatever directory a session happened to start in +/// (`~/Downloads`, a scratch dir), which nobody asked for by installing loch +/// once. A project-level install still records a plain directory, since that +/// was asked for. A line naming no scope (local ones, and every line before +/// scopes) records as it always did. +pub fn applies(scope: Option, event: &Map) -> bool { + if scope != Some(Scope::User) { + return true; + } + let root = snapshot::workspace_root(&event_cwd(event)); + // A home directory that is itself a repository (dotfiles) is the root of + // every directory under it, and is refused before any store is opened. + snapshot::has_git_marker(&root) && snapshot::snapshottable(&root) +} + +/// How long after one hook has handled an event a byte-identical one is taken +/// to be the same event, seen by another hook. Those start within +/// milliseconds of each other and, having waited on the lock, read the time +/// the first wrote as it let go. A genuine repeat follows a model round trip, +/// which is seconds, so a wider window could only drop real events. +const DUPLICATE_WINDOW_MS: u64 = 2_000; + +fn now_ms() -> u64 { + (sys::now() * 1000.0) as u64 +} + +fn events_dir() -> PathBuf { + snapshot::loch_home().join("events") +} + +/// The right to handle one event, held for as long as the hook runs. +/// +/// **An event is handled once, however many of loch's hooks it reaches.** An +/// agent runs every scope's hooks for an event (a user-wide one, a project's, +/// an older line beside a newer one), at once, and each gets the same bytes +/// on stdin: verified on Claude Code 2.1 and Codex 0.166. Two hooks handling +/// one prompt would snapshot it twice and race over the session's state, the +/// second closing the first's turn as an empty interruption. So the hooks of +/// a session take turns under a lock, and one finding that the event it was +/// handed was handled moments ago does nothing. An event is its hook's name, +/// its payload and the length of its transcript: Claude Code's prompts carry +/// a `prompt_id` and Codex's events a `turn_id`, and a second `Stop` for one +/// prompt comes after more of the transcript was written. +/// +/// Deciding instead which hook should step aside means knowing which files +/// the agent runs: where it reads a project's settings from, whether it +/// trusts them, whether they changed after it started. A wrong answer loses +/// the turn. This needs none of it. +pub struct Claim { + file: fs::File, + digest: String, +} + +pub enum Claimed { + /// This hook handles the event; `finish` once done. + Mine(Claim), + /// Another hook already has. + Handled, + /// The lock couldn't be taken. The event is handled anyway, since a + /// duplicate record beats a lost turn. + Unguarded, +} + +pub fn claim(session: &str, name: &str, stdin: &[u8], transcript: Option<&str>) -> Claimed { + use sha2::{Digest, Sha256}; + use std::io::Read; + let mut hasher = Sha256::new(); + hasher.update(name.as_bytes()); + hasher.update(b"\n"); + hasher.update(stdin); + // The payload alone can repeat: Claude Code stopping twice for one prompt + // sends the same bytes both times. The agent waits on these hooks, so + // every hook for one event sees the same transcript, and a genuine second + // event follows the output that grew it. Read before waiting on the lock, + // as the hooks start, so nothing the agent writes once another hook has + // exited is counted. + let length = transcript + .and_then(|t| fs::metadata(t).ok()) + .map(|m| m.len()); + hasher.update(format!("\n{:?}", length).as_bytes()); + let digest: String = hasher + .finalize() + .iter() + .map(|b| format!("{:02x}", b)) + .collect(); + let Ok(()) = fs::create_dir_all(events_dir()) else { + return Claimed::Unguarded; + }; + let Ok(mut file) = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(events_dir().join(format!("{}.last", session))) + else { + return Claimed::Unguarded; + }; + if file.lock().is_err() { + return Claimed::Unguarded; + } + let mut seen = String::new(); + let _ = file.read_to_string(&mut seen); + let recent = seen + .split_once(' ') + .filter(|(last, _)| *last == digest) + .and_then(|(_, at)| at.trim().parse::().ok()) + .is_some_and(|at| now_ms().saturating_sub(at) < DUPLICATE_WINDOW_MS); + if recent { + Claimed::Handled + } else { + Claimed::Mine(Claim { file, digest }) + } +} + +impl Claim { + /// Records the event as handled, timed from when it finished, and lets + /// the session's next hook in. A write cut short leaves something that + /// matches nothing, so the next hook handles the event again. + pub fn finish(mut self) { + use std::io::{Seek, Write}; + let _ = self.file.set_len(0); + let _ = self.file.seek(std::io::SeekFrom::Start(0)); + let _ = write!(self.file, "{} {}", self.digest, now_ms()); + } +} + /// Run by the harness with the event as JSON on stdin. An agent this build /// doesn't know does nothing, like every other failure here. -pub fn run(name: &str, agent_id: &str, stdin: &[u8]) { +pub fn run(name: &str, agent_id: &str, scope: Option, stdin: &[u8]) { let Some(agent) = agent::by_id(agent_id) else { return; }; @@ -348,6 +486,17 @@ pub fn run(name: &str, agent_id: &str, stdin: &[u8]) { let Ok(Value::Object(event)) = json::loads(text) else { return; }; + if !applies(scope, &event) { + return; + } + let claim = match session_of(&event) { + Ok(session) => match claim(&session, name, stdin, transcript_of(&event).as_deref()) { + Claimed::Handled => return, + Claimed::Mine(claim) => Some(claim), + Claimed::Unguarded => None, + }, + Err(Stop) => None, + }; let store = || store::create_store(&store::resolve_store_uri(None)).ok(); let _ = match name { "prompt" => prompt(agent, &event, store().as_deref()), @@ -357,6 +506,9 @@ pub fn run(name: &str, agent_id: &str, stdin: &[u8]) { // still name them until `install` is re-run; they do nothing. _ => return, }; + if let Some(claim) = claim { + claim.finish(); + } // Collection rides on the hooks, as `git gc --auto` rides on commands: // the check is a counter read, and the work runs once in many turns. if snapshot::collection_due() { diff --git a/src/trace.rs b/src/trace.rs index 483c823..a1b7a85 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -5,7 +5,7 @@ //! What a turn changed is recorded by the hooks (`hook.rs`) and matched by //! content (`attribution.rs`); nothing here reads or writes git history. -use crate::agent::{self, Agent}; +use crate::agent::{self, Agent, Scope}; use crate::attribution::{EditRecord, TurnRecord}; use crate::claude::{self, home_dir}; use crate::format::Turn; @@ -62,6 +62,9 @@ pub fn py_str(value: Option<&Value>) -> String { /// git-notes design. Removed on install, so they stop costing a process each. const RETIRED: &[&str] = &["pre-tool", "post-tool"]; +/// How every line `install` writes ends. +const LINE_END: &str = " 2>/dev/null || true"; + #[derive(Debug)] pub enum InstallError { Internal(String), @@ -69,36 +72,92 @@ pub enum InstallError { pub struct Installed { pub added: Vec, + /// Events whose loch line was there in another form (another path to + /// loch, another scope) and was rewritten where it stood. + pub replaced: Vec, + /// Old loch hooks no longer used, and second loch lines for an event. pub removed: Vec, + /// Second loch lines for an event that were left where they are, since + /// the agent keys trust by position. + pub duplicates: Vec, } /// The line a hook runs. `agent` is passed only for agents other than Claude -/// Code, so the lines earlier versions wrote for it still match. -pub fn hook_line(command: &str, name: &str, agent: &dyn Agent) -> String { +/// Code, and the scope only for the user's, so the lines earlier versions +/// wrote still match. +pub fn hook_line(command: &str, name: &str, agent: &dyn Agent, scope: Scope) -> String { let flag = if agent.id() == claude::AGENT { String::new() } else { format!(" --agent {}", agent.id()) }; - // A checkout whose machine lacks loch gets a silent no-op rather than an - // error on every turn, since the settings file is committed. - format!("{} hook {}{} 2>/dev/null || true", command, name, flag) + // Only the user's lines name a scope, the one `hook::applies` acts on, so + // a project's committed lines and Ness's local ones stay as they were. + let scope = match scope { + Scope::User => format!(" --scope {}", Scope::User.as_str()), + Scope::Project | Scope::Local => String::new(), + }; + // A machine without loch gets a silent no-op rather than an error on every + // turn, since a project's settings file is committed and a user's applies + // everywhere. + format!("{} hook {}{}{}{}", command, name, flag, scope, LINE_END) +} + +/// A loch hook line, read back: which hook, for which agent, at which scope +/// (`None` for a line that names none, as local ones and older ones don't). +pub struct HookLine { + pub name: String, + pub agent: String, + pub scope: Option, +} + +/// Whether `line` is one `hook_line` wrote, whatever the path to loch. Only +/// these are ever rewritten or removed; every other hook is left alone. +pub fn parse_hook_line(line: &str) -> Option { + let body = line.strip_suffix(LINE_END)?; + let at = body.rfind(" hook ")?; + let mut words = body[at + " hook ".len()..].split(' '); + let name = words.next()?.to_string(); + let known = RETIRED.contains(&name.as_str()) + || agent::all() + .iter() + .any(|a| a.hook_events().iter().any(|(_, n)| *n == name)); + if !known || body[..at].is_empty() { + return None; + } + let mut parsed = HookLine { + name, + agent: claude::AGENT.into(), + scope: None, + }; + while let Some(flag) = words.next() { + let value = words.next()?; + match flag { + "--agent" => parsed.agent = value.into(), + "--scope" => parsed.scope = Some(Scope::parse(value)?), + _ => return None, + } + } + Some(parsed) } fn is_retired(line: &str) -> bool { - RETIRED - .iter() - .any(|name| line.ends_with(&format!(" hook {} 2>/dev/null || true", name))) + parse_hook_line(line).is_some_and(|l| RETIRED.contains(&l.name.as_str())) } /// Adds an agent's loch hooks to its hooks file, keeping whatever else is /// there, and takes out the ones loch no longer uses. Re-running changes -/// nothing. Claude Code's settings and Codex's hooks.json share the shape +/// nothing. A loch line already there in another form is rewritten in place, +/// and a second one for the same event removed, so no other hook moves; +/// where the agent keys trust by position (Codex), the second is left and +/// reported instead. Claude Code's settings and Codex's +/// hooks.json share the shape /// `{"hooks": {"": [{"hooks": [{"type": "command", "command": ...}]}]}}`. pub fn install_hooks( settings_path: &str, command: &str, agent: &dyn Agent, + scope: Scope, ) -> std::result::Result { let mut settings = match fs::read(settings_path) { Ok(bytes) => { @@ -154,39 +213,90 @@ pub fn install_hooks( hooks.retain(|_, groups| groups.as_array().is_none_or(|g| !g.is_empty())); let mut added = Vec::new(); + let mut replaced = Vec::new(); + let mut duplicates = Vec::new(); + // An agent whose trust is keyed by position keeps every group where it + // is: removing one would shift the keys of all the groups after it. + let positional = agent.hooks_need_review(); for (event, name) in agent.hook_events() { - let line = hook_line(command, name, agent); + let line = hook_line(command, name, agent, scope); let groups = hooks .entry(event.to_string()) .or_insert_with(|| Value::Array(Vec::new())); let Value::Array(groups) = groups else { return Err(not_a_dict()); }; - let present = groups.iter().any(|group| { + let ours = |entry: &Value| { + entry + .get("command") + .and_then(Value::as_str) + .and_then(parse_hook_line) + .is_some_and(|l| l.name == *name && l.agent == agent.id()) + }; + let mut seen = 0; + for group in groups.iter_mut() { + let Some(Value::Array(entries)) = + group.as_object_mut().and_then(|g| g.get_mut("hooks")) + else { + continue; + }; + let mut index = 0; + while index < entries.len() { + if !ours(&entries[index]) { + index += 1; + continue; + } + seen += 1; + if seen == 1 { + if !entries[index] + .get("command") + .is_some_and(|c| c.is_str(&line)) + { + if let Some(entry) = entries[index].as_object_mut() { + entry.insert("command".into(), Value::str(line.as_str())); + } + replaced.push(event.to_string()); + } + index += 1; + } else if positional { + // Harmless beside the first, since an event is handled + // once (`hook::claim`), and only the person can retire it. + duplicates.push(event.to_string()); + index += 1; + } else { + // Another path to loch, appended by an older install. + entries.remove(index); + removed.push(event.to_string()); + } + } + } + groups.retain(|group| { group .get("hooks") .and_then(Value::as_array) - .is_some_and(|entries| { - entries - .iter() - .any(|entry| entry.get("command").is_some_and(|c| c.is_str(&line))) - }) + .is_none_or(|entries| !entries.is_empty()) }); - if present { - continue; + if seen == 0 { + groups.push(Value::Object(object! { + "hooks" => vec![Value::Object(object! {"type" => "command", "command" => line.as_str()})], + })); + added.push(event.to_string()); } - groups.push(Value::Object(object! { - "hooks" => vec![Value::Object(object! {"type" => "command", "command" => line.as_str()})], - })); - added.push(event.to_string()); } let parent = sys::dirname(settings_path); fs::create_dir_all(&parent).map_err(|e| InstallError::Internal(sys::os_error(&e, &parent)))?; let text = format!("{}\n", json::dumps(&settings, json::INDENTED)); fs::write(settings_path, text) .map_err(|e| InstallError::Internal(sys::os_error(&e, settings_path)))?; - removed.dedup(); - Ok(Installed { added, removed }) + let mut unique = std::collections::HashSet::new(); + removed.retain(|event| unique.insert(event.clone())); + duplicates.dedup(); + Ok(Installed { + added, + replaced, + removed, + duplicates, + }) } // -- transcripts ---------------------------------------------------------------- diff --git a/src/usage.txt b/src/usage.txt index d494c0f..98a2771 100644 --- a/src/usage.txt +++ b/src/usage.txt @@ -11,7 +11,8 @@ Usage: loch ingest [--cwd ] [--branch ] [--session ] [--author | --author-key ] [--out ] - loch install [--local] [--command ] [--agent ] + loch install [--local | --project] [--cwd ] [--command ] + [--agent ] loch blame [--html [] [--lines ] [--no-open]] [--store ] loch log [:[-]] [--store ] @@ -44,12 +45,17 @@ Environment: Derived conversation files go to ~/.loch/derived unless --out says otherwise. -`install` adds Claude Code hooks (.claude/settings.json, or with --local -.claude/settings.local.json), and with --agent codex or all Codex's -(.codex/hooks.json, or with --local the user-wide ~/.codex/hooks.json), snapshot the workspace when a prompt is submitted, +`install` adds hooks that snapshot the workspace when a prompt is submitted, when the agent stops and when the session ends, and record which lines each turn added — however it added them — in the store, along with the session's -transcript. Codex runs new hooks only after you trust them in its /hooks. +transcript. By default they go in your own settings (Claude Code's +settings.json under CLAUDE_CONFIG_DIR or ~/.claude, Codex's +$CODEX_HOME/hooks.json) and run in every git repository. --local puts them in +this project on this machine alone (.claude/settings.local.json; Codex has no +uncommitted file, so .codex/hooks.json), and --project in its committed +settings for everyone. A turn is recorded once, however many of these reach +it. Codex runs new hooks only after you trust them in its /hooks, and a +project's only in a project it trusts. Nothing is written to git, so squashes and rebases don't lose anything. `blame` shows which turn wrote each line, `log` every turn that changed a file or line range; `ask` forks that conversation and resumes it in the agent that diff --git a/tests/codex.rs b/tests/codex.rs index 9e05bcf..41f35ab 100644 --- a/tests/codex.rs +++ b/tests/codex.rs @@ -717,13 +717,15 @@ fn a_bundle_of_claude_sessions_alone_has_no_agent_fields() { #[test] fn install_adds_codex_hooks_beside_the_ones_already_there() { let world = World::new(); - let hooks = world.repo.join(".codex/hooks.json"); + // Ness's status hooks live in the user's file. + let hooks = world.home.join(".codex/hooks.json"); fs::create_dir_all(hooks.parent().unwrap()).unwrap(); let theirs = r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"their-status-hook","timeout":5}]}],"PreToolUse":[{"hooks":[{"type":"command","command":"their-tool-hook"}]}]}}"#; fs::write(&hooks, theirs).unwrap(); let installed = world.ok(&["install", "--agent", "codex"]); assert_eq!(text(&installed, "command"), "install"); + assert_eq!(text(&installed, "scope"), "user"); assert_eq!(text(&installed, "hookCommand"), "loch"); let codex = &items(&installed, "agents")[0]; assert_eq!(text(codex, "agent"), "codex"); @@ -741,25 +743,30 @@ fn install_adds_codex_hooks_beside_the_ones_already_there() { let line = |group: &Value| text(&items(group, "hooks")[0], "command").to_string(); assert_eq!( line(&stop[1]), - "loch hook stop --agent codex 2>/dev/null || true" + "loch hook stop --agent codex --scope user 2>/dev/null || true" ); assert_eq!(groups("PreToolUse").len(), 1); assert_eq!( line(&groups("UserPromptSubmit")[0]), - "loch hook prompt --agent codex 2>/dev/null || true" + "loch hook prompt --agent codex --scope user 2>/dev/null || true" ); assert_eq!( line(&groups("SessionEnd")[0]), - "loch hook end --agent codex 2>/dev/null || true" + "loch hook end --agent codex --scope user 2>/dev/null || true" ); + assert!(!world.repo.join(".codex").exists()); let again = world.ok(&["install", "--agent", "codex"]); let codex = &items(&again, "agents")[0]; assert!(items(codex, "added").is_empty()); assert_eq!(at(codex, "needsReview"), &Value::Bool(false)); - assert_eq!(groups("Stop").len(), 2); + let written = json::loads(&fs::read_to_string(&hooks).unwrap()).unwrap(); + assert_eq!( + at(at(&written, "hooks"), "Stop").as_array().unwrap().len(), + 2 + ); - // --local is machine-specific, so it goes to the user's file. + // Codex has no uncommitted project file, so --local is the project's. let local = world.ok(&[ "install", "--agent", @@ -768,9 +775,11 @@ fn install_adds_codex_hooks_beside_the_ones_already_there() { "--command", "/opt/loch", ]); + let codex = &items(&local, "agents")[0]; + assert_eq!(text(codex, "scope"), "local"); assert_eq!( - text(&items(&local, "agents")[0], "settings"), - s(&world.home.join(".codex/hooks.json")) + text(codex, "settings"), + s(&world.repo.join(".codex/hooks.json")) ); } @@ -778,15 +787,22 @@ fn install_adds_codex_hooks_beside_the_ones_already_there() { fn install_sets_up_claude_alone_unless_asked() { let world = World::new(); // What existing callers (Ness's `install --local --command`) run: it must - // not start writing Codex's user-wide hooks file. + // write this worktree's Claude settings and nothing of Codex's. let local = world.ok(&["install", "--local", "--command", "/opt/loch"]); assert_eq!(items(&local, "agents").len(), 1); + assert_eq!( + text(&local, "settings"), + s(&world.repo.join(".claude/settings.local.json")) + ); + let written = fs::read_to_string(world.repo.join(".claude/settings.local.json")).unwrap(); + assert!(written.contains("\"/opt/loch hook stop 2>/dev/null || true\"")); assert!(!world.home.join(".codex").exists()); + assert!(!world.repo.join(".codex").exists()); let plain = world.ok(&["install"]); assert_eq!(text(&items(&plain, "agents")[0], "agent"), "claude-code"); - assert!(!world.repo.join(".codex").exists()); + assert!(!world.home.join(".codex").exists()); - let installed = world.ok(&["install", "--agent", "all"]); + let installed = world.ok(&["install", "--agent", "all", "--project"]); let agents: Vec<&str> = items(&installed, "agents") .iter() .map(|a| text(a, "agent")) @@ -802,6 +818,68 @@ fn install_sets_up_claude_alone_unless_asked() { assert!(claude.contains("\"loch hook stop 2>/dev/null || true\"")); } +/// Codex runs the user's and the project's hooks for every event, each with +/// the same payload. Which of them Codex actually runs (an untrusted project, +/// an untrusted hook) doesn't matter: whichever gets there first records the +/// event, and the other finds it handled. +#[test] +fn a_codex_event_reaching_two_loch_hooks_is_recorded_once() { + let world = World::new(); + let repo = s(&world.repo); + let both = |name: &str, event: &str| { + for scope in [&["--scope", "user"][..], &[][..]] { + let mut args = vec!["hook", name, "--agent", "codex"]; + args.extend_from_slice(scope); + let out = world.loch_with(&args, event); + assert!(out.status.success() && out.stdout.is_empty()); + } + }; + for (turn, minute, prompt, script) in [ + (TURN_A, 1, "first", "echo one > a.txt"), + (TURN_B, 2, "second", "echo two > b.txt"), + ] { + world.begin(SESSION, turn, &repo, minute, prompt); + both("prompt", &world.event(SESSION, Some(turn), Some(prompt))); + world.sh(script); + world.finish(SESSION, turn, minute); + both("stop", &world.event(SESSION, Some(turn), None)); + } + let record = world.edit_record(); + let turns = items(&record, "turns"); + assert_eq!(turns.len(), 2); + assert!(turns.iter().all(|t| !at(t, "interrupted").truthy())); +} + +#[test] +fn install_leaves_a_second_codex_loch_line_where_it_is() { + let world = World::new(); + let hooks = world.home.join(".codex/hooks.json"); + fs::create_dir_all(hooks.parent().unwrap()).unwrap(); + let two = r#"{"hooks":{"Stop":[ + {"hooks":[{"type":"command","command":"/a/loch hook stop --agent codex 2>/dev/null || true"}]}, + {"hooks":[{"type":"command","command":"their-status-hook"}]}, + {"hooks":[{"type":"command","command":"/b/loch hook stop --agent codex 2>/dev/null || true"}]}]}}"#; + fs::write(&hooks, two).unwrap(); + let installed = world.ok(&["install", "--agent", "codex"]); + let codex = &items(&installed, "agents")[0]; + assert_eq!(items(codex, "duplicates")[0].as_str(), Some("Stop")); + let written = json::loads(&fs::read_to_string(&hooks).unwrap()).unwrap(); + let stop = at(at(&written, "hooks"), "Stop") + .as_array() + .unwrap() + .clone(); + let line = |group: &Value| text(&items(group, "hooks")[0], "command").to_string(); + // Every group keeps its position, and so its trust. + assert_eq!( + stop.iter().map(line).collect::>(), + vec![ + "loch hook stop --agent codex --scope user 2>/dev/null || true".to_string(), + "their-status-hook".to_string(), + "/b/loch hook stop --agent codex 2>/dev/null || true".to_string(), + ] + ); +} + #[test] fn a_timestamp_a_bundle_carries_cannot_crash_restore() { let world = World::new(); diff --git a/tests/trace.rs b/tests/trace.rs index e249244..b9d30d2 100644 --- a/tests/trace.rs +++ b/tests/trace.rs @@ -23,6 +23,10 @@ struct World { store: PathBuf, transcript: PathBuf, minute: usize, + /// Hooks run as the harness would: every loch line the settings files + /// hold for the event, in parallel, rather than one `loch hook` call. + fired: bool, + sequential: bool, } impl Drop for World { @@ -58,7 +62,12 @@ impl World { home, repo, minute: 0, + fired: false, + sequential: false, }; + let bin = world.root.join("bin"); + fs::create_dir_all(&bin).unwrap(); + std::os::unix::fs::symlink(env!("CARGO_BIN_EXE_loch"), bin.join("loch")).unwrap(); fs::create_dir_all(world.transcript.parent().unwrap()).unwrap(); if git { world.git(&world.repo, &["init", "-q", "-b", "main"]); @@ -75,6 +84,10 @@ impl World { command .current_dir(cwd) .env("HOME", &self.home) + .env( + "PATH", + format!("{}:/usr/bin:/bin", s(&self.root.join("bin"))), + ) .env("LOCH_STORE", &self.store) .env("GIT_CONFIG_GLOBAL", self.root.join("gitconfig")) .env("GIT_CONFIG_NOSYSTEM", "1") @@ -167,10 +180,78 @@ impl World { s(&self.transcript), text ); + if self.fired { + self.fire("UserPromptSubmit", &event); + return; + } let out = self.loch_in(&self.repo, &["hook", "prompt"], &event); assert!(out.status.success() && out.stdout.is_empty()); } + /// The settings files Claude Code reads for the repo, user-wide first. + fn settings_files(&self) -> Vec { + vec![ + self.home.join(".claude/settings.json"), + self.repo.join(".claude/settings.json"), + self.repo.join(".claude/settings.local.json"), + ] + } + + /// Every command the settings files hold for `event`. + fn hook_commands(&self, event: &str) -> Vec { + let mut commands = Vec::new(); + for file in self.settings_files() { + let Ok(text) = fs::read_to_string(&file) else { + continue; + }; + let settings = json::loads(&text).unwrap(); + let Some(groups) = settings.get("hooks").and_then(|h| h.get(event)) else { + continue; + }; + for group in groups.as_array().unwrap() { + for entry in group.get("hooks").unwrap().as_array().unwrap() { + commands.push(entry.get("command").unwrap().as_str().unwrap().to_string()); + } + } + } + commands + } + + /// Runs an event's hooks as Claude Code does, all at once, in `cwd`; or + /// one after another, the ordering in which a second `prompt` finds the + /// first's turn open. + fn fire_in(&self, cwd: &Path, event: &str, stdin: &str) { + let one_by_one = self.sequential; + let mut children = Vec::new(); + for line in self.hook_commands(event) { + children.push({ + let mut child = self + .command("sh", cwd) + .args(["-c", &line]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(stdin.as_bytes()) + .unwrap(); + child + }); + if one_by_one { + settle(children.pop().unwrap()); + } + } + children.into_iter().for_each(settle); + } + + fn fire(&self, event: &str, stdin: &str) { + self.fire_in(&self.repo, event, stdin); + } + fn hook(&self, name: &str) { let out = self.loch_in(&self.repo, &["hook", name], &self.event()); assert!(out.status.success() && out.stdout.is_empty()); @@ -215,6 +296,10 @@ impl World { s(&self.repo), self.minute )); + if self.fired { + self.fire("Stop", &self.event()); + return; + } let out = self.loch_in(&self.repo, &["hook", "stop"], &self.event()); assert!(out.status.success() && out.stdout.is_empty()); } @@ -240,6 +325,11 @@ impl World { } } +fn settle(child: std::process::Child) { + let out = child.wait_with_output().unwrap(); + assert!(out.status.success() && out.stdout.is_empty() && out.stderr.is_empty()); +} + /// Each line's owner, as prompt text or None. fn owners(blame: &Value) -> Vec> { let mut lines = Vec::new(); @@ -286,12 +376,12 @@ fn install_writes_the_two_turn_hooks_and_keeps_existing_settings() { ) .unwrap(); // No repository is needed: the hooks record files, not commits. - let first = w.json(&["install"]); + let first = w.json(&["install", "--project"]); assert_eq!( first.get("added").unwrap(), &json::loads(r#"["UserPromptSubmit", "Stop", "SessionEnd"]"#).unwrap() ); - let again = w.json(&["install"]); + let again = w.json(&["install", "--project"]); assert_eq!(again.get("added").unwrap(), &Value::Array(vec![])); let written = json::loads(&fs::read_to_string(&settings).unwrap()).unwrap(); assert!(written.get("model").unwrap().is_str("x")); @@ -323,7 +413,7 @@ fn install_retires_the_per_command_hooks_it_used_to_write() { {"type": "command", "command": "keep-me"}]}]}}"#, ) .unwrap(); - let result = w.json(&["install"]); + let result = w.json(&["install", "--project"]); assert_eq!( result.get("removed").unwrap(), &json::loads(r#"["PreToolUse", "PostToolUse"]"#).unwrap() @@ -422,7 +512,12 @@ fn stopping_twice_for_one_prompt_is_one_turn() { w.write("a.py", "first = 1\n"); w.stop("p1"); w.write("a.py", "first = 1\nsecond = 2\n"); - // Claude Code stops again for the same prompt. + // Claude Code stops again for the same prompt, after saying more. + w.record(format!( + r#"{{"type": "assistant", "uuid": "p1-more", "parentUuid": "p1-end", "sessionId": "{}", "cwd": "{}", "timestamp": "2026-11-18T10:01:45.000Z", "message": {{"role": "assistant", "content": [{{"type": "text", "text": "and another"}}]}}}}"#, + SESSION, + s(&w.repo) + )); let out = w.loch_in(&w.repo, &["hook", "stop"], &w.event()); assert!(out.status.success()); let log = w.json(&["log", "a.py"]); @@ -794,3 +889,219 @@ fn the_hooks_collect_on_their_own_once_due() { // That prompt's snapshot made 50: the hook collected and reset the count. assert_eq!(fs::read_to_string(&counter).unwrap().trim(), "0"); } + +// -- install scopes ------------------------------------------------------------------ + +fn loch_line(name: &str, flags: &str) -> String { + format!("loch hook {}{} 2>/dev/null || true", name, flags) +} + +fn groups_of(path: &Path, event: &str) -> Vec { + let settings = json::loads(&fs::read_to_string(path).unwrap()).unwrap(); + settings + .get("hooks") + .unwrap() + .get(event) + .unwrap() + .as_array() + .unwrap() + .clone() +} + +fn first_command(group: &Value) -> String { + group.get("hooks").unwrap().as_array().unwrap()[0] + .get("command") + .unwrap() + .as_str() + .unwrap() + .to_string() +} + +#[test] +fn install_defaults_to_the_user_s_settings_and_keeps_their_hooks() { + let w = World::new(true); + let user = w.home.join(".claude/settings.json"); + fs::create_dir_all(user.parent().unwrap()).unwrap(); + fs::write( + &user, + r#"{"theme": "dark", "hooks": {"Stop": [{"hooks": [{"type": "command", "command": "their-own"}]}]}}"#, + ) + .unwrap(); + let installed = w.json(&["install"]); + assert!(installed.get("scope").unwrap().is_str("user")); + assert!(installed.get("settings").unwrap().is_str(&s(&user))); + assert!(installed.get("hookCommand").unwrap().is_str("loch")); + assert!(!w.repo.join(".claude").exists(), "nothing in the project"); + let written = json::loads(&fs::read_to_string(&user).unwrap()).unwrap(); + assert!(written.get("theme").unwrap().is_str("dark")); + let stop = groups_of(&user, "Stop"); + assert_eq!(first_command(&stop[0]), "their-own"); + assert_eq!(first_command(&stop[1]), loch_line("stop", " --scope user")); + + let again = w.json(&["install"]); + assert_eq!(again.get("added").unwrap(), &Value::Array(vec![])); + assert_eq!(again.get("replaced").unwrap(), &Value::Array(vec![])); + assert_eq!(groups_of(&user, "Stop").len(), 2); +} + +#[test] +fn install_follows_claude_config_dir() { + let w = World::new(true); + let account = w.root.join("account"); + let out = w + .command(env!("CARGO_BIN_EXE_loch"), &w.repo) + .env("CLAUDE_CONFIG_DIR", &account) + .args(["install", "--json"]) + .output() + .unwrap(); + let document = json::loads(String::from_utf8(out.stdout).unwrap().trim()).unwrap(); + let settings = account.join("settings.json"); + assert!(document.get("settings").unwrap().is_str(&s(&settings))); + assert!(settings.exists()); + assert!(!w.home.join(".claude/settings.json").exists()); +} + +#[test] +fn install_rewrites_only_its_own_line_and_in_place() { + let w = World::new(true); + let user = w.home.join(".claude/settings.json"); + fs::create_dir_all(user.parent().unwrap()).unwrap(); + // What an older loch, or another path to it, left: in the middle of + // someone else's hooks. + fs::write( + &user, + r#"{"hooks": {"Stop": [ + {"hooks": [{"type": "command", "command": "first"}]}, + {"hooks": [{"type": "command", "command": "/old/bin/loch hook stop 2>/dev/null || true"}]}, + {"hooks": [{"type": "command", "command": "last"}]}]}}"#, + ) + .unwrap(); + let installed = w.json(&["install"]); + assert_eq!( + installed.get("replaced").unwrap(), + &json::loads(r#"["Stop"]"#).unwrap() + ); + assert_eq!( + installed.get("added").unwrap(), + &json::loads(r#"["UserPromptSubmit", "SessionEnd"]"#).unwrap() + ); + let stop: Vec = groups_of(&user, "Stop").iter().map(first_command).collect(); + assert_eq!( + stop, + vec![ + "first".to_string(), + loch_line("stop", " --scope user"), + "last".to_string() + ] + ); +} + +#[test] +fn install_takes_one_scope() { + let w = World::new(true); + let out = w.loch(&["install", "--local", "--project", "--json"]); + assert_eq!(out.status.code(), Some(2)); + let document = json::loads(String::from_utf8(out.stdout).unwrap().trim()).unwrap(); + assert!(document.get("code").unwrap().is_str("usage")); +} + +#[test] +fn a_user_wide_hook_does_nothing_outside_a_repository() { + let mut w = World::new(false); + w.json(&["install"]); + w.fired = true; + w.prompt("p1", "somewhere that is not a project"); + w.write("a.txt", "anything\n"); + w.stop("p1"); + w.fire("SessionEnd", &w.event()); + assert!( + !w.home.join(".loch").exists(), + "no snapshot, state or record" + ); + assert!(!w.store.exists(), "no transcript copied to the store"); +} + +#[test] +fn a_user_wide_hook_records_in_a_repository() { + for commits in [true, false] { + // Without commits there is no root commit to name the project by, + // and it is still a project. + let mut w = World::new(commits); + if !commits { + w.git(&w.repo, &["init", "-q", "-b", "main"]); + } + w.json(&["install"]); + w.fired = true; + w.prompt("p1", "write it"); + w.write("a.txt", "the agent's line\n"); + w.stop("p1"); + assert_eq!(owners(&w.json(&["blame", "a.txt"])), vec![some("write it")]); + } +} + +#[test] +fn a_turn_is_recorded_once_beside_a_project_s_own_hooks() { + for (narrower, sequential) in [("--local", false), ("--local", true), ("--project", true)] { + let mut w = World::new(true); + w.sequential = sequential; + w.json(&["install"]); + // Ness's install: this worktree alone, with loch's absolute path. + w.json(&["install", narrower, "--command", env!("CARGO_BIN_EXE_loch")]); + assert_eq!(w.hook_commands("UserPromptSubmit").len(), 2); + w.fired = true; + w.prompt("p1", "first"); + w.write("a.txt", "one\n"); + w.stop("p1"); + w.prompt("p2", "second"); + w.write("b.txt", "two\n"); + w.stop("p2"); + assert_eq!(interrupted_flags(&w), vec![false, false], "{}", narrower); + assert_eq!(owners(&w.json(&["blame", "a.txt"])), vec![some("first")]); + assert_eq!(owners(&w.json(&["blame", "b.txt"])), vec![some("second")]); + } +} + +#[test] +fn install_removes_a_second_claude_loch_line() { + let w = World::new(true); + let user = w.home.join(".claude/settings.json"); + fs::create_dir_all(user.parent().unwrap()).unwrap(); + // What re-running an older install after loch moved left: two paths. + fs::write( + &user, + r#"{"hooks": {"Stop": [ + {"hooks": [{"type": "command", "command": "/a/loch hook stop 2>/dev/null || true"}]}, + {"hooks": [{"type": "command", "command": "theirs"}, + {"type": "command", "command": "/b/loch hook stop 2>/dev/null || true"}]}]}}"#, + ) + .unwrap(); + let installed = w.json(&["install"]); + assert_eq!( + installed.get("removed").unwrap(), + &json::loads(r#"["Stop"]"#).unwrap() + ); + let stop = groups_of(&user, "Stop"); + assert_eq!(stop.len(), 2); + assert_eq!(first_command(&stop[0]), loch_line("stop", " --scope user")); + assert_eq!(stop[1].get("hooks").unwrap().as_array().unwrap().len(), 1); + assert_eq!(first_command(&stop[1]), "theirs"); +} + +/// A genuine second `Stop` can arrive with the same payload and the transcript +/// not yet grown. Past the window it is an event of its own, not another +/// hook's copy of the first, and its edits are the turn's. +#[test] +fn an_identical_stop_after_the_duplicate_window_is_handled() { + let mut w = World::new(true); + w.prompt("p1", "two steps"); + w.write("a.py", "first = 1\n"); + w.stop("p1"); + w.write("a.py", "first = 1\nsecond = 2\n"); + std::thread::sleep(std::time::Duration::from_millis(2_500)); + let out = w.loch_in(&w.repo, &["hook", "stop"], &w.event()); + assert!(out.status.success()); + assert_eq!( + owners(&w.json(&["blame", "a.py"])), + vec![some("two steps"); 2] + ); +}