diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f1b9f0..cc7ff7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -Needs the lich release after v0.92.0, the first that answers `/subagent` and -sends the notification envelope. This release is a minor so that an older lich -never installs it. +Needs the lich release after v0.92.0, the first that answers `/subagent`, takes +the touched report's paths and sends the notification envelope. This release is +a minor so that an older lich never installs it. ### Added @@ -27,6 +27,23 @@ never installs it. native is lich's call. When lich does not answer within 10 seconds, or cannot be reached, the native subagent runs. Codex on Windows runs the hook through `hooks/win-veto.cmd`, which keeps the veto `win-run.cmd` would drop. +- **An edit says when another lich session wrote the same file minutes ago, on + every harness but opencode 2.** The touched report now names the files a + write touched, and lich answers with a note naming the other session when it + wrote one of them in the last ten minutes. The hook hands that note to the + model as written: Claude Code's and Cursor CLI's additionalContext, Codex's + (on Windows through `hooks/win-veto.cmd`), Crush's `context` from v0.99.0, + where the report moves to `PostToolUse`, opencode's tool output and oh-my-pi's + additionalContext. Antigravity and Kiro CLI, whose post-write hooks cannot + show text, hold it until their next `PreInvocation` or `userPromptSubmit`. + It replaces the Claude Code mod's edit guard, and the plugin writes no text + of its own. + +### Fixed + +- **Antigravity 1.5.15 edits refresh the card again.** It writes with + `write_file` and `edit_file`, which the touched matcher did not name; it now + names them beside the older `write_to_file` and `replace_file_content`. ### Removed @@ -37,6 +54,13 @@ never installs it. off its final message itself. Their texts in every prompt language go with them, and so does the worker count in the prompt footer, which the errands already counted. +- **The Claude Code mod is gone; the plugin is hooks and skills.** lich no + longer drives a Claude Code terminal session through it (`lich control` and + `ask_session` there, and its prompts delivered as a task notification), the + session no longer reports its own usage or a compaction, the footer line of + errands and the self-run `/compact` are gone, and its texts in seven prompt + languages with them. The edit guard became the hook above. lich's chat, which + drives Claude Code through stream-json, never ran the mod and loses nothing. ## [0.21.1] - 2026-11-13 diff --git a/CLAUDE.md b/CLAUDE.md index 8a4a157..3cd514d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,15 +19,7 @@ hooks/detail.jq # what a tool call acts on, shared by two of t hooks/conversation-id.sh # the conversation a payload comes from, sourced by four of them hooks/veto-subagent.sh # the subagent veto: the one hook that blocks, waiting on lich's answer hooks/win-run.cmd # runs one of those scripts on Windows (Codex) -hooks/win-veto.cmd # runs veto-subagent.sh on Windows (Codex), keeping the stdout its veto rides -hooks/lich.js # the one module hooks/hooks.json names under `modules`: registers the mods below -hooks/mod-control.js # Claude Code mod: lich drives the session -hooks/mod-usage.js # Claude Code mod: the session reports its own context, rate limits and cost -hooks/edit-guard.js # Claude Code mod: an edit says which other lich session edited the file -hooks/mod-status.js # Claude Code mod: the session's relay errands in the prompt footer -hooks/mod-compacting.js # Claude Code mod: the card says when the conversation is being compacted -hooks/self-command.js # Claude Code mod: the session runs a built-in slash command the user asked for -hooks/status-line.js # the lich line in the prompt footer, shared by the mods above +hooks/win-veto.cmd # runs a hook whose stdout is an answer (the veto, the edit note) on Windows (Codex) opencode/lich.js # opencode client: a module, not a command omp/lich.js # omp client: a module, not a command docs/ # lich ⇄ plugin communication contracts @@ -53,24 +45,20 @@ no commands: a plugin there is a JavaScript module its server imports, so all four reports live in `opencode/lich.js`. **omp** has a `--hook` flag but merges it with `--extension` into one list it `import()`s, so its "hooks" are modules too, and its client is `omp/lich.js`. **Crush** runs the scripts unchanged — its -hooks are Claude Code-compatible down to the stdin payload — but has exactly one -event, `PreToolUse`, so only the session id and the touched refresh are -registered for it, plus the subagent veto, which needs no end of turn. +hooks are Claude Code-compatible down to the stdin payload — but before +v0.99.0 had exactly one event, `PreToolUse`, so only the session id, the +touched report (on `PostToolUse` from v0.99.0) and the subagent veto are +registered for it: none of them needs an end of turn. ## Contracts Contracts are **canonical in the lich repository** (`docs/hooks/` there); this plugin only implements the client side. Each hook has a doc in `docs/` here that points at its contract and describes the plugin-side behavior. Read it before creating or changing a hook: -- [docs/session-state.md](docs/session-state.md) — session-state reporting (`busy`/`done`) via `UserPromptSubmit`/`Stop`, the tool a turn is running via `PreToolUse`, and `compacting` through a mod bracketing `session.compact` (Claude Code only) +- [docs/session-state.md](docs/session-state.md) — session-state reporting (`busy`/`done`) via `UserPromptSubmit`/`Stop` and the tool a turn is running via `PreToolUse` - [docs/session-start.md](docs/session-start.md) — Claude session id via `SessionStart` - [docs/session-title.md](docs/session-title.md) — the provider's own session title, via `PostToolUse`/`PreInvocation` and `Stop` -- [docs/session-touched.md](docs/session-touched.md) — git-status refresh signal via `PostToolUse` (file-mutating tools only) -- [docs/mod-control.md](docs/mod-control.md): lich drives a Claude Code session (prompt, abort, model, effort, command) and asks it side questions (ask) through a mod that long-polls for commands and acks each one; Claude Code only, the other harnesses have no mod system -- [docs/mod-usage.md](docs/mod-usage.md): a Claude Code session reports the context window, rate limits and cost it measured itself, through a mod hooking `session.measure`; Claude Code only -- [docs/mod-status.md](docs/mod-status.md): a Claude Code session shows the relay errands it is part of (owed, out, ready) in its prompt footer, through a mod reading `/mod/status`, which never collects; Claude Code only -- [docs/self-command.md](docs/self-command.md): a Claude Code session runs a built-in slash command the user asked it for (`/compact`), queued after the turn, through a mod answering the Skill tool's refusal of a built-in, and lich's `control_session` refusal of the session's own, by queueing the command itself; Claude Code only +- [docs/session-touched.md](docs/session-touched.md) — git-status refresh signal via `PostToolUse` (file-mutating tools only), naming the files written, and lich's edit-overlap note handed to the model (held and collected where the post-write hook cannot show text) - [docs/subagent-cards.md](docs/subagent-cards.md): the agent's own subagent call becomes a lich session, through a pre-tool hook that asks `/subagent` and turns lich's deny into the harness's veto; every harness but opencode 2, Kiro CLI through lich's own registration -- [docs/edit-guard.md](docs/edit-guard.md): an edit to a file another lich session edited in the last minutes carries a note naming it, through markers in the checkout's git dir rather than an HTTP contract; Claude Code only - [docs/providers.md](docs/providers.md) — the per-harness map, including what installing on omp takes and what it cannot report Each doc carries the event mapping for **every** provider, one column each — a contract is implemented once and registered per harness. [docs/providers.md](docs/providers.md) is the map: which file each harness reads, where the event vocabularies differ, and what adding another provider takes. A harness that cannot close a state does not get that report registered: an unendable `busy` is worse on a card than a card with no indicator. @@ -103,40 +91,19 @@ drop and the listener that never answers, which must not hold the turn. against the events and `ctx.sessionManager` methods measured on omp v17.3.0 — pinned in a comment there, because 17.x moves fast — plus the rule that outside lich it subscribes to nothing at all. -[tests/mod-control.test.mjs](tests/mod-control.test.mjs) does the same for the -Claude Code mod, handing it a fake `$` and asserting its acks against the -mod-control fixtures and its polls against the commands lich sends; -[tests/mod-usage.test.mjs](tests/mod-usage.test.mjs) does the same for its -usage reports against the mod-usage fixtures, -[tests/mod-status.test.mjs](tests/mod-status.test.mjs) for the footer line it -draws from the mod-status response, and -[tests/mod-compacting.test.mjs](tests/mod-compacting.test.mjs) for the -`compacting` bracket against the session-state fixtures. -[tests/edit-guard.test.mjs](tests/edit-guard.test.mjs) hands the edit guard a -fake `$` with an in-memory git dir and asserts the markers it leaves and the -note another session's marker adds, and -[tests/status-line.test.mjs](tests/status-line.test.mjs) that the mods share -one lich line in the prompt footer. -[tests/self-command.test.mjs](tests/self-command.test.mjs) does the same for -the self-command mod: which Skill calls it takes, that the command runs only -after the call is answered, and that `/model` and `/effort` never run. [tests/subagent.test.mjs](tests/subagent.test.mjs) runs every harness's subagent veto, the script as each registration spells it and the two modules in process, against a stub answering with the subagent-cards fixture's answers: the body each sends for its own call, the veto each turns a deny into with the reason untouched, and the allow every failure is. +[tests/touched.test.mjs](tests/touched.test.mjs) does the same for the +touched report: the paths each harness sends for its own write, `hold` and +`collect` where the post-write hook cannot show text, and every note the +session-touched fixture answers with, handed to the model in that harness's +shape, byte for byte. [tests/contract.mjs](tests/contract.mjs) is the fixtures, the assertions and the stub, shared so every client answers to the same lines. Node only, no dependencies. -[tests/mod-control.engine.test.ts](tests/mod-control.engine.test.ts) and -[tests/mod-usage.engine.test.ts](tests/mod-usage.engine.test.ts) and -[tests/mod-status.engine.test.ts](tests/mod-status.engine.test.ts) and -[tests/edit-guard.engine.test.ts](tests/edit-guard.engine.test.ts) and -[tests/self-command.engine.test.ts](tests/self-command.engine.test.ts) run the -mods under Claude Code's own engine (`claude plugin test .`); they need a -`claude` binary, so CI does not run them. The kit does not check a `tool.call` -result against the tool's output schema (measured on 2.1.289), so whether -Claude Code accepts a mod's tool result is a live run's to answer. The fixtures are vendored in `tests/fixtures/` from lich (`docs/hooks/fixtures/*.jsonl` there) by @@ -159,7 +126,7 @@ commit it pins until a release ships it. - Outside lich (env vars absent) every hook is a no-op with exit 0 — the plugin must be safe to install globally. - A skill must be useful from any working directory: the user runs the agent CLI on their own project, not on the lich checkout. - One script per contract, shared by every provider that runs commands. Registration differs per harness, the report does not — extend a script to read a second transcript format before adding a second script. A harness that runs no commands at all is the one case for a client of its own, which is what `opencode/lich.js` and `omp/lich.js` are; they still send the same payloads to the same endpoints. -- opencode and omp both await their plugin handlers, so neither `lich.js` ever awaits a report or throws — that is their version of "always exit 0". The subagent veto is the exception in both, as in the scripts: it awaits lich's answer, and a deny is how each refuses the call (opencode by throwing, omp by returning `{block: true}`). The omp one also subscribes to nothing outside lich: omp loads it on every run on the machine, so the gate has to be in the module. +- opencode and omp both await their plugin handlers, so neither `lich.js` ever awaits a report or throws — that is their version of "always exit 0". The subagent veto and the touched report are the exceptions in both, as in the scripts: each awaits lich's answer, because the answer is what the model reads (a deny refuses the call, opencode by throwing and omp by returning `{block: true}`; an edit note goes back with the write's result). The omp one also subscribes to nothing outside lich: omp loads it on every run on the machine, so the gate has to be in the module. - **A module client names only events it was measured emitting.** A name read off a type declaration is a report that silently never fires, which is worse than an absent feature — the omp `waiting` state is left unreported for exactly this reason. - **The same goes for every other name a registration carries** — an event, a tool a matcher names, a payload field, a plugin-root variable. All of them fail the same way: quietly, on every event, with a green test suite, because a harness that never runs the hook reports nothing to disagree with. - **A name is measured off a real payload, or it is a guess.** Not from a harness you already support, and not from a symbol table or an enum either — those are the *implementation's* names, and something may map them before they reach a hook. Antigravity is the worked example in both directions: its guide says a tool name is the step type lowercased with `CORTEX_STEP_TYPE_` dropped, and the enum's `MCP_TOOL` still arrives as `call_mcp_tool`. Its write tools really are `write_to_file` and `replace_file_content`, which the enum does not contain. Run the turn, print the payload, read the name off it — a matcher built any other way matches nothing, and losing a report costs no error, only the report. @@ -169,8 +136,7 @@ commit it pins until a release ships it. ```bash claude --plugin-dir . -claude plugin validate .claude-plugin/plugin.json # the manifest, hooks.json and the mod -claude plugin test . # the mod under Claude Code's engine +claude plugin validate .claude-plugin/plugin.json # the manifest and hooks.json ``` Codex has no equivalent one-shot flag; install the clone as a local marketplace instead (`codex plugin marketplace add .` then `codex plugin add lich@lich-plugin`), and trust the hooks once with `/hooks`. @@ -186,6 +152,6 @@ Same standard as the `lich` repository (Keep a Changelog + SemVer). Releases are 1. Move the `[Unreleased]` entries in `CHANGELOG.md` under the new version heading (with date) and refresh the compare links at the bottom. 2. Pick the number by what changed: a release that sends anything lich's contract did not already accept (a new endpoint, header, field or value) bumps the **minor** (the major, from 1.0); anything else bumps the **patch**. lich accepts every release below the next minor of the contract it implements, so a contract change released as a patch reaches a lich that refuses it. A contract change is tagged here once lich has merged it and before the lich release that installs it, since that lich may fetch files only this release ships; an older lich never picks it up, because its ceiling stops below this minor. `docs/hooks/README.md` in lich, Versioning, is the rule. -3. Align `version` in `.claude-plugin/plugin.json` **and** `.codex-plugin/plugin.json` with the tag, and `plugin_version` in each `hooks/report-*.sh` and in `hooks/veto-subagent.sh`, and `PLUGIN_VERSION` in `opencode/lich.js`, `omp/lich.js`, `hooks/mod-control.js`, `hooks/mod-usage.js`, `hooks/mod-status.js`, and `hooks/mod-compacting.js`, the header every report sends. The suite fails while any of them disagrees with the Claude Code manifest. The root `plugin.json` is not a third one to bump: Antigravity's manifest takes only a `name`, and lich writes its own carrying the tag when it installs a release. +3. Align `version` in `.claude-plugin/plugin.json` **and** `.codex-plugin/plugin.json` with the tag, and `plugin_version` in each `hooks/report-*.sh` and in `hooks/veto-subagent.sh`, and `PLUGIN_VERSION` in `opencode/lich.js` and `omp/lich.js`, the header every report sends. The suite fails while any of them disagrees with the Claude Code manifest. The root `plugin.json` is not a third one to bump: Antigravity's manifest takes only a `name`, and lich writes its own carrying the tag when it installs a release. 4. Annotated tag `vX.Y.Z` + push with the tag. 5. `gh release create vX.Y.Z` with the notes taken from the matching `CHANGELOG.md` section. diff --git a/README.md b/README.md index 6ea94bc..77b4262 100644 --- a/README.md +++ b/README.md @@ -5,10 +5,10 @@ The agent side of the [lich](https://github.com/lichdotdev/lich) integration. li - **session state** — `busy`/`done` on the session card (`UserPromptSubmit`/`PreInvocation`/`Stop`) - **session start** — persists the agent's session id on the lich session (`SessionStart`/`PreInvocation`) - **session title** — names the card after the session's own title (`Stop`) -- **session touched** — refreshes the card's git status right after file-mutating tools (`PostToolUse`) +- **session touched** — refreshes the card's git status right after file-mutating tools, and hands the model lich's note when another session wrote the same file minutes ago (`PostToolUse`) - **subagent cards** — turns the agent's own subagent call into a lich session, asking lich before the tool runs (`PreToolUse`, or the module's pre-tool event) -The four reports are what Claude Code, Codex, Antigravity, opencode and omp send. **Crush reports two of them** — its session id and the git-status refresh — because `PreToolUse` is the only event it has, and a state nothing can end is worse on a card than no state. **omp reports all four minus the bell**: no event of its own for "your turn" has been measured yet, so its card shows a spinner while the agent waits on you. [docs/providers.md](docs/providers.md) has the event mapping per harness. +The four reports are what Claude Code, Codex, Antigravity, opencode and omp send. **Crush reports two of them** — its session id and the git-status refresh (on `PostToolUse` from Crush v0.99.0, with the edit note) — and no state: none of its newer turn events was measured yet, and a state nothing can end is worse on a card than no state. **omp reports all four minus the bell**: no event of its own for "your turn" has been measured yet, so its card shows a spinner while the agent waits on you. [docs/providers.md](docs/providers.md) has the event mapping per harness. On **opencode** under a lich from before it registered its MCP server there, it also carries the other direction: the operations lich offers a session for @@ -17,18 +17,6 @@ opencode that server at spawn, as it does Claude Code and Codex, and the module then defines none. [docs/opencode-tools.md](docs/opencode-tools.md) has the list and the cases where they are deliberately absent. -On **Claude Code** it carries the other direction too, from lich to the session: -a mod, a module Claude Code runs in its own process, takes the commands given -with `lich control` or an agent's `control_session` tool (start a turn with a -prompt, stop the running turn, override the model or the effort, run a slash -command), answers a side question asked with `lich ask` or `ask_session` from a -fork of the session's conversation without stopping its turn, and reports how -each one went. It needs Claude Code 2.1.280 or later -with mods turned on; an older one keeps every report above, and `lich control` -refuses its session, naming what to fix. -[docs/mod-control.md](docs/mod-control.md) has what it does and which releases -run it. No other harness has a mod system, so none of them gets the controls. - On every harness here but opencode 2, and on Kiro CLI through lich's own registration, the agent's **subagent call** becomes a lich session: before the tool runs, the plugin asks lich, which opens the task as a card you can watch @@ -38,11 +26,11 @@ report arrives at the asking session's prompt on its own as a such as the read-only explorers, is lich's call, and when lich cannot be reached the native subagent runs. [docs/subagent-cards.md](docs/subagent-cards.md) has the veto per harness. Since a card shares the checkout unless the call asked -for a worktree, an edit to a file another lich session edited in the last ten -minutes tells the model which session it was and how to reach it -([docs/edit-guard.md](docs/edit-guard.md)). Asked to run a built-in slash command -such as `/compact`, the session runs it on itself once its turn ends -([docs/self-command.md](docs/self-command.md)). +for a worktree, the touched report names the files a write touched, and when +another lich session wrote one of them in the last ten minutes, lich answers +with a note naming it that the hook hands to the model; on Antigravity and Kiro +CLI, whose post-write hooks cannot show text, it arrives before the next model +call or with the next prompt ([docs/session-touched.md](docs/session-touched.md)). It also ships skills for the parts of lich you configure from inside a session: @@ -67,12 +55,6 @@ hooks/report-session-start.sh # session-start hook hooks/report-title.sh # session-title hook hooks/report-touched.sh # session-touched hook hooks/veto-subagent.sh # subagent-cards hook: lich's veto on a subagent call -hooks/lich.js # the Claude Code mods' entry, which registers the five below -hooks/mod-control.js # mod-control client, a Claude Code mod -hooks/mod-usage.js # mod-usage client, a Claude Code mod -hooks/edit-guard.js # names the other lich session that edited a file, a Claude Code mod -hooks/mod-status.js # mod-status client: the session's errands in the prompt footer, a Claude Code mod -hooks/self-command.js # runs a built-in slash command the user asked the session for, a Claude Code mod opencode/lich.js # opencode client: all four reports, the subagent veto and the seven tools, one module omp/lich.js # omp client: the reports and the subagent veto, one module docs/ # client-side docs, one per contract @@ -151,7 +133,10 @@ Crush has no plugin system either: its hooks live in your own `crush.json`. Clon "hooks": { "PreToolUse": [ { "name": "lich session id", "command": "/home/you/src/lich-plugin/hooks/report-session-start.sh crush", "timeout": 5 }, - { "name": "lich git-status refresh", "matcher": "^(edit|write|multiedit|bash)$", "command": "/home/you/src/lich-plugin/hooks/report-touched.sh", "timeout": 5 } + { "name": "lich subagent cards", "matcher": "^agent$", "command": "/home/you/src/lich-plugin/hooks/veto-subagent.sh crush", "timeout": 15 } + ], + "PostToolUse": [ + { "name": "lich git-status refresh", "matcher": "^(edit|multiedit|write|bash)$", "command": "/home/you/src/lich-plugin/hooks/report-touched.sh", "timeout": 5 } ] } } @@ -195,4 +180,4 @@ claude --plugin-dir . node --test tests/*.test.mjs ``` -Every hook script runs as a real subprocess, from the command line its registration spells, against a stub HTTP server — and the body it POSTs is asserted against [lich's contract fixtures](https://github.com/lichdotdev/lich/tree/main/docs/hooks/fixtures): an accepted shape, never a rejected one, the right endpoint, token and `X-Lich-Plugin` header, plus the client rules (no lich environment → no report; exit 0 when lich answers 500 or refuses the connection). The opencode and omp modules and the Claude Code mod are imported instead of spawned and fed the events a real run of each emits, against the same fixtures. All of them share `tests/contract.mjs`. The fixtures are vendored in `tests/fixtures/` by `tests/refresh-fixtures.sh`, at the lich release named in `tests/lich-ref`; CI diffs them against that release so a contract that moves in lich goes red here. +Every hook script runs as a real subprocess, from the command line its registration spells, against a stub HTTP server — and the body it POSTs is asserted against [lich's contract fixtures](https://github.com/lichdotdev/lich/tree/main/docs/hooks/fixtures): an accepted shape, never a rejected one, the right endpoint, token and `X-Lich-Plugin` header, plus the client rules (no lich environment → no report; exit 0 when lich answers 500 or refuses the connection). The opencode and omp modules are imported instead of spawned and fed the events a real run of each emits, against the same fixtures. All of them share `tests/contract.mjs`. The fixtures are vendored in `tests/fixtures/` by `tests/refresh-fixtures.sh`, at the lich release named in `tests/lich-ref`; CI diffs them against that release so a contract that moves in lich goes red here. diff --git a/docs/edit-guard.md b/docs/edit-guard.md deleted file mode 100644 index 93c4ac5..0000000 --- a/docs/edit-guard.md +++ /dev/null @@ -1,91 +0,0 @@ -# Mod: edit guard - -Tells a Claude Code session inside lich that the file it just edited was also -edited, minutes earlier, by another lich session working in the same checkout. -There is no lich contract behind it: the sessions meet in the checkout's git -dir, and nothing is sent to lich. - -| client | Claude Code | Codex | Antigravity | opencode | omp | Crush | -|-----------------------|---------------------------------------------------------|---------------------|---------------------|---------------------|---------------------|---------------------| -| `hooks/edit-guard.js` | mod, registered by `hooks/lich.js`, the `modules` entry | none: no mod system | none: no mod system | none: no mod system | none: no mod system | none: no mod system | - -## Why - -A subagent lich opens as a card ([subagent-cards.md](subagent-cards.md)) works -in the asking session's checkout by default, so two Claude Code sessions can -edit the same file at once. Each one only sees the other's change when it reads -the file again, and neither knows who made it or that the other may still be at -work on it. - -## What Claude Code already does - -Measured on Claude Code 2.1.289 (`--model haiku`, a scratch git repository): a -session read four files, another process then changed each of them, and the -session edited them without reading again. - -| tool | result | -|-----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `Edit`, `old_string` still in the file | applied, the other change kept: `The file … has been updated successfully. (note: the file had been modified on disk since you last read it — the edit applied cleanly, but the file contains other changes not in your context. Read it before edits that depend on surrounding content.)` | -| `Edit`, `old_string` changed by the other side | refused: `File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.` | -| `Write` | refused, same message | -| `NotebookEdit` | refused, same message | - -`MultiEdit` is not a tool in that release. So Claude Code never overwrites a -change it has not read: the guard denies nothing, and only adds who made the -change. - -## How it behaves - -It hooks `tool.call` on `Edit`, `Write` and `NotebookEdit`, and does nothing -unless `LICH_SESSION_ID` is set. - -1. Before the call it asks git for the git dir of the folder holding the file - (`git -C rev-parse --absolute-git-dir`, the worktree's own for a - linked worktree). Outside a repository it stops here. -2. It reads `/lich-edits/`, the marker the last - session to edit that file left: `{"path", "session", "at"}`, `at` in epoch - milliseconds. -3. It runs the call. A `deny` from a hook beneath is passed on as it came. -4. When the call succeeded, it writes its own marker over that one. -5. When the marker named a different lich session and is under 10 minutes old, - the result goes back with one more `context` line, which the model reads - after the tool's result: the path, the session, the time and how long - ago, and that `send_to_session` or `lich send` reaches that session. A - refused call carries the line too, since it explains the refusal. -6. The same edit puts ` also edited by ` in the lich line - of the prompt footer, for the user, who never reads the `context` line. - It stays until the marker leaves the 10-minute window, or a newer one - replaces it. The line is shared with the other mods through - `hooks/status-line.js` ([mod-status.md](mod-status.md), What the line reads). - -The line names the session by the label on its card, the name the user and -`lich send` know it by. lich puts no label in a session's environment and no -command tells a session its own, so the marker keeps the id and the label is -looked up when a line is about to be added, never on an edit that gets none: -`$LICH_BIN sessions --json`, two seconds at most, matched on its `id` field -(lich 0.60.0 and later). When the CLI is missing or fails, the session is -gone, or the lich is older and lists no ids, the line names the id -instead. - -Ten minutes spans the turn in which the other session made its edit; past that -the work is likely finished and the file as read is the news. - -A failure of the guard itself (git, a marker it cannot read or write) is logged -with `$.ui.log`, a dim line in the transcript, and the edit goes on as if the -guard were not there. - -## Limits - -- It speaks only after the edit. The `context` of a `tool.call` result is read - with the tool's result; there is no slot to warn before the call runs. The - refusals above are what keep the edit safe. -- A lich older than 0.60.0 lists no session ids in `lich sessions --json`, so - there the line names the session by id. -- One marker per file, the last editor's: two other sessions editing the same - file leave only the newer one's name. -- A file in a folder that does not exist yet is outside any repository to git, - so a `Write` creating a new folder is not recorded. -- Edits made by `Bash` (`sed -i`, a formatter) are not seen, nor are edits by - harnesses other than Claude Code, which have no mod system. -- Markers are never cleaned up; each is a few hundred bytes, one per file a - lich session edited, under the git dir where git ignores it. diff --git a/docs/mod-control.md b/docs/mod-control.md deleted file mode 100644 index 343dd96..0000000 --- a/docs/mod-control.md +++ /dev/null @@ -1,149 +0,0 @@ -# Mod: control - -Client side of the [mod-control contract](https://github.com/lichdotdev/lich/blob/main/docs/hooks/mod-control.md) -(the endpoints, the commands and the ack are defined in the lich repository; -this plugin only implements them). - -Lets lich drive a Claude Code session, through `lich control` on the command -line or the `control_session` MCP tool an agent calls: start a turn with a -prompt, stop the running turn, override the model or the effort of every -request, and run one of its slash commands; and ask it a side question it -answers without stopping, through `lich ask` or the `ask_session` MCP tool. It -runs the other way from the -hooks: instead of reporting what happened, it holds a long poll open on lich, -applies the commands that come back, and acks each one. - -| client | Claude Code | Codex | Antigravity | opencode | omp | Crush | -|------------------------|-------------------------------------------------------|---------------------|---------------------|---------------------|---------------------|---------------------| -| `hooks/mod-control.js` | mod, registered by `hooks/lich.js` (`hooks/hooks.json` `modules`) | none: no mod system | none: no mod system | none: no mod system | none: no mod system | none: no mod system | - -A Claude Code mod is a module Claude Code runs inside its own process, listed -under `modules` in the same `hooks/hooks.json` that registers the scripts. Both -kinds live in one file and both fire. Claude Code takes one entry there, so the -entry is `hooks/lich.js`, which registers this module and the other mods. -lich refuses to queue a command for a -session whose mod is not polling, so on every other harness `lich control` and -`control_session` fail at once, naming what to fix, instead of waiting on -nothing. - -| command | applied with | ack `ok: true` once | -|-----------|--------------------------------------|-----------------------------------------| -| `prompt` | `$.prompt.submit({ text })`, or with `notification` `$.prompt.submit({ text: , asUser: true })` | its turn started | -| `abort` | `$.turn.abort({ turnId })`, the id `turn.start` gave | the turn ended | -| `model` | every `turn.step` sent with `model` | the override is set, or dropped when absent | -| `effort` | every `turn.step` sent with `effort` | the override is set, or dropped when absent | -| `command` | `$.command.run({ command: name, args })` | it ran, once the session was idle | -| `ask` | `$.model.fork({ prompt })`, the question behind a preamble | the fork answered; `answer` carries it | - -`GET /mod/commands?token=…&session_id=…` to fetch, `POST /mod/acks` with -`{"session_id", "id", "kind", "ok", "error"?, "answer"?}` to ack, `X-Lich-Plugin` on both. - -## How it behaves - -- **Outside lich it never polls.** It reads the three variables in - `session.start` and stops there when one is missing. Its `turn.step` hook - still runs on every request and passes it on unchanged. -- **Only an interactive session polls.** A `claude -p` with a parked poll stays - open until the poll returns, up to 25 seconds after its turn ended, and one run - from a tool inside a lich session inherits that session's variables, so it - would also take the parent's commands. `session.start` says which one it is - (`isInteractive`). -- **Polling never waits on a command.** Commands are applied one after another, - apart from the poll, which goes out again at once. A `prompt` resolves only - when the session is idle and its turn starts, and lich stops queueing for a - mod that has not polled in 30 seconds: a poll held behind that prompt would - get the abort meant for the running turn refused. -- **Nor does a command wait on a `prompt` or a slash command.** The prompt is - submitted in its place and acked when its turn starts, and a `command` is - acked once Claude Code ran it, which is only when the session is idle. What - comes after either runs at once: an `abort` held behind a prompt, or a - `/compact` queued during a turn, would reach the running turn only after that - turn ended, and behind a prompt it would then cancel the prompt's own turn - instead. A `model` or `effort` sent meanwhile likewise applies to the running - turn's next request. -- **An `ask` waits on nothing and nothing waits on it.** A fork runs beside the - turn and can take over a minute (measured at 109 seconds for a long answer on - 2.1.289), so it starts the moment its poll returns and acks whenever it - answers, outside the order the other commands keep. Several run at once. -- **A prompt with a `notification` reads like a background agent's - completion.** It is submitted as the user in the shape Claude Code gives its - own: `` with ``, `` and the prompt's text - as ``, no task id. Claude Code shows the summary as one dim line, and - the model reads the text and starts its turn (measured on 2.1.289). Status and - summary are XML-escaped, which Claude Code decodes for the line; the text is - not, because the model reads it as written and an escaped `&&` would reach it - as `&&`. -- **The question goes behind a preamble.** It says the question is a side one, - that the answer stays out of the conversation, and that tools are unavailable. - Without it, a fork made mid-turn reaches for a tool, is refused, and answers - in a second request: twice the latency and the uncached tokens (measured on - 2.1.289). -- **An answer is cut at 16,000 UTF-16 units**, with `\n[truncated]` after it, - which keeps the ack under lich's 64 KiB body limit. A fork that does not - answer acks `ok: false` with its reason: `nothing-to-fork`, - `api-error `, `empty-reply` or `aborted`. -- **Every other ack is awaited before the next command.** That is the - contract's rule for an `abort`: lich ends the turn it has open when the ack - lands, so a late one would end the turn the next `prompt` opened. An ack that - cannot be sent is dropped, and the next command runs. -- **An effort outside `low`, `medium`, `high`, `xhigh` and `max` is refused** - (`unknown effort`). Claude Code would take it and fail the hook only at the - next model request, long after an `ok` ack. A model name has no such check - before a request uses it, so it is acked as set. -- **A `404` stops polling for the session**, a network error or a `5xx` backs off - 1 second doubling to 10, and a `200` resets it. Any other status backs off the - same way rather than poll in a tight loop. -- **A kind it does not know is acked `ok: false`, `unknown kind`**, its kind - echoed so a lich newer than the plugin hears of it. - -## Which Claude Code runs it - -Measured against a stub lich on each release: - -- **2.1.280 and later** load and run the module. -- **2.1.260 to 2.1.278** load the plugin and skip the module: the switch Claude - Code rolls mods out under (`tengu_plugin_hooks_modules`) is off for installed - plugins there. -- **2.1.250** knows mods with an older event set: `claude plugin validate` - fails on `session.start`, but a session loads the plugin and skips the module. -- **2.1.200** ignores the `modules` key. - -On every one of them the scripts keep reporting as before. What an older Claude -Code loses is the controls: `lich control` and `control_session` refuse the -session, naming what to fix. The same happens on a current one when the rollout switch is off: it is -a server-side flag Claude Code caches on disk, and an older `claude` run under -the same home can save it off for the next session. - -A mod also loads only once the folder is trusted. The scripts register before -the trust prompt is answered, the module after. - -## Known ceilings - -- **Overrides live in the module.** A reload of the module (a new plugin - release, a hot reload while developing) starts it fresh, with no model or - effort override and without telling lich. The reload itself cancels a parked - poll, so lich's "client gone" path covers it. -- **The classic hooks do not see the effort override.** `Stop`'s payload still - names the session's own effort. The transcript's assistant rows carry the one - the request used. -- **An effort sent to a model without effort is dropped by Claude Code**, and - the ack still says `ok`: the override is set, it just changes nothing for that - model. -- **A slash command that opens a dialog never acks until someone closes it.** - Measured on 2.1.288 and 2.1.289: `/cost` holds Claude Code's command queue - until Esc is pressed in the session's terminal, and every later slash command - waits behind it. `abort`, `model` and `effort` still apply, since the mod - does not wait on a `command`, and a dialog opens only on an idle session, so - there is no turn behind it to abort. -- **`/model` and `/effort` are refused by lich, not by the mod.** Run through a - mod, Claude Code saves what they set as the default for every new session; - the `model` and `effort` commands are the per-session route. -- **A fork sees the conversation as of the session's last finished model - response.** A reply being written, a tool call running, or a prompt whose - first reply is still being written is not in it. Measured on 2.1.289. -- **A fork cannot be cancelled, and survives an Esc on the turn.** It takes no - signal; measured on 2.1.289, it answered in full after the turn it ran beside - was interrupted. A module reload is what kills one, and then nothing is acked: - lich's wait runs out. -- **A fork's tokens are not in the transcript**, so nothing that reads cost - from it counts an `ask`. diff --git a/docs/mod-status.md b/docs/mod-status.md deleted file mode 100644 index e39af21..0000000 --- a/docs/mod-status.md +++ /dev/null @@ -1,59 +0,0 @@ -# Mod: status - -Client side of the [mod-status contract](https://github.com/lichdotdev/lich/blob/main/docs/hooks/mod-status.md) -(the endpoint and the response are defined in the lich repository; this plugin -only implements them). - -Shows, in the prompt footer, the relay errands the session is -part of: who it owes an answer, the tasks it handed out that are still running, -and the answers waiting to be collected. The card shows these in the window; -this puts them in front of the person at the terminal. - -| client | Claude Code | Codex | Antigravity | opencode | omp | Crush | -|-----------------------|---------------------------------------------------------|---------------------|---------------------|---------------------|---------------------|---------------------| -| `hooks/mod-status.js` | mod, registered by `hooks/lich.js`, the `modules` entry | none: no mod system | none: no mod system | none: no mod system | none: no mod system | none: no mod system | - -| when | read | -|---------------------------------------------|----------------------------------------------------------| -| `session.start`, then every 5 seconds | `GET /mod/status?token=…&session_id=…`, `X-Lich-Plugin` | - -## What the line reads - -Each list that is not empty adds a piece, in this order, joined by commas: - -| list | piece | -|---------|-----------------------------------------------------------------------------------------| -| `owed` | `owes "Session 26" an answer` for one asked by a session, `owes N answers` otherwise | -| `open` | `N tasks out`, plus `(M waiting)` for those whose session waits on a human | -| `ready` | `N answers to collect` | - -The line reads `lich: 1 task out, 1 answer to collect`. With all three lists -empty the piece is gone. - -The mods share one lich line, built by `hooks/status-line.js`: the errands, -then the note of [edit-guard.md](edit-guard.md), joined by ` · `. The line is drawn dim among the mode -labels at the right of the prompt footer, by a `ui.render` hook on -`SessionMode` that adds it after Claude Code's own labels. `$.ui.status` is -not used: Claude Code draws it as a yellow warning under the prompt, and keeps -only one per plugin. - -## How it behaves - -- **Outside lich it never reads.** It reads the three variables in - `session.start` and stops there when one is missing. -- **Only an interactive session reads.** A `claude -p` run from a tool inside a - lich session inherits that session's variables, and would show the parent's - errands. Its `session.start` hook matches `isInteractive: true`. -- **Reading never collects.** An answer under `ready` stays in the inbox for - the agent's `wait_for_answer`. -- **A failed read is not retried.** The piece is cleared until a read works - again, 5 seconds later. -- **A `404` stops the reads for the session**: that lich predates the contract. - -## Limits - -- **Up to 5 seconds late.** lich pushes nothing; an errand that opens or - closes shows at the next read. -- **Labels are the ones at send time**, as lich keeps them. -- **Claude Code only.** Every other harness has no mod system; there the card - is the only place these errands show. diff --git a/docs/mod-usage.md b/docs/mod-usage.md deleted file mode 100644 index cb9acd9..0000000 --- a/docs/mod-usage.md +++ /dev/null @@ -1,48 +0,0 @@ -# Mod: usage - -Client side of the [mod-usage contract](https://github.com/lichdotdev/lich/blob/main/docs/hooks/mod-usage.md) -(the endpoint and the payload are defined in the lich repository; this plugin -only implements them). - -Reports what a Claude Code session measured about itself, the figures its -status line draws: the context window and how full it is, the account's -rate-limit windows, and what the conversation has cost. lich shows those -instead of the figures it derives from the transcript and from a request it -would otherwise spend measuring a token login's plan. - -| client | Claude Code | Codex | Antigravity | opencode | omp | Crush | -|----------------------|----------------------------------------------------------|---------------------|---------------------|---------------------|---------------------|---------------------| -| `hooks/mod-usage.js` | mod, registered by `hooks/lich.js`, the `modules` entry | none: no mod system | none: no mod system | none: no mod system | none: no mod system | none: no mod system | - -Claude Code takes one hooks module per plugin and refuses a second `modules` -entry, so `hooks/lich.js` is that module and registers each mod of the plugin -from its own file. - -| event | sent | -|-------------------|----------------------------------------------------------------------| -| `session.measure` | `POST /mod/usage` with `{"session_id", "conversation_id", "context", "rate_limits", "cost_usd"?}` | - -`conversation_id` is `$.session.id()`. `context` is `{window, tokens?, percent?}` -and each of `rate_limits` is `{kind, percent_used, resets_at?}`, Claude Code's -own figures renamed: one it does not have is left out, never zeroed. - -## How it behaves - -- **Outside lich it never reports.** It reads the three variables in - `session.start` and stops there when one is missing. -- **Only an interactive session reports.** A `claude -p` run from a tool inside - a lich session inherits that session's variables, and its figures would land - on the parent's card. Its `session.start` hook matches `isInteractive: true`, - so a non-interactive run never reads the link. -- **A measurement taken before `session.start` waits for it.** Claude Code - measures the session as it starts. -- **Reports go out one at a time, in order.** lich keeps the latest, so an older - one landing last would put stale figures back. -- **The event is never held up.** The report is posted beside the chain, a - failed one is dropped and never retried (the next carries the whole figures - again), and a `404` stops reporting for the session. - -Claude Code fires `session.measure` once at start, at the end of every -main-thread turn, and when a rate-limit window moves a whole point; never -mid-turn (measured on 2.1.289). A compaction fires it once more, just before -the `SessionStart` it reports as `compact` (measured on 2.1.295). diff --git a/docs/providers.md b/docs/providers.md index f42997e..c6567f9 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -4,9 +4,7 @@ lich drives an agent CLI inside a PTY and injects the same three variables (`LICH_PORT`, `LICH_TOKEN`, `LICH_SESSION_ID`) into every one it spawns. The [hook contracts](https://github.com/lichdotdev/lich/blob/main/docs/hooks/README.md) are therefore provider-agnostic: what changes per provider is only *how the -harness registers hooks* and *what its lifecycle events are called*. A Claude -Code session also carries `LICH_BIN`, which the mods that drive the lich CLI -read. +harness registers hooks* and *what its lifecycle events are called*. This repository is one plugin, packaged for each harness it supports: @@ -24,14 +22,7 @@ This repository is one plugin, packaged for each harness it supports: | `hooks/report-*.sh` | the four | the reports themselves | | `hooks/veto-subagent.sh` | the four, Kiro CLI | the subagent veto ([subagent-cards.md](subagent-cards.md)) | | `hooks/win-run.cmd` | Codex | runs a script on Windows | -| `hooks/win-veto.cmd` | Codex | runs the veto on Windows, keeping its stdout | -| `hooks/lich.js` | Claude Code | the one module `hooks/hooks.json` names under `modules`; registers the mods below | -| `hooks/mod-control.js` | Claude Code | the mod-control client, a mod | -| `hooks/mod-usage.js` | Claude Code | the mod-usage client, a mod | -| `hooks/mod-status.js` | Claude Code | the mod-status client, a mod | -| `hooks/edit-guard.js` | Claude Code | names the other lich session that edited a file, a mod | -| `hooks/mod-compacting.js` | Claude Code | the session-state `compacting` report, a mod | -| `hooks/self-command.js` | Claude Code | runs a built-in slash command the user asked the session for, a mod | +| `hooks/win-veto.cmd` | Codex | runs a hook whose stdout is an answer (the veto, the edit note) on Windows, keeping it | | `opencode/lich.js` | opencode | the whole client, as a module | | `omp/lich.js` | omp | the whole client, as a module | | `skills/` | all | skills, same layout | @@ -75,10 +66,9 @@ swallows its own errors and never awaits a report. | `busy` + tool | `PreToolUse` | `PreToolUse` | `PreToolUse` | `tool.execute.before` | `tool_call` | — | | `waiting` + reason | `Notification` | `PermissionRequest` | — (not measured) | any `*.asked` | — (see below) | — | | `done` | `Stop`, `StopFailure` | `Stop` | `Stop` | `session.status` (`idle`) | `session_stop` | — | -| `compacting` | `session.compact` (a mod) | — | — | — | — | — | | title | `Stop` | `Stop` | `Stop` | `session.updated` | `session_stop`, `turn_start` | — | | `idle` | `SessionEnd` | — (registered, never fires) | — (never fires) | — (nothing outlives it) | — (nothing outlives it) | — | -| touched | `PostToolUse` (write tools) | `PostToolUse` (write tools) | `PostToolUse` (write tools) | `file.edited` | `tool_result` (write tools) | `PreToolUse` (write tools) | +| touched | `PostToolUse` (write tools) | `PostToolUse` (write tools) | `PostToolUse` (write tools, `hold`), `PreInvocation` (`collect`) | `tool.execute.after` (write tools) | `tool_result` (write tools) | `PostToolUse` (write tools; `PreToolUse` before v0.99.0) | Every cell above was taken off a real run of that harness against a stub listener, not off its documentation. @@ -249,13 +239,15 @@ listener. 17.x moves fast — re-measure before trusting a name. ## Crush specifics -- **One event exists: `PreToolUse`.** Crush's hooks are Claude Code-compatible - down to the stdin payload and the exit codes, so the scripts run unchanged — - but with nothing that fires at the end of a turn, only two of the four reports - can be honest. Crush reports its session id and refreshes git status; it shows - no spinner, no check, no bell, and keeps the card's own name. Its `agent` - calls go through the subagent veto ([subagent-cards.md](subagent-cards.md)), - which needs no end of turn. +- **`PreToolUse` was its one event before v0.99.0.** Crush's hooks are Claude + Code-compatible down to the stdin payload and the exit codes, so the scripts + run unchanged. Crush reports its session id and the touched report (on + `PostToolUse` from v0.99.0, with its edit note; see + [session-touched.md](session-touched.md)); it shows no spinner, no check, no + bell, and keeps the card's own name. Its `agent` calls go through the subagent + veto ([subagent-cards.md](subagent-cards.md)), which needs no end of turn. + v0.100.0 documents 13 events, `TurnStart` and `TurnEnd` among them; none of + the state reports rides them yet, since none was measured on a real turn. - **`busy` is deliberately not registered.** A `busy` with no `Stop` behind it would pin a spinner to the card until the next turn — wrong for longer than it is right. The day Crush ships an end-of-turn event, `report-state.sh` and @@ -263,9 +255,9 @@ listener. 17.x moves fast — re-measure before trusting a name. - **The session id arrives late.** It rides the first tool call, because that is the first event there is. A conversation that answers without a tool never reports one. -- **The touched refresh runs one tool early**, for the same reason: `PreToolUse` - fires before the write, so the immediate git fetch sees the tree the tool has - not changed yet. What it front-runs in practice is the previous tool's write. +- **Before v0.99.0 the touched refresh runs one tool early**, for the same + reason: `PreToolUse` fires before the write, so the immediate git fetch sees + the tree the tool has not changed yet, and there is no note. - **Registration is a hand-merge.** Crush has no plugin system: its hooks live in the user's own `crush.json`, and `command` is resolved against the working directory, not the config file — so a global install needs an absolute path. diff --git a/docs/self-command.md b/docs/self-command.md deleted file mode 100644 index bb4a13b..0000000 --- a/docs/self-command.md +++ /dev/null @@ -1,113 +0,0 @@ -# Mod: self-command - -Lets a Claude Code session inside lich run one of its own built-in slash -commands when the user asks for it ("run /compact"). There is no lich contract -behind it and nothing is sent to lich: lich's `control` refuses a session -controlling itself on purpose (`docs/ceilings.md` in lich, "A session cannot -control itself"), and the mod runs in the session's own process anyway. - -The text this mod adds for the agent follows `LICH_PROMPT_LANG`, the prompt language lich exports into every session (English when unset or unknown; catalog in `hooks/prompt-text.js`). - -| client | Claude Code | Codex | Antigravity | opencode | omp | Crush | -|-------------------------|---------------------------------------------------------|---------------------|---------------------|---------------------|---------------------|---------------------| -| `hooks/self-command.js` | mod, registered by `hooks/lich.js`, the `modules` entry | none: no mod system | none: no mod system | none: no mod system | none: no mod system | none: no mod system | - -## How the model asks - -Through a tool it already reaches for: the Skill tool, or lich's own -`control_session`. Measured on Claude Code -2.1.295, asked to "run /compact", the model answered that it could not because -`/compact` is a CLI command and not a skill; called on `compact`, the Skill tool -refuses with `compact is a built-in CLI command, not a skill. Ask the user to -run /compact themselves — it cannot be invoked via the Skill tool.` - -Asked the same with only the Skill tool taken, sessions still went to -`control_session`, whose description says "never your own": one called it on -itself, another asked a peer session to run it on it. Claude Code names that -tool `mcp__lich__control_session` in `tool.call` and `tool.describe`, the call's -input arrives as `{ session, action, value, args }`, and lich refuses a session -named by its own label with an error result whose text is `"\n', - asUser: true, - }, - ], - [ - 'prompt', - { - text: - '\nwaiting\n' + - 'lich session "a<b&c" is waiting on a permission prompt\n' + - '\n' + - 'waiting\n' + - 'A permission prompt in its card. Its task stays open: open that card to answer it.\n' + - '\n' + - '', - asUser: true, - }, - ], - ]) - assert.deepEqual( - mod.acks().filter((a) => a.kind !== 'ask').map(({ id, kind, ok }) => ({ id, kind, ok })), - COMMANDS.filter((c) => c !== asked).map(({ id, kind }) => ({ id, kind, ok: true })), - ) - assert.deepEqual( - mod.acks().filter((a) => a.kind === 'ask').map(({ id, ok }) => ({ id, ok })), - [{ id: asked.id, ok: true }], - ) - for (const request of mod.ackRequests()) { - const { body } = assertContractHonoured('/mod/acks', request) - assert.equal(body.session_id, LICH_SESSION_ID) - } -}) - -test('a model or effort override reaches every model request', async () => { - const mod = await applied([ - { id: 'm3', kind: 'model', model: 'claude-opus-4-1' }, - { id: 'm5', kind: 'effort', effort: 'high' }, - ]) - for (const index of [0, 1]) { - const sent = await mod.step({ turnId: 't1', index, model: 'claude-sonnet-5-5', effort: 'medium', messageCount: 1 }) - assert.equal(sent.model, 'claude-opus-4-1') - assert.equal(sent.effort, 'high') - assert.equal(sent.index, index) - } -}) - -test('an override dropped by its absence restores the session\'s own model and effort', async () => { - const mod = load({ - polls: [ - ok([{ id: 'm3', kind: 'model', model: 'claude-opus-4-1' }, { id: 'm5', kind: 'effort', effort: 'high' }]), - ok([{ id: 'm4', kind: 'model' }, { id: 'm6', kind: 'effort' }]), - ], - }) - await mod.start() - await until(() => mod.acks().length === 4, 'four acks') - const e = { turnId: 't2', index: 1, model: 'claude-sonnet-5-5', effort: 'medium', messageCount: 3 } - assert.deepEqual(await mod.step(e), e) -}) - -// Claude Code takes the level and fails the hook at the next model request, -// long after the ack (measured on 2.1.288), so the mod refuses it up front. -test('an effort outside the five levels is refused and leaves the override alone', async () => { - const mod = await applied([ - { id: 'm1', kind: 'effort', effort: 'low' }, - { id: 'm2', kind: 'effort', effort: 'bogus' }, - ]) - const [, refusedAck] = mod.acks() - assert.deepEqual(refusedAck, { session_id: LICH_SESSION_ID, id: 'm2', kind: 'effort', ok: false, error: 'unknown effort' }) - assertContractHonoured('/mod/acks', mod.ackRequests()[1]) - assert.equal((await mod.step()).effort, 'low') -}) - -test('an abort with no turn running is acked as a failure', async () => { - const mod = await applied([{ id: 'm2', kind: 'abort' }], { - before: async (m) => { - await m.turnStart('t1') - await m.turnComplete('t1') - }, - }) - assert.deepEqual(mod.calls, []) - const [ack] = mod.acks() - assert.equal(ack.ok, false) - assert.equal(ack.error, 'no turn is running') - assertContractHonoured('/mod/acks', mod.ackRequests()[0]) -}) - -test('a subagent turn ending does not forget the main turn', async () => { - const mod = await applied([{ id: 'm2', kind: 'abort' }], { - before: async (m) => { - await m.turnStart('t1') - await m.turnComplete('sub-1') - }, - }) - assert.deepEqual(mod.calls, [['abort', { turnId: 't1' }]]) - assert.equal(mod.acks()[0].ok, true) -}) - -test('the next command waits for the abort ack to be answered', async () => { - const answered = deferred() - const mod = load({ - polls: [ok([{ id: 'm2', kind: 'abort' }, { id: 'm1', kind: 'prompt', text: 'go on' }])], - }) - mod.holdAcks(() => answered.promise) - await mod.turnStart('t1') - await mod.start() - await until(() => mod.ackRequests().length === 1, 'the abort ack') - await new Promise((r) => setTimeout(r, 20)) - assert.deepEqual(mod.calls, [['abort', { turnId: 't1' }]], 'the prompt ran before lich answered the abort ack') - answered.resolve(ACKED) - await until(() => mod.calls.length === 2, 'the prompt') - assert.deepEqual(mod.calls[1], ['prompt', { text: 'go on' }]) -}) - -test('an ack that cannot be sent is dropped and the next command still runs', async () => { - const mod = load({ - polls: [ok([{ id: 'm2', kind: 'abort' }, { id: 'm1', kind: 'prompt', text: 'go on' }])], - }) - mod.holdAcks(() => Promise.reject(new Error('connect ECONNREFUSED 127.0.0.1'))) - await mod.turnStart('t1') - await mod.start() - await until(() => mod.ackRequests().length === 2, 'both acks') - assert.deepEqual( - mod.calls.map(([kind]) => kind), - ['abort', 'prompt'], - ) -}) - -test('what Claude Code refuses is acked with its reason', async () => { - const mod = await applied( - [ - { id: 'm1', kind: 'prompt', text: 'blocked' }, - { id: 'm7', kind: 'command', name: 'nao-existe' }, - { id: 'm2', kind: 'abort' }, - ], - { - before: (m) => m.turnStart('t1'), - engine: { - submit: () => ({ drop: 'a plugin dropped it' }), - // Claude Code's own rejection, measured on 2.1.288. - command: () => Promise.reject(new Error('$.command.run: no command named /nao-existe in this session')), - abort: () => Promise.reject(new Error('t1 is not the running turn')), - }, - }, - ) - assert.deepEqual( - mod.acks().map(({ ok, error }) => ({ ok, error })), - [ - { ok: false, error: 'a plugin dropped it' }, - { ok: false, error: '$.command.run: no command named /nao-existe in this session' }, - { ok: false, error: 't1 is not the running turn' }, - ], - ) - for (const request of mod.ackRequests()) assertContractHonoured('/mod/acks', request) -}) - -// The contract's own rule, so a lich newer than the mod hears of it. This lich -// would refuse the ack, since it validates `kind` against the five it knows; -// a lich that sends a sixth kind knows six. -test('a kind the mod does not know is acked as unknown, its kind echoed', async () => { - const mod = await applied([{ id: 'm9', kind: 'rewind' }]) - assert.deepEqual(mod.acks(), [ - { session_id: LICH_SESSION_ID, id: 'm9', kind: 'rewind', ok: false, error: 'unknown kind' }, - ]) - assert.equal(mod.ackRequests()[0].headers['x-lich-plugin'], PLUGIN_VERSION) -}) - -// --------------------------------------------------------------------- ask -- - -/** The prompt the fork is sent: the question behind the mod's preamble. */ -function forkPrompt(question) { - return `This is a side question asked from outside your turn, while you work. It does not interrupt your turn and your answer is not added to the conversation. Tools are unavailable: do not call any tool. Answer from what the conversation already holds, in plain text, briefly. Question: ${question}` -} - -test('an ask is answered by a fork of the session and its answer rides the ack', async () => { - const mod = await applied([{ id: 'm9', kind: 'ask', question: 'what are you on?' }]) - assert.deepEqual(mod.calls, [['fork', { prompt: forkPrompt('what are you on?') }]]) - assert.deepEqual(mod.acks(), [{ session_id: LICH_SESSION_ID, id: 'm9', kind: 'ask', ok: true, answer: ANSWER }]) - assertContractHonoured('/mod/acks', mod.ackRequests()[0]) -}) - -test('an ask with no answer acks the fork\'s reason', async () => { - const cases = [ - [{ isAnswered: false, reason: 'nothing-to-fork' }, 'nothing-to-fork'], - [{ isAnswered: false, reason: 'api-error', status: 529, error: 'overloaded', usage: USAGE }, 'api-error 529 overloaded'], - [{ isAnswered: false, reason: 'empty-reply', usage: USAGE }, 'empty-reply'], - [{ isAnswered: false, reason: 'aborted', usage: USAGE }, 'aborted'], - ] - for (const [reply, error] of cases) { - const mod = await applied([{ id: 'm9', kind: 'ask', question: 'why?' }], { engine: { fork: () => reply } }) - assert.deepEqual(mod.acks(), [{ session_id: LICH_SESSION_ID, id: 'm9', kind: 'ask', ok: false, error }]) - assertContractHonoured('/mod/acks', mod.ackRequests()[0]) - } -}) - -test('a long answer is cut at 16,000 characters and says so', async () => { - const text = 'x'.repeat(16001) - const mod = await applied([{ id: 'm9', kind: 'ask', question: 'essay?' }], { - engine: { fork: () => ({ isAnswered: true, text, usage: USAGE }) }, - }) - assert.equal(mod.acks()[0].answer, `${'x'.repeat(16000)}\n[truncated]`) -}) - -test('an answer of exactly 16,000 characters is left whole', async () => { - const text = 'x'.repeat(16000) - const mod = await applied([{ id: 'm9', kind: 'ask', question: 'essay?' }], { - engine: { fork: () => ({ isAnswered: true, text, usage: USAGE }) }, - }) - assert.equal(mod.acks()[0].answer, text) -}) - -// A fork can run for a minute and more (measured at 109 seconds on Claude Code -// 2.1.289), so neither the poll nor an abort may wait on one. -test('an ask still answering holds back neither the poll nor the commands after it', async () => { - const forked = deferred() - const mod = load({ - polls: [ok([{ id: 'm9', kind: 'ask', question: 'why?' }]), ok([{ id: 'm2', kind: 'abort' }])], - engine: { fork: () => forked.promise }, - }) - await mod.turnStart('t1') - await mod.start() - await until(() => mod.acks().length === 1, 'the abort ack') - await until(() => mod.parked() === 1, 'the poll after the abort') - assert.deepEqual(mod.acks()[0], { session_id: LICH_SESSION_ID, id: 'm2', kind: 'abort', ok: true }) - forked.resolve({ isAnswered: true, text: ANSWER, usage: USAGE }) - await until(() => mod.acks().length === 2, 'the ask ack') - assert.equal(mod.acks()[1].answer, ANSWER) -}) - -test('an ask does not wait on an abort ack still being answered', async () => { - const held = deferred() - const mod = load({ polls: [ok([{ id: 'm2', kind: 'abort' }, { id: 'm9', kind: 'ask', question: 'why?' }])] }) - mod.holdAcks((request) => (JSON.parse(request.raw).kind === 'abort' ? held.promise : Promise.resolve(ACKED))) - await mod.turnStart('t1') - await mod.start() - await until(() => mod.acks().some((a) => a.kind === 'ask'), 'the ask ack') - held.resolve(ACKED) -}) diff --git a/tests/mod-status.engine.test.ts b/tests/mod-status.engine.test.ts deleted file mode 100644 index 18983e3..0000000 --- a/tests/mod-status.engine.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -// The status reads under Claude Code's own engine: `claude plugin test .` loads -// hooks/lich.js, which registers hooks/mod-status.js, the test's hooks standing -// for lich (`http.fetch`) and for the engine's own footer (`ui.render` of `SessionMode`). -// tests/mod-status.test.mjs is the suite CI runs against the contract fixture; -// this one proves the module loads beside the other mods and its line reaches -// the status line through the engine. - -import { expect, mock, test } from 'claude-code/testing' -import type { On } from 'claude-code' - -const ENV = { LICH_PORT: '47999', LICH_TOKEN: 'tok', LICH_SESSION_ID: 'lich-1' } -const STATUS = { - owed: [], - open: [{ ticket: '4f0c1a2e', target: 'docs', state: 'busy' }], - ready: [{ ticket: 'c7a91e04', target: 'review', status: 'answered' }], -} - -/** - * Answers every status read with STATUS and parks every other request, as lich - * does a poll with nothing queued; records the modes the footer is drawn with. - */ -function lich(on: On) { - const reads: string[] = [] - const footer = { modes: [] as readonly string[] } - on('session.start', async (_$, e) => ({ cwd: e.cwd })) - on('ui.render', { component: 'SessionMode' }, async ($, e) => { - footer.modes = e.props.modes - const { Text } = $.ui.resolve(e) - return h(Text, {}, e.props.modes.join(' & ')) - }) - on('http.fetch', async (_$, e) => { - if (e.url.includes('/mod/status')) { - reads.push(e.url) - return { value: { status: 200, ok: true, headers: {}, text: JSON.stringify(STATUS) } } - } - return new Promise(() => {}) - }) - return { reads, footer } -} - -test("lich's errands reach the footer", async ($, on) => { - mock.env(on, ENV) - const clock = mock.clock(on) - const world = lich(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await clock.settle() - expect(world.reads[0]).toContain('/mod/status?token=tok&session_id=lich-1') - await $.ui.render({ surface: 'terminal', component: 'SessionMode', requestId: 'footer', props: { modes: [] } }) - expect(world.footer.modes).toEqual(['lich: 1 task out, 1 answer to collect']) -}) - -test('a non-interactive run reads nothing', async ($, on) => { - mock.env(on, ENV) - const clock = mock.clock(on) - const world = lich(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: false }) - await clock.settle() - expect(world.reads).toHaveLength(0) -}) diff --git a/tests/mod-status.test.mjs b/tests/mod-status.test.mjs deleted file mode 100644 index d957130..0000000 --- a/tests/mod-status.test.mjs +++ /dev/null @@ -1,150 +0,0 @@ -// Pins the Claude Code mod's status reads (hooks/mod-status.js) to lich's -// mod-status contract: the request it sends, and the status line it draws -// from the response lich answers with (mod-status.json). -// -// Like the other mod suites it imports the module and hands it a fake engine: -// `$.http.fetch` records each read and answers with what a test hands it, and -// `$.clock.every` keeps the timer for the test to fire. -// -// Run: node --test tests/ - -import { test } from 'node:test' -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import path from 'node:path' - -import { LICH_SESSION_ID, PLUGIN_VERSION, ROOT, TOKEN, footerLine, lichEnv } from './contract.mjs' -import { register } from '../hooks/mod-status.js' - -const PORT = 47997 -const STATUS = JSON.parse(readFileSync(path.join(ROOT, 'tests', 'fixtures', 'mod-status.json'), 'utf8')) -const NONE = { owed: [], open: [], ready: [] } - -const answering = (body, status = 200) => async () => ({ status, ok: status < 300, headers: {}, text: JSON.stringify(body) }) - -/** Registers the module against a fake engine; `answer` answers each read. */ -function load({ env = lichEnv(PORT), answer = answering(NONE) } = {}) { - let start - register((event, matcher, hook) => { - assert.equal(event, 'session.start') - assert.deepEqual(matcher, { isInteractive: true }) - start = hook - }) - const reads = [] - const statuses = [] - const timers = [] - const $ = { - env: { get: async (name) => env[name] }, - clock: { - every: (ms, fn) => { - const timer = { ms, fn, cancelled: false, cancel: () => (timer.cancelled = true) } - timers.push(timer) - return timer - }, - }, - ui: { invalidate: () => statuses.push(footerLine()) }, - http: { - fetch: async (url, init = {}) => { - reads.push({ url, method: init.method ?? 'GET', headers: init.headers ?? {} }) - return answer() - }, - }, - } - const settled = () => new Promise((r) => setTimeout(r, 10)) - return { - reads, - statuses, - timers, - start: async (isInteractive = true) => { - if (isInteractive) await start($, { cwd: '/w', surface: 'terminal', isInteractive }, async (e) => e) - await settled() - }, - tick: async () => { - timers[0].fn() - await settled() - }, - } -} - -test('a read is the GET the contract spells, repeated every few seconds', async () => { - const mod = load() - await mod.start() - - const url = new URL(mod.reads[0].url) - assert.equal(mod.reads[0].method, 'GET') - assert.equal(`${url.host}${url.pathname}`, `127.0.0.1:${PORT}/mod/status`) - assert.equal(url.searchParams.get('token'), TOKEN) - assert.equal(url.searchParams.get('session_id'), LICH_SESSION_ID) - assert.equal(mod.reads[0].headers['X-Lich-Plugin'], PLUGIN_VERSION) - assert.equal(mod.timers.length, 1) - assert.equal(mod.timers[0].ms, 5000) - await mod.tick() - assert.equal(mod.reads.length, 2) -}) - -test("lich's status draws as one line", async () => { - const mod = load({ answer: answering(STATUS) }) - await mod.start() - - assert.deepEqual(mod.statuses, ['lich: owes 2 answers, 4 tasks out (1 waiting), 2 answers to collect']) -}) - -test('one answer owed names the session that asked, unless it came from the command line', async () => { - const [fromSession, fromCli] = STATUS.owed - const named = load({ answer: answering({ ...NONE, owed: [fromSession] }) }) - const cli = load({ answer: answering({ ...NONE, owed: [fromCli] }) }) - await named.start() - await cli.start() - - assert.deepEqual(named.statuses, ['lich: owes "Session 26" an answer']) - assert.deepEqual(cli.statuses, ['lich: owes 1 answer']) -}) - -test('nothing to show clears the line', async () => { - const mod = load() - await mod.start() - - assert.deepEqual(mod.statuses, [undefined]) -}) - -test('a failed read clears the line, is not retried, and the next one still runs', async () => { - let answer = answering(STATUS, 500) - const mod = load({ answer: () => answer() }) - await mod.start() - assert.deepEqual(mod.statuses, [undefined]) - assert.equal(mod.reads.length, 1) - - answer = async () => { - throw new Error('connect ECONNREFUSED') - } - await mod.tick() - answer = answering(STATUS) - await mod.tick() - - assert.deepEqual(mod.statuses.at(-1), 'lich: owes 2 answers, 4 tasks out (1 waiting), 2 answers to collect') - assert.equal(mod.timers[0].cancelled, false) -}) - -test('a lich older than the contract stops the reads for the session', async () => { - const mod = load({ answer: answering({}, 404) }) - await mod.start() - - assert.equal(mod.timers[0].cancelled, true) - assert.deepEqual(mod.statuses, [undefined]) -}) - -test('outside lich nothing is read', async () => { - const mod = load({ env: {} }) - await mod.start() - - assert.equal(mod.reads.length, 0) - assert.equal(mod.timers.length, 0) -}) - -test("a non-interactive run never reads the card that started it", async () => { - const mod = load() - await mod.start(false) - - assert.equal(mod.reads.length, 0) - assert.equal(mod.timers.length, 0) -}) diff --git a/tests/mod-usage.engine.test.ts b/tests/mod-usage.engine.test.ts deleted file mode 100644 index 3b46632..0000000 --- a/tests/mod-usage.engine.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -// The usage report under Claude Code's own engine: `claude plugin test .` loads -// the plugin's hooks module (hooks/lich.js, which registers hooks/mod-usage.js) -// from hooks/hooks.json the way a session does, the test's hooks standing for -// lich (`http.fetch`). tests/mod-usage.test.mjs is the suite CI runs against -// the contract fixtures; this one proves the module loads and its hooks chain -// in the engine that runs it. - -import { expect, mock, test } from 'claude-code/testing' -import type { On, SessionMeasureInput } from 'claude-code' - -const ENV = { LICH_PORT: '47999', LICH_TOKEN: 'tok', LICH_SESSION_ID: 'lich-1' } - -const MEASURED: SessionMeasureInput = { - context: { tokens: 43592, window: 200000, percent: 22 }, - rateLimits: [{ kind: 'five_hour', percentUsed: 14, resetsAt: '2026-10-05T00:30:00.000Z' }], - cost: { usd: 0.0977631 }, - changed: ['context', 'cost'], -} - -/** - * Records every usage report and parks every poll, as lich does with nothing - * queued; also stands for the engine's own session start, measurement and id, - * which the kit leaves to the test. - */ -function lich(on: On) { - const reports: Record[] = [] - on('session.start', async (_$, e) => ({ cwd: e.cwd })) - on('session.measure', async (_$, e) => ({ changed: e.changed })) - on('session.id', async () => ({ value: 'conv-1' })) - on('http.fetch', async (_$, e) => { - if (e.url.includes('/mod/usage')) { - reports.push(JSON.parse(e.init?.body ?? '{}')) - return { value: { status: 204, ok: true, headers: {}, text: '' } } - } - return new Promise(() => {}) - }) - return { reports } -} - -test('a measurement is reported to lich', async ($, on) => { - mock.env(on, ENV) - const clock = mock.clock(on) - const world = lich(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.session.measure(MEASURED) - await clock.settle() - expect(world.reports).toHaveLength(1) - expect(world.reports[0]).toMatchObject({ - session_id: 'lich-1', - conversation_id: 'conv-1', - context: { window: 200000, tokens: 43592, percent: 22 }, - rate_limits: [{ kind: 'five_hour', percent_used: 14, resets_at: '2026-10-05T00:30:00.000Z' }], - cost_usd: 0.0977631, - }) -}) - -test('a non-interactive run reports nothing', async ($, on) => { - mock.env(on, ENV) - const clock = mock.clock(on) - const world = lich(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: false }) - await $.session.measure(MEASURED) - await clock.settle() - expect(world.reports).toHaveLength(0) -}) diff --git a/tests/mod-usage.test.mjs b/tests/mod-usage.test.mjs deleted file mode 100644 index 4ef1368..0000000 --- a/tests/mod-usage.test.mjs +++ /dev/null @@ -1,223 +0,0 @@ -// Pins the Claude Code mod's usage report (hooks/mod-usage.js) to lich's -// mod-usage contract. -// -// Like mod-control.test.mjs, it imports the module and hands it a fake engine, -// recording every fetch as contract.mjs reads a request, so the reports answer -// to the same fixtures lich asserts (mod-usage.jsonl). The `session.measure` -// payloads below are what Claude Code 2.1.289 delivered against a stub lich. -// -// Run: node --test tests/ - -import { test } from 'node:test' -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import path from 'node:path' - -import { LICH_SESSION_ID, ROOT, assertContractHonoured, lichEnv } from './contract.mjs' -import { register } from '../hooks/mod-usage.js' -import { register as registerEntry } from '../hooks/lich.js' - -const PORT = 47998 -const CONVERSATION = '3fb3ad05-5b58-45ea-a1e0-0d1d4b0a89b9' - -const AT_START = { - context: { window: 200000 }, - rateLimits: [ - { kind: 'five_hour', percentUsed: 14, resetsAt: '2026-10-05T00:30:00.000Z' }, - { kind: 'seven_day', percentUsed: 80, resetsAt: '2026-10-05T15:00:00.000Z' }, - ], - cost: { usd: 0 }, - changed: ['context', 'rateLimits', 'cost'], -} - -const AT_TURN_END = { - context: { tokens: 43592, window: 200000, percent: 22 }, - rateLimits: AT_START.rateLimits, - cost: { usd: 0.0977631 }, - changed: ['context', 'cost'], -} - -const NO_CONTENT = { status: 204, ok: true, headers: {}, text: '' } - -/** Waits for `predicate` to hold, failing after a second of real time. */ -async function until(predicate, what) { - const deadline = Date.now() + 1000 - while (!predicate()) { - if (Date.now() > deadline) assert.fail(`timed out waiting for ${what}`) - await new Promise((r) => setImmediate(r)) - } -} - -const settle = () => new Promise((r) => setTimeout(r, 20)) - -/** - * Registers the module against a fake engine. A hook registered with a - * matcher runs only for an event that matches it, as the engine runs it. - * `answer` answers each report. - */ -function load({ env = lichEnv(PORT), answer = () => Promise.resolve(NO_CONTENT) } = {}) { - const hooks = new Map() - register((event, ...rest) => { - const hook = rest.pop() - const matcher = rest[0] ?? {} - hooks.set(event, { matcher, hook }) - }) - const requests = [] - const $ = { - env: { get: async (name) => env[name] }, - session: { id: async () => CONVERSATION }, - http: { - fetch: (url, init = {}) => { - const { pathname, search } = new URL(url) - const headers = Object.fromEntries(Object.entries(init.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v])) - const request = { method: init.method ?? 'GET', url: pathname + search, headers, raw: init.body ?? '' } - requests.push(request) - return answer(request) - }, - }, - } - const passOn = async (e) => e - const fire = (event, e) => { - const { matcher, hook } = hooks.get(event) - const matches = Object.entries(matcher).every(([key, value]) => e[key] === value) - return matches ? hook($, e, passOn) : passOn(e) - } - return { - requests, - reports: () => requests.map((r) => JSON.parse(r.raw)), - start: (isInteractive = true) => fire('session.start', { cwd: '/w', surface: 'terminal', isInteractive }), - measure: (e) => fire('session.measure', e), - } -} - -test('a measurement reaches lich as the contract spells it', async () => { - const mod = load() - await mod.start() - - await mod.measure(AT_TURN_END) - await until(() => mod.requests.length === 1, 'the report') - - assertContractHonoured('/mod/usage', mod.requests[0]) - assert.deepEqual(mod.reports()[0], { - session_id: LICH_SESSION_ID, - conversation_id: CONVERSATION, - context: { window: 200000, tokens: 43592, percent: 22 }, - rate_limits: [ - { kind: 'five_hour', percent_used: 14, resets_at: '2026-10-05T00:30:00.000Z' }, - { kind: 'seven_day', percent_used: 80, resets_at: '2026-10-05T15:00:00.000Z' }, - ], - cost_usd: 0.0977631, - }) -}) - -test('a figure Claude Code does not have is left out, never zeroed', async () => { - const mod = load() - await mod.start() - - await mod.measure({ context: { window: 200000 }, rateLimits: [{ kind: 'five_hour', percentUsed: 3 }], changed: ['context'] }) - await until(() => mod.requests.length === 1, 'the report') - - assertContractHonoured('/mod/usage', mod.requests[0]) - const body = mod.reports()[0] - assert.deepEqual(body.context, { window: 200000 }) - assert.deepEqual(body.rate_limits, [{ kind: 'five_hour', percent_used: 3 }]) - assert.ok(!('cost_usd' in body)) -}) - -// Claude Code measures the session as it starts, which can land before the -// session.start hook has read the link. -test('a measurement taken before the session started is sent once it does', async () => { - const mod = load() - - await mod.measure(AT_START) - await settle() - assert.equal(mod.requests.length, 0) - await mod.start() - await until(() => mod.requests.length === 1, 'the held report') - - assertContractHonoured('/mod/usage', mod.requests[0]) -}) - -test('the event is passed on without waiting for lich', async () => { - const mod = load({ answer: () => new Promise(() => {}) }) - await mod.start() - - const passed = await mod.measure(AT_START) - - assert.equal(passed, AT_START) -}) - -test('outside lich nothing is sent', async () => { - const mod = load({ env: {} }) - await mod.start() - - await mod.measure(AT_TURN_END) - await settle() - - assert.equal(mod.requests.length, 0) -}) - -test('a non-interactive run never reports onto the card that started it', async () => { - const mod = load() - await mod.start(false) - - await mod.measure(AT_TURN_END) - await settle() - - assert.equal(mod.requests.length, 0) -}) - -test('reports go out one at a time, in the order they were measured', async () => { - let release - const first = new Promise((r) => { - release = () => r(NO_CONTENT) - }) - const mod = load({ answer: () => (mod.requests.length === 1 ? first : Promise.resolve(NO_CONTENT)) }) - await mod.start() - - await mod.measure(AT_START) - await mod.measure(AT_TURN_END) - await settle() - assert.equal(mod.requests.length, 1, 'the second report went out before the first was answered') - release() - await until(() => mod.requests.length === 2, 'the second report') - - assert.deepEqual(mod.reports().map((r) => r.cost_usd), [0, 0.0977631]) -}) - -test('a report that fails is dropped and the next one still goes out', async () => { - const mod = load({ - answer: () => - mod.requests.length === 1 ? Promise.reject(new Error('connect ECONNREFUSED')) : Promise.resolve(NO_CONTENT), - }) - await mod.start() - - await mod.measure(AT_START) - await mod.measure(AT_TURN_END) - await until(() => mod.requests.length === 2, 'the report after the failure') - await settle() - - assert.equal(mod.requests.length, 2, 'the failed report was retried') -}) - -test('a lich that predates the contract is not asked again', async () => { - const mod = load({ answer: () => Promise.resolve({ status: 404, ok: false, headers: {}, text: '' }) }) - await mod.start() - - await mod.measure(AT_START) - await mod.measure(AT_TURN_END) - await settle() - - assert.equal(mod.requests.length, 1) -}) - -// Claude Code takes one hooks module per plugin, so hooks.json names the entry -// that registers every mod of the plugin, this one included. -test('the plugin entry module registers the usage report beside control', () => { - const hooksJson = JSON.parse(readFileSync(path.join(ROOT, 'hooks', 'hooks.json'), 'utf8')) - assert.deepEqual(hooksJson.modules, ['./lich.js']) - const events = [] - registerEntry((event) => events.push(event)) - assert.ok(events.includes('session.measure'), 'mod-usage is not registered') - assert.ok(events.includes('turn.step'), 'mod-control is not registered') -}) diff --git a/tests/opencode.test.mjs b/tests/opencode.test.mjs index 6732c14..7ad1d06 100644 --- a/tests/opencode.test.mjs +++ b/tests/opencode.test.mjs @@ -203,11 +203,11 @@ test('an event that only contains "asked" reports nothing', async () => { assert.equal(requests.length, 0, `a non-prompt raised a bell: ${requests[0]?.raw}`) }) -test('file.edited refreshes the git status', async () => { - const requests = await reportsFor(({ event }) => event('file.edited', { file: '/w/oc-probe.txt' })) - assert.equal(requests.length, 1) - const { body } = assertContractHonoured('/session-touched', requests[0]) - assert.equal(body.session_id, LICH_SESSION_ID) +// file.edited fires before the same write's tool.execute.after, which reports +// the edit with its paths (touched.test.mjs), so it reports nothing itself. +test('file.edited reports nothing: the write reports its own files', async () => { + const requests = await reportsFor(({ event }) => event('file.edited', { file: '/w/oc-probe.txt' }), { expected: 0 }) + assert.equal(requests.length, 0) }) test('tool.execute.before names the tool and what it acts on', async () => { diff --git a/tests/prompt-text.test.mjs b/tests/prompt-text.test.mjs deleted file mode 100644 index 89bea2c..0000000 --- a/tests/prompt-text.test.mjs +++ /dev/null @@ -1,314 +0,0 @@ -// Pins the agent-facing text catalog (hooks/prompt-text.js) and that each hook -// renders it in the prompt language lich exports as LICH_PROMPT_LANG. The -// English texts are pinned verbatim by each hook's own suite; this one holds -// the catalogs level with each other and runs one text per hook in pt-BR. -// -// Run: node --test tests/ - -import { test } from 'node:test' -import assert from 'node:assert/strict' - -import { en, ptBR, zhCN, es, ja, ko, ru, say, promptLang } from '../hooks/prompt-text.js' -import { register as registerEditGuard } from '../hooks/edit-guard.js' -import { register as registerSelfCommand } from '../hooks/self-command.js' -import { register as registerModControl } from '../hooks/mod-control.js' - -const slots = (text) => [...text.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort() - -// Names the model or the contract matches on: kept literal in every locale. -const LITERALS = [ - '', - 'send_to_session', - 'wait_for_answer', - 'SendMessage', - 'lich send', - 'mcp__lich__control_session', - 'subagent/', -] - -test('every English text has a pt-BR twin and the other way round', () => { - assert.deepEqual(Object.keys(ptBR).sort(), Object.keys(en).sort()) -}) - -test('a translation fills the same slots as the English text', () => { - for (const key of Object.keys(en)) assert.deepEqual(slots(ptBR[key]), slots(en[key]), key) -}) - -test('names that must stay literal are kept in every translation', () => { - for (const key of Object.keys(en)) { - for (const literal of LITERALS) { - if (en[key].includes(literal)) assert.ok(ptBR[key].includes(literal), `${key} lost ${literal}`) - } - } -}) - -test('an unknown or absent language says the English text', () => { - for (const lang of [undefined, '', 'fr', 'PT-br']) assert.equal(say(lang, 'editNoteAgo', { minutes: 2 }), '2 min ago') - assert.equal(say('pt-BR', 'editNoteAgo', { minutes: 2 }), 'há 2 min') -}) - -test('a key no catalog has is an error, not an empty text', () => { - assert.throws(() => say('en', 'nope'), /no prompt text named "nope"/) -}) - -test('the language is read from LICH_PROMPT_LANG, English when unset or unknown', async () => { - const lang = async (value) => promptLang(value) - assert.equal(await lang('pt-BR'), 'pt-BR') - assert.equal(await lang('en'), 'en') - assert.equal(await lang(undefined), 'en') - assert.equal(await lang('klingon'), 'en') -}) - -// ------------------------------------------------------------ per hook, pt-BR -- - -const PT = { LICH_PROMPT_LANG: 'pt-BR' } - -function hooksOf(register) { - const hooks = new Map() - register((event, ...rest) => { - const matcher = rest.length > 1 ? rest[0] : {} - hooks.set(`${event} ${matcher.tool ?? ''}`.trim(), rest.at(-1)) - }) - return hooks -} - -const pass = (value) => async () => value -const exits = (code, stdout = '', stderr = '') => ({ exitCode: code, stdout, stderr }) - -test('edit-guard: the note about another session speaks pt-BR', async () => { - const MIN = 60_000 - const T0 = Date.parse('2026-10-05T12:00:00.000Z') - const disk = new Map() - let now = T0 - const hooks = hooksOf(registerEditGuard) - const session = (id) => { - const env = { ...PT, LICH_SESSION_ID: id } - const $ = { - env: { get: async (n) => env[n] }, - clock: { now: async () => now, after: () => ({ cancel() {} }) }, - ui: { log() {}, invalidate() {} }, - process: { run: async () => exits(0, '/r/.git\n') }, - fs: { - exists: async (p) => disk.has(p), - read: async (p) => disk.get(p), - write: async (p, t) => void disk.set(p, t), - }, - } - return () => hooks.get('tool.call Edit')($, { tool: 'Edit', file_path: '/r/a.js' }, pass({ result: {}, text: 'ok' })) - } - await session('lich-a')() - now = T0 + 3 * MIN - const result = await session('lich-b')() - assert.match(result.context[0], /^\/r\/a\.js também foi editado pela sessão lich lich-a em 2026-10-05T12:00:00\.000Z \(há 3 min\)/) - assert.match(result.context[0], /send_to_session ou lich send/) -}) - -test('self-command: the tool notes and the queued answers speak pt-BR', async () => { - const hooks = hooksOf(registerSelfCommand) - const env = { ...PT, LICH_SESSION_ID: 'lich-1', LICH_BIN: '/lich' } - const $ = { - env: { get: async (n) => env[n] }, - clock: { after() {} }, - command: { list: async () => [{ name: 'compact', source: 'builtin' }, { name: 'model', source: 'builtin' }], run: async () => ({}) }, - ui: { toast() {}, invalidate() {} }, - process: { run: async () => exits(0, JSON.stringify({ label: 'x', name: 'y' })) }, - } - await hooks.get('session.start')($, { isInteractive: true }, async (e) => e) - - const skill = await hooks.get('tool.describe Skill')($, { tool: 'Skill', description: 'base' }, async (e) => e) - assert.match(skill.description, /^base\n\nNesta sessão um slash command embutido/) - const control = await hooks.get('tool.describe mcp__lich__control_session')( - $, - { tool: 'mcp__lich__control_session', description: 'base' }, - async (e) => e, - ) - assert.match(control.description, /passe session "lich-1"\./) - - const refused = { isError: true, result: 'compact is a built-in CLI command, not a skill' } - const queued = await hooks.get('tool.call Skill')($, { tool: 'Skill', skill: 'compact' }, async () => refused) - assert.equal(queued.context[0], '/compact está na fila e roda quando este turno terminar. Encerre o turno agora.') - - const denied = await hooks.get('tool.call Skill')($, { tool: 'Skill', skill: 'model', args: 'opus' }, async () => refused) - assert.match(denied.deny, /^\/model executado de dentro da sessão/) -}) - -test('mod-control: the side question is prefaced in pt-BR', async () => { - const hooks = hooksOf(registerModControl) - const forks = [] - const env = { ...PT, LICH_PORT: '1', LICH_TOKEN: 't', LICH_SESSION_ID: 's' } - let served = false - const $ = { - env: { get: async (n) => env[n] }, - clock: { after: (ms, fn) => setImmediate(fn) }, - http: { - fetch: async (url) => { - if (url.includes('/mod/acks')) return { status: 204, ok: true, headers: {}, text: '' } - if (served) return new Promise(() => {}) - served = true - const body = [{ id: 'm1', kind: 'ask', question: 'o que faz?' }] - return { status: 200, ok: true, headers: {}, text: JSON.stringify(body) } - }, - }, - model: { - fork: async (args) => { - forks.push(args) - return { isAnswered: true, text: 'a', usage: {} } - }, - }, - } - await hooks.get('session.start')($, { isInteractive: true }, async (e) => e) - for (let i = 0; i < 50 && forks.length === 0; i++) await new Promise((r) => setImmediate(r)) - assert.equal(forks.length, 1) - assert.match(forks[0].prompt, /^Esta é uma pergunta lateral feita de fora do seu turno/) - assert.ok(forks[0].prompt.endsWith('Pergunta: o que faz?')) -}) - -// ---------------------------------------------- zh-CN, es, ja, ko and ru catalogs -- - -const NEW_LOCALES = { 'zh-CN': zhCN, es, ja, ko, ru } - -for (const [tag, catalog] of Object.entries(NEW_LOCALES)) { - test(`${tag}: same keys, same slots and the literal names as English`, () => { - assert.deepEqual(Object.keys(catalog).sort(), Object.keys(en).sort()) - for (const key of Object.keys(en)) { - assert.deepEqual(slots(catalog[key]), slots(en[key]), key) - for (const literal of LITERALS) { - if (en[key].includes(literal)) assert.ok(catalog[key].includes(literal), `${key} lost ${literal}`) - } - } - }) - - test(`${tag}: LICH_PROMPT_LANG selects the catalog`, () => { - assert.equal(promptLang(tag), tag) - assert.notEqual(say(tag, 'editNoteAgo', { minutes: 2 }), '2 min ago') - }) -} - -// What each hook renders per locale, one text per hook. The hook is driven the -// way the pt-BR tests above drive it, with only the language swapped. -const EXPECTED = { - 'zh-CN': { - edit: /^\/r\/a\.js 也被 lich 会话 lich-a 在 2026-10-05T12:00:00\.000Z(3 分钟前)编辑过/, - skill: /^base\n\n在此会话中,内置斜杠命令/, - control: /传入 session "lich-1"。/, - queued: '/compact 已进入队列,将在本回合结束后运行。现在请结束本回合。', - saved: /^在会话内部运行 \/model/, - ask: /^这是在你的回合之外/, - }, - es: { - edit: /^\/r\/a\.js también fue editado por la sesión lich lich-a en 2026-10-05T12:00:00\.000Z \(hace 3 min\)/, - skill: /^base\n\nEn esta sesión, un slash command integrado/, - control: /pasa session "lich-1"\./, - queued: '/compact está en cola y se ejecuta cuando termine este turno. Termina el turno ahora.', - saved: /^\/model ejecutado desde dentro de la sesión/, - ask: /^Esta es una pregunta lateral hecha desde fuera de tu turno/, - }, - ja: { - edit: /^\/r\/a\.js は lich セッション lich-a によっても 2026-10-05T12:00:00\.000Z(3 分前)に編集されています/, - skill: /^base\n\nこのセッションでは、ユーザーが実行を求めたときに、組み込みのスラッシュコマンド/, - control: /session に "lich-1" を渡してください。/, - queued: '/compact はキューに入り、このターンが終わると実行されます。今すぐターンを終えてください。', - saved: /^\/model をセッションの中から実行すると/, - ask: /^これは、あなたが作業している間にターンの外から尋ねられた横からの質問です/, - }, - ko: { - edit: /^\/r\/a\.js은\(는\) lich 세션 lich-a도 2026-10-05T12:00:00\.000Z\(3분 전\)에 수정했습니다/, - skill: /^base\n\n이 세션에서는 사용자가 실행을 요청하면 내장 슬래시 명령/, - control: /session에 "lich-1"를 전달하세요\./, - queued: '/compact이(가) 대기열에 들어갔고 이 턴이 끝나면 실행됩니다. 지금 턴을 끝내세요.', - saved: /^세션 안에서 \/model을\(를\) 실행하면/, - ask: /^이것은 당신이 작업하는 동안 턴 밖에서 들어온 곁가지 질문입니다/, - }, - ru: { - edit: /^\/r\/a\.js также редактировала сессия lich lich-a в 2026-10-05T12:00:00\.000Z \(3 мин назад\)/, - skill: /^base\n\nВ этой сессии здесь также можно назвать встроенную slash-команду/, - control: /передайте session "lich-1"\./, - queued: '/compact поставлена в очередь и выполнится, когда этот ход закончится. Завершите ход сейчас.', - saved: /^\/model, запущенная изнутри сессии/, - ask: /^Это побочный вопрос, заданный вне вашего хода/, - }, -} - -for (const [tag, want] of Object.entries(EXPECTED)) { - const LANG = { LICH_PROMPT_LANG: tag } - - test(`${tag}: edit-guard renders the note about another session`, async () => { - const T0 = Date.parse('2026-10-05T12:00:00.000Z') - const disk = new Map() - let now = T0 - const hooks = hooksOf(registerEditGuard) - const session = (id) => { - const env = { ...LANG, LICH_SESSION_ID: id } - const $ = { - env: { get: async (n) => env[n] }, - clock: { now: async () => now, after: () => ({ cancel() {} }) }, - ui: { log() {}, invalidate() {} }, - process: { run: async () => exits(0, '/r/.git\n') }, - fs: { - exists: async (p) => disk.has(p), - read: async (p) => disk.get(p), - write: async (p, t) => void disk.set(p, t), - }, - } - return () => hooks.get('tool.call Edit')($, { tool: 'Edit', file_path: '/r/a.js' }, pass({ result: {}, text: 'ok' })) - } - await session('lich-a')() - now = T0 + 3 * 60_000 - const result = await session('lich-b')() - assert.match(result.context[0], want.edit) - assert.match(result.context[0], /send_to_session( o| 或| または|이나| или) lich send/) - }) - - test(`${tag}: self-command renders the tool notes and the queued answer`, async () => { - const hooks = hooksOf(registerSelfCommand) - const env = { ...LANG, LICH_SESSION_ID: 'lich-1', LICH_BIN: '/lich' } - const $ = { - env: { get: async (n) => env[n] }, - clock: { after() {} }, - command: { list: async () => [{ name: 'compact', source: 'builtin' }, { name: 'model', source: 'builtin' }], run: async () => ({}) }, - ui: { toast() {}, invalidate() {} }, - process: { run: async () => exits(0, JSON.stringify({ label: 'x', name: 'y' })) }, - } - await hooks.get('session.start')($, { isInteractive: true }, async (e) => e) - - const skill = await hooks.get('tool.describe Skill')($, { tool: 'Skill', description: 'base' }, async (e) => e) - assert.match(skill.description, want.skill) - const control = await hooks.get('tool.describe mcp__lich__control_session')( - $, - { tool: 'mcp__lich__control_session', description: 'base' }, - async (e) => e, - ) - assert.match(control.description, want.control) - - const refused = { isError: true, result: 'compact is a built-in CLI command, not a skill' } - const queued = await hooks.get('tool.call Skill')($, { tool: 'Skill', skill: 'compact' }, async () => refused) - assert.equal(queued.context[0], want.queued) - const denied = await hooks.get('tool.call Skill')($, { tool: 'Skill', skill: 'model', args: 'opus' }, async () => refused) - assert.match(denied.deny, want.saved) - }) - - test(`${tag}: mod-control prefaces the side question`, async () => { - const hooks = hooksOf(registerModControl) - const forks = [] - const env = { ...LANG, LICH_PORT: '1', LICH_TOKEN: 't', LICH_SESSION_ID: 's' } - let served = false - const $ = { - env: { get: async (n) => env[n] }, - clock: { after: (ms, fn) => setImmediate(fn) }, - http: { - fetch: async (url) => { - if (url.includes('/mod/acks')) return { status: 204, ok: true, headers: {}, text: '' } - if (served) return new Promise(() => {}) - served = true - return { status: 200, ok: true, headers: {}, text: JSON.stringify([{ id: 'm1', kind: 'ask', question: 'q?' }]) } - }, - }, - model: { fork: async (args) => (forks.push(args), { isAnswered: true, text: 'a', usage: {} }) }, - } - await hooks.get('session.start')($, { isInteractive: true }, async (e) => e) - for (let i = 0; i < 50 && forks.length === 0; i++) await new Promise((r) => setImmediate(r)) - assert.equal(forks.length, 1) - assert.match(forks[0].prompt, want.ask) - assert.ok(forks[0].prompt.endsWith('q?')) - }) -} diff --git a/tests/refresh-fixtures.sh b/tests/refresh-fixtures.sh index 212271f..3b124f5 100755 --- a/tests/refresh-fixtures.sh +++ b/tests/refresh-fixtures.sh @@ -19,21 +19,19 @@ ref=$(tr -d '[:space:]' <"$here/lich-ref") raw=https://raw.githubusercontent.com/lichdotdev/lich/$ref base=$raw/docs/hooks/fixtures -for file in session-start.jsonl session-state.jsonl session-title.jsonl \ - session-touched.jsonl mod-usage.jsonl mod-control.jsonl \ - mod-status.json; do +for file in session-start.jsonl session-state.jsonl session-title.jsonl; do curl -fsSL "$base/$file" -o "$here/fixtures/$file" echo "refreshed $file at $ref" done -# mod-commands' prompt examples became notification envelopes in lich's merge -# commit 1f4166bf (feat/request-envelope), in no release yet, so it is read at +# session-touched gained paths, hold, collect and the edit note in lich's merge +# commit c62b0796 (feat/touched-edit-note), in no release yet, so it is read at # that commit. Once a release ships it, move tests/lich-ref to that release and # put the file back in the loop above. -unreleased=1f4166bf61a4cd91ef91c7811f35fa8d17c0016a -curl -fsSL "https://raw.githubusercontent.com/lichdotdev/lich/$unreleased/docs/hooks/fixtures/mod-commands.json" \ - -o "$here/fixtures/mod-commands.json" -echo "refreshed mod-commands.json at $unreleased (unreleased)" +unreleased=c62b0796c191b66fff0eb23a6665e6ed3b2a7a83 +curl -fsSL "https://raw.githubusercontent.com/lichdotdev/lich/$unreleased/docs/hooks/fixtures/session-touched.jsonl" \ + -o "$here/fixtures/session-touched.jsonl" +echo "refreshed session-touched.jsonl at $unreleased (unreleased)" # subagent-cards is a contract of its own, merged in lich at d33b02a8 and in no # release yet, so it is read at that commit. Once a release ships it, move diff --git a/tests/self-command.engine.test.ts b/tests/self-command.engine.test.ts deleted file mode 100644 index 952b107..0000000 --- a/tests/self-command.engine.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -// The self-command mod under Claude Code's own engine: `claude plugin test .` -// loads hooks/lich.js, which registers hooks/self-command.js. The test's hooks -// stand for the Skill tool's own refusal of a built-in (the `tool.call` beneath -// the mod) and for the command's run (`command.run`). -// -// tests/self-command.test.mjs is the suite CI runs; this one proves the module -// loads beside the other mods and that the command it queues reaches -// `command.run` as the plugin, once the call has been answered. - -import { expect, mock, test } from 'claude-code/testing' -import type { On } from 'claude-code' - -const ENV = { LICH_SESSION_ID: 'lich-1' } -const REFUSAL = 'compact is a built-in CLI command, not a skill.' - -function world(on: On) { - const ran: unknown[] = [] - mock.env(on, ENV) - const clock = mock.clock(on) - on('session.start', async (_$, e) => ({ cwd: e.cwd })) - // The kit has no command list of its own ("no implementation for - // command.list", measured on 2.1.295): this hook stands for the session's. - on('command.list', async () => ({ value: [{ name: 'compact', description: '', source: 'builtin' }] })) - on('tool.call', { tool: 'Skill' }, async () => ({ result: `Error: ${REFUSAL}`, isError: true as const })) - on('command.run', async (_$, e) => { - ran.push({ command: e.command, args: e.args, origin: e.origin }) - return { text: '' } - }) - return { ran, clock } -} - -test('a built-in the Skill tool refused runs as the plugin after the call is answered', async ($, on) => { - const w = world(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - const answer = await $.tool.call({ tool: 'Skill', skill: 'compact', args: 'keep the plan' }) - expect(answer.result).toEqual({ success: true, commandName: 'compact' }) - expect(w.ran).toEqual([]) - await w.clock.settle() - expect(w.ran).toEqual([{ command: 'compact', args: 'keep the plan', origin: { kind: 'plugin', name: 'lich' } }]) -}) - -test('a non-interactive run leaves the refusal alone', async ($, on) => { - const w = world(on) - await $.session.start({ cwd: '/w', surface: null, isInteractive: false }) - const answer = await $.tool.call({ tool: 'Skill', skill: 'compact' }) - expect(answer.isError).toBe(true) - await w.clock.settle() - expect(w.ran).toEqual([]) -}) diff --git a/tests/self-command.test.mjs b/tests/self-command.test.mjs deleted file mode 100644 index 70dc647..0000000 --- a/tests/self-command.test.mjs +++ /dev/null @@ -1,257 +0,0 @@ -// Pins the Claude Code mod that runs a built-in slash command the model asks -// for through the Skill tool (hooks/self-command.js): which calls it takes, -// what it queues, and what reaches the model. -// -// Like the other mod suites it imports the module and hands it a fake engine: -// `$.command.list` answers a few commands, `$.command.run` records each run, -// `$.process.run` answers `lich whoami --json` with this session, and a -// `$.clock.after` timer runs when the test fires it. -// -// Run: node --test tests/ - -import { test } from 'node:test' -import assert from 'node:assert/strict' - -import { register } from '../hooks/self-command.js' - -const COMMANDS = [ - { name: 'compact', description: 'Compacts the conversation.', source: 'builtin' }, - { name: 'clear', description: 'Clears the conversation.', source: 'builtin' }, - { name: 'model', description: 'Sets the model.', source: 'builtin' }, - { name: 'effort', description: 'Sets the effort.', source: 'builtin' }, - { name: 'deploy', description: 'A user command.', source: 'user' }, -] - -// What the Skill tool answers for a built-in, as Claude Code 2.1.295 did. -const refusedBy = (name) => { - const text = `${name} is a built-in CLI command, not a skill. Ask the user to run /${name} themselves — it cannot be invoked via the Skill tool.` - return { ref: 1, result: `Error: ${text}`, text: `${text}`, isError: true } -} -const LOADED = { ref: 1, result: { success: true, commandName: 'review' }, text: 'Launching skill: review' } - -// What lich's control_session answers, as the lich MCP server did on Claude -// Code 2.1.295: a session targeting itself, and one targeting a peer. -const SELF_REFUSAL = (() => { - const text = - '"fix/x" is this session, and a session cannot control itself: an abort would end the turn asking for it, ' + - 'and a prompt or a slash command would only run once that turn is over' - return { ref: 1, result: `Error: ${text}`, text, isError: true } -})() -const NO_SUCH = { ref: 1, result: 'Error: no session named "ghost"', text: 'no session named "ghost"', isError: true } -const DELIVERED = { ref: 1, result: 'ran /compact on "peer"', text: 'ran /compact on "peer"' } - -const CONTROL = 'mcp__lich__control_session' - -// This session as `lich whoami --json` prints it (docs/cli.md in lich). -const WHOAMI = { label: 'fix/x', name: 'lich-plugin-a1b2', project: 'lich-plugin', kind: 'claude', state: 'busy', id: 'lich-1' } - -/** Registers the module against a fake engine started with `env`. */ -async function session({ - env = { LICH_SESSION_ID: 'lich-1', LICH_BIN: '/bin/lich' }, - isInteractive = true, - runFails = false, - whoami = { exitCode: 0, stdout: JSON.stringify(WHOAMI) }, -} = {}) { - const hooks = {} - register((event, matcher, hook) => { - hooks[`${event} ${JSON.stringify(matcher)}`] = hook - }) - const runs = [] - const toasts = [] - const timers = [] - const invalidated = [] - const processes = [] - const $ = { - env: { get: async (name) => env[name] }, - clock: { after: (ms, fn) => timers.push({ ms, fn }) }, - command: { - list: async () => COMMANDS, - run: async (input) => { - runs.push(input) - if (runFails) throw new Error('the command queue is closed') - return {} - }, - }, - ui: { toast: (text) => toasts.push(text), invalidate: (event) => invalidated.push(event) }, - process: { - run: async (argv) => { - processes.push(argv) - assert.deepEqual(argv, ['/bin/lich', 'whoami', '--json']) - return { stderr: '', ...whoami } - }, - }, - } - const start = hooks['session.start {"isInteractive":true}'] - if (isInteractive) await start($, { cwd: '/w', surface: 'terminal', isInteractive }, async (e) => e) - return { - runs, - toasts, - timers, - invalidated, - processes, - describe: (description) => - hooks['tool.describe {"tool":"Skill"}']($, { tool: 'Skill', description }, async (e) => ({ description: e.description })), - call: (input, beneath) => - hooks['tool.call {"tool":"Skill"}']($, { tool: 'Skill', tool_use_id: 'toolu_1', ...input }, async () => beneath), - describeControl: (description) => - hooks[`tool.describe {"tool":"${CONTROL}"}`]($, { tool: CONTROL, description }, async (e) => ({ - description: e.description, - })), - control: (input, beneath) => - hooks[`tool.call {"tool":"${CONTROL}"}`]($, { tool: CONTROL, tool_use_id: 'toolu_2', ...input }, async () => beneath), - fire: async () => { - for (const timer of timers.splice(0)) await timer.fn() - }, - } -} - -test('a built-in the Skill tool refused is queued, and runs only after the hook answered', async () => { - const mod = await session() - const answer = await mod.call({ skill: 'compact', args: ' focus on the tests ' }, refusedBy('compact')) - - assert.deepEqual(answer.result, { success: true, commandName: 'compact' }) - assert.match(answer.context[0], /\/compact focus on the tests is queued and runs once this turn ends/) - assert.deepEqual(mod.runs, [], 'ran inside the hook the turn is waiting on') - await mod.fire() - assert.deepEqual(mod.runs, [{ command: 'compact', args: 'focus on the tests' }]) -}) - -test('a leading slash in the name is dropped', async () => { - const mod = await session() - await mod.call({ skill: '/clear' }, refusedBy('/clear')) - await mod.fire() - assert.deepEqual(mod.runs, [{ command: 'clear', args: '' }]) -}) - -test('/model and /effort are refused and never run: they would save a default for every session', async () => { - const mod = await session() - for (const name of ['model', 'effort']) { - const answer = await mod.call({ skill: name, args: 'opus' }, refusedBy(name)) - assert.match(answer.deny, new RegExp(`/${name} .*default for every new Claude Code session`)) - assert.match(answer.deny, /lich/) - } - await mod.fire() - assert.deepEqual(mod.runs, []) -}) - -test('what the Skill tool served stays its own', async () => { - const mod = await session() - assert.equal(await mod.call({ skill: 'review' }, LOADED), LOADED) - assert.equal(mod.timers.length, 0) -}) - -test('a refusal for a name that is no built-in reaches the model untouched', async () => { - const mod = await session() - for (const name of ['deploy', 'nonexistent']) { - const refused = refusedBy(name) - assert.equal(await mod.call({ skill: name }, refused), refused) - } - assert.equal(mod.timers.length, 0) -}) - -test('a command that fails once queued says so in a toast', async () => { - const mod = await session({ runFails: true }) - await mod.call({ skill: 'compact' }, refusedBy('compact')) - await mod.fire() - assert.deepEqual(mod.toasts, ['/compact did not run: the command queue is closed']) -}) - -test('the Skill description tells the model it can name a built-in, and is redrawn once enabled', async () => { - const mod = await session() - assert.deepEqual(mod.invalidated, ['tool.describe']) - const { description } = await mod.describe('Execute a skill.') - assert.ok(description.startsWith('Execute a skill.')) - assert.match(description, /built-in slash command .* queued and runs once your turn ends/) -}) - -test('a built-in lich refused because the target is this session is queued on it', async () => { - const mod = await session() - const answer = await mod.control( - { session: 'fix/x', action: 'command', value: '/compact', args: ' keep the plan ' }, - SELF_REFUSAL, - ) - - assert.match(answer.result, /\/compact keep the plan is queued on this session and runs once this turn ends/) - assert.equal(answer.isError, undefined) - assert.deepEqual(mod.runs, [], 'ran inside the hook the turn is waiting on') - await mod.fire() - assert.deepEqual(mod.runs, [{ command: 'compact', args: 'keep the plan' }]) -}) - -test('control_session naming this session by its id, label or name, in any case, is queued on it', async () => { - for (const target of ['lich-1', 'fix/x', 'FIX/X', 'lich-plugin-a1b2']) { - const mod = await session() - const answer = await mod.control({ session: target, action: 'command', value: 'compact' }, SELF_REFUSAL) - assert.match(answer.result, /\/compact is queued on this session/, target) - await mod.fire() - assert.deepEqual(mod.runs, [{ command: 'compact', args: '' }], target) - } -}) - -test('lich refusing a target that whoami does not name as this session reaches the model untouched', async () => { - const mod = await session() - assert.equal(await mod.control({ session: 'other', action: 'command', value: 'compact' }, SELF_REFUSAL), SELF_REFUSAL) - assert.equal(mod.timers.length, 0) -}) - -test('when whoami fails, only the session id is taken as this session', async () => { - const mod = await session({ whoami: { exitCode: 1, stdout: '' } }) - assert.equal(await mod.control({ session: 'fix/x', action: 'command', value: 'compact' }, SELF_REFUSAL), SELF_REFUSAL) - const answer = await mod.control({ session: 'lich-1', action: 'command', value: 'compact' }, SELF_REFUSAL) - assert.match(answer.result, /\/compact is queued on this session/) -}) - -test('whoami runs only for a refused command, never for a delivered one', async () => { - const mod = await session() - await mod.control({ session: 'peer', action: 'command', value: 'compact' }, DELIVERED) - await mod.control({ session: 'fix/x', action: 'abort' }, SELF_REFUSAL) - assert.deepEqual(mod.processes, []) -}) - -test('control_session on this session refuses /model and /effort, and never runs them', async () => { - const mod = await session() - for (const name of ['model', 'effort']) { - const answer = await mod.control({ session: 'fix/x', action: 'command', value: name }, SELF_REFUSAL) - assert.match(answer.deny, new RegExp(`/${name} .*default for every new Claude Code session`)) - } - await mod.fire() - assert.deepEqual(mod.runs, []) -}) - -test('what lich answered for another session, or for no self command, reaches the model untouched', async () => { - const mod = await session() - for (const [input, beneath] of [ - [{ session: 'peer', action: 'command', value: 'compact' }, DELIVERED], - [{ session: 'ghost', action: 'command', value: 'compact' }, NO_SUCH], - [{ session: 'fix/x', action: 'abort' }, SELF_REFUSAL], - [{ session: 'fix/x', action: 'prompt', value: 'hi' }, SELF_REFUSAL], - [{ session: 'fix/x', action: 'command', value: 'deploy' }, SELF_REFUSAL], - ]) { - assert.equal(await mod.control(input, beneath), beneath) - } - assert.equal(mod.timers.length, 0) -}) - -test('the control_session description says a command on this session is accepted', async () => { - const mod = await session() - const { description } = await mod.describeControl('Drive another session. Claude Code sessions only, and never your own.') - assert.ok(description.startsWith('Drive another session.')) - assert.match(description, /action command .* this session itself as the target: pass session "lich-1"/) - assert.match(description, /queued and runs once your turn ends/) -}) - -for (const [why, options] of [ - ['outside lich', { env: {} }], - ['in a non-interactive run', { isInteractive: false }], -]) { - test(`${why} the mod changes nothing`, async () => { - const mod = await session(options) - const refused = refusedBy('compact') - assert.equal(await mod.call({ skill: 'compact' }, refused), refused) - assert.deepEqual(await mod.describe('Execute a skill.'), { description: 'Execute a skill.' }) - assert.equal(await mod.control({ session: 'fix/x', action: 'command', value: 'compact' }, SELF_REFUSAL), SELF_REFUSAL) - assert.deepEqual(await mod.describeControl('Drive.'), { description: 'Drive.' }) - assert.equal(mod.timers.length, 0) - assert.deepEqual(mod.invalidated, []) - }) -} diff --git a/tests/status-line.test.mjs b/tests/status-line.test.mjs deleted file mode 100644 index 6a6d261..0000000 --- a/tests/status-line.test.mjs +++ /dev/null @@ -1,46 +0,0 @@ -// Pins hooks/status-line.js: the mods' parts share one lich line, drawn among -// the mode labels at the right of Claude Code's prompt footer. -// -// Run: node --test tests/ - -import { test } from 'node:test' -import assert from 'node:assert/strict' - -import { footerLine } from './contract.mjs' -import { register, setStatusPart } from '../hooks/status-line.js' - -test('parts share the one line in a fixed order, and the line goes with the last part', () => { - const lines = [] - for (const [part, text] of [ - ['edits', 'app.js also edited by "docs"'], - ['errands', '1 task out'], - ['edits', undefined], - ['errands', undefined], - ]) { - setStatusPart(part, text) - lines.push(footerLine()) - } - - assert.deepEqual(lines, [ - 'lich: app.js also edited by "docs"', - 'lich: 1 task out · app.js also edited by "docs"', - 'lich: 1 task out', - undefined, - ]) -}) - -test("the line goes after Claude Code's own modes, which are kept", () => { - let draw - register((event, matcher, hook) => { - assert.equal(event, 'ui.render') - assert.deepEqual(matcher, { component: 'SessionMode' }) - draw = hook - }) - const e = { surface: 'terminal', component: 'SessionMode', requestId: 'footer', props: { modes: ['focus'] } } - const passOn = (rewritten) => rewritten - - assert.equal(draw({}, e, passOn), e, 'with no part the footer is passed on untouched') - setStatusPart('errands', '1 task out') - assert.deepEqual(draw({}, e, passOn).props.modes, ['focus', 'lich: 1 task out']) - setStatusPart('errands', undefined) -}) diff --git a/tests/touched.test.mjs b/tests/touched.test.mjs new file mode 100644 index 0000000..f9f13d8 --- /dev/null +++ b/tests/touched.test.mjs @@ -0,0 +1,379 @@ +// Pins the session-touched clients to lich's contract: the paths each harness +// sends for its own write, `hold` where the harness cannot show the note there, +// `collect` before its next model call, and the note lich answers with, handed +// to the model in the harness's own shape and byte for byte. The script +// harnesses run hooks/report-touched.sh as their registration spells it; +// opencode and omp run their modules in process. +// +// The notes are lich's, replayed from session-touched.jsonl. The payloads are +// the providers' own as measured on 2026-11-23 (docs/session-touched.md), cut +// to the fields that matter. +// +// Run: node --test tests/ + +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { spawn } from 'node:child_process' +import { mkdtempSync, readFileSync, symlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + +import { CASES, LICH_SESSION_ID, ROOT, TOKEN, assertContractHonoured, assertReportHonoured, lichEnv, settleStubs, startStub, withStub } from './contract.mjs' +import { LichPlugin } from '../opencode/lich.js' +import lichPlugin from '../omp/lich.js' + +const ENDPOINT = '/session-touched' +const NOTES = [...new Set(CASES[ENDPOINT].map((c) => c.answer?.note).filter(Boolean))] +const NOTE = NOTES[0] + +// ---------------------------------------------------------------- clients -- + +const BASE_ENV = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith('LICH_'))) +const TMP = mkdtempSync(path.join(tmpdir(), 'lich-plugin-touched-')) +const SPACED_ROOT = path.join(TMP, 'Application Support') +symlinkSync(ROOT, SPACED_ROOT) + +const read = (file) => JSON.parse(readFileSync(path.join(ROOT, file), 'utf8')) +const hooksIn = (group) => (Array.isArray(group.hooks) ? group.hooks : [group]) + +/** The registered touched command a hook file runs on `event`. */ +function touchedCommand(file, event) { + const events = read(file).hooks ?? read(file).lich + for (const group of events[event] ?? []) { + for (const hook of hooksIn(group)) if (hook.command.includes('report-touched.sh')) return hook.command + } + assert.fail(`${file} registers no touched hook on ${event}`) +} + +// Kiro's hooks are written by lich into the agent's config, so the suite runs +// the lines lich registers (docs/session-touched.md, Registration). +const COMMANDS = { + claude: touchedCommand('hooks/hooks.json', 'PostToolUse'), + codex: touchedCommand('hooks/codex-hooks.json', 'PostToolUse'), + crush: touchedCommand('hooks/crush-hooks.json', 'PostToolUse').split('').join(SPACED_ROOT), + 'crush-pre': `"${SPACED_ROOT}/hooks/report-touched.sh"`, + 'antigravity-hold': touchedCommand('hooks.json', 'PostToolUse'), + 'antigravity-collect': touchedCommand('hooks.json', 'PreInvocation'), + 'kiro-hold': `"${SPACED_ROOT}/hooks/report-touched.sh" hold`, + 'kiro-collect': `"${SPACED_ROOT}/hooks/report-touched.sh" collect`, +} + +/** Antigravity runs a hook with the plugin root as its working directory. */ +function runScript(client, payload, env) { + return new Promise((resolve) => { + const child = spawn('/bin/sh', ['-c', COMMANDS[client]], { + cwd: SPACED_ROOT, + env: { + ...BASE_ENV, + ...(client.startsWith('antigravity') ? {} : { CLAUDE_PLUGIN_ROOT: SPACED_ROOT }), + ...env, + }, + stdio: ['pipe', 'pipe', 'pipe'], + }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (c) => (stdout += c)) + child.stderr.on('data', (c) => (stderr += c)) + child.stdin.on('error', () => {}) + child.stdin.end(JSON.stringify(payload)) + child.on('close', (code) => settleStubs().then(() => resolve({ code, stdout, stderr }))) + }) +} + +async function withEnv(env, fn) { + const saved = { ...process.env } + for (const key of Object.keys(process.env)) if (key.startsWith('LICH_')) delete process.env[key] + Object.assign(process.env, env) + try { + return await fn() + } finally { + for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key] + Object.assign(process.env, saved) + } +} + +/** + * Runs one client on its payload and returns the note the model is handed, or + * null when it is handed none. A shape the harness would not read fails here. + */ +async function delivered(client, payload, env) { + if (client === 'opencode') { + return withEnv(env, async () => { + const hooks = await LichPlugin() + const output = { title: 't', output: 'Wrote file successfully.', metadata: payload.metadata ?? {} } + await hooks['tool.execute.after'](payload.input, output) + if (output.output === 'Wrote file successfully.') return null + assert.ok(output.output.startsWith('Wrote file successfully.\n\n'), 'the note goes after the tool output') + return output.output.slice('Wrote file successfully.\n\n'.length) + }) + } + if (client === 'omp') { + return withEnv(env, async () => { + const handlers = new Map() + lichPlugin({ on: (name, handler) => handlers.set(name, [...(handlers.get(name) ?? []), handler]) }) + const ctx = { sessionManager: { getSessionId: () => 'p1' } } + const answers = await Promise.all((handlers.get('tool_result') ?? []).map((h) => h(payload, ctx))) + const given = answers.filter((a) => a !== undefined) + if (given.length === 0) return null + assert.equal(given.length, 1) + assert.deepEqual(Object.keys(given[0]), ['additionalContext']) + return given[0].additionalContext + }) + } + const result = await runScript(client, payload, env) + assert.equal(result.code, 0, `exited ${result.code}: ${result.stderr}`) + const out = result.stdout + switch (client) { + case 'claude': + case 'codex': { + if (out === '') return null + const json = JSON.parse(out) + assert.deepEqual(json, { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: json.hookSpecificOutput.additionalContext } }) + return json.hookSpecificOutput.additionalContext + } + case 'crush': { + if (out === '') return null + const json = JSON.parse(out) + assert.deepEqual(Object.keys(json).sort(), ['context', 'version']) + assert.equal(json.version, 1) + return json.context + } + case 'crush-pre': + case 'kiro-hold': + assert.equal(out, '', 'a touch that cannot show a note prints nothing') + return null + case 'antigravity-hold': + assert.equal(out, '{}', 'Antigravity gets its verdict and nothing else') + return null + case 'antigravity-collect': { + const json = JSON.parse(out) + if (Object.keys(json).length === 0) return null + assert.equal(json.injectSteps.length, 1) + assert.deepEqual(Object.keys(json.injectSteps[0]), ['systemMessage']) + return json.injectSteps[0].systemMessage.systemMessage + } + case 'kiro-collect': + return out === '' ? null : out + } + throw new Error(`no client ${client}`) +} + +const IN_PROCESS = new Set(['opencode', 'omp']) + +/** The one touched request a stub got, held to the contract. */ +function touchedRequest(client, stub) { + const asked = stub.requests.filter((r) => r.url.split('?')[0] === ENDPOINT) + assert.equal(asked.length, 1, `${client} reported ${asked.length} times`) + const [request] = asked + if (IN_PROCESS.has(client)) return assertContractHonoured(ENDPOINT, request).body + assert.equal(request.url, ENDPOINT) + assert.equal(request.headers.authorization, `Bearer ${TOKEN}`) + return assertReportHonoured(ENDPOINT, request).body +} + +// --------------------------------------------------------------- payloads -- + +const PATCH = '*** Begin Patch\n*** Add File: a.go\n+x\n*** Update File: sub/../b.go\n@@\n-x\n+y\n*** Move to: c.go\n*** Delete File: ./d.go\n*** End Patch' + +/** One write per client, the body lich must get for it, and whether it can carry a note. */ +const WRITES = [ + { + client: 'claude', + payload: { session_id: 'p1', cwd: '/repo', hook_event_name: 'PostToolUse', tool_name: 'Write', tool_input: { file_path: '/repo/a.go', content: 'x' } }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/a.go'] }, + }, + { + name: 'a Cursor CLI write, through the Claude Code install', + client: 'claude', + payload: { + conversation_id: 'p1', + session_id: 'p1', + hook_event_name: 'postToolUse', + tool_name: 'Write', + tool_input: { file_path: '/repo/a.go', contents: 'x' }, + tool_use_id: 'call-1', + cursor_version: '2026.11.22-e9042b2', + }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/a.go'] }, + }, + { + client: 'codex', + payload: { session_id: 'p1', turn_id: 't1', cwd: '/repo', hook_event_name: 'PostToolUse', tool_name: 'apply_patch', tool_input: { command: PATCH }, tool_use_id: 'call_1' }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/a.go', '/repo/b.go', '/repo/c.go', '/repo/d.go'] }, + }, + { + client: 'crush', + payload: { event: 'PostToolUse', hook_event_name: 'PostToolUse', session_id: 'p1', cwd: '/repo', tool_name: 'edit', tool_input: { file_path: '/repo/a.go' }, tool_response: 'ok', tool_use_id: 'call_1' }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/a.go'] }, + }, + { + client: 'opencode', + payload: { input: { tool: 'write', sessionID: 'p1', callID: 'c1', args: { filePath: '/repo/a.go', content: 'x' } }, metadata: { filepath: '/repo/a.go' } }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/a.go'] }, + }, + { + name: 'an opencode apply_patch', + client: 'opencode', + payload: { + input: { tool: 'apply_patch', sessionID: 'p1', callID: 'c2', args: { patchText: PATCH } }, + metadata: { files: [{ filePath: '/repo/a.go', relativePath: 'a.go' }, { filePath: '/repo/b.go', relativePath: 'b.go' }] }, + }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/a.go', '/repo/b.go'] }, + }, + { + client: 'omp', + payload: { type: 'tool_result', toolCallId: 'c', toolName: 'write', input: { path: 'a.go' }, content: [], isError: false, details: { resolvedPath: '/repo/a.go' } }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/a.go'] }, + }, + { + name: 'an oh-my-pi edit', + client: 'omp', + payload: { type: 'tool_result', toolCallId: 'c', toolName: 'edit', input: { path: 'a.go' }, content: [], isError: false, details: { op: 'update', path: '/repo/a.go' } }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/a.go'] }, + }, +] + +/** The writes whose hook cannot hand the model text: lich holds the note. */ +const HELD = [ + { + client: 'antigravity-hold', + payload: { conversationId: 'p1', cwd: '/repo', hookEventName: 'PostToolUse', stepIdx: 4, toolCall: { id: 'call_1', name: 'edit_file', args: { Path: '/repo/a.go' } }, error: '' }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/a.go'], hold: true }, + }, + { + client: 'kiro-hold', + payload: { hook_event_name: 'postToolUse', cwd: '/repo', session_id: 'p1', tool_name: 'write', tool_input: { command: 'create', path: 'notes/./a.go', content: 'x' } }, + body: { session_id: LICH_SESSION_ID, paths: ['/repo/notes/a.go'], hold: true }, + }, +] + +/** The hooks that run before the next model call and collect what was held. */ +const COLLECTS = [ + { client: 'antigravity-collect', payload: { conversationId: 'p1', cwd: '/repo', hookEventName: 'PreInvocation', stepIdx: 5 } }, + { client: 'kiro-collect', payload: { hook_event_name: 'userPromptSubmit', cwd: '/repo', session_id: 'p1', prompt: 'go on' } }, +] + +const label = (c) => c.name ?? `a ${c.client} write` +const noteAnswer = (note) => ({ status: 200, body: JSON.stringify({ note }) }) + +// ---------------------------------------------------------------- requests -- + +for (const w of [...WRITES, ...HELD]) { + test(`${label(w)}: reports its files the way the contract spells them`, async () => { + await withStub(async (stub) => { + await delivered(w.client, w.payload, lichEnv(stub.port)) + assert.deepEqual(touchedRequest(w.client, stub), w.body) + }) + }) +} + +for (const c of COLLECTS) { + test(`${c.client}: asks for the held note and nothing else`, async () => { + await withStub(async (stub) => { + await delivered(c.client, c.payload, lichEnv(stub.port)) + assert.deepEqual(touchedRequest(c.client, stub), { session_id: LICH_SESSION_ID, collect: true }) + }) + }) +} + +// A shell names no file: the touch is the refresh alone, and it can still carry +// a note lich kept for the session (a held one, on a harness that cannot hold). +const SHELLS = [ + ['claude', { session_id: 'p1', cwd: '/repo', hook_event_name: 'PostToolUse', tool_name: 'Bash', tool_input: { command: 'make' } }], + ['codex', { session_id: 'p1', cwd: '/repo', hook_event_name: 'PostToolUse', tool_name: 'Bash', tool_input: { command: 'make' } }], + ['crush', { event: 'PostToolUse', hook_event_name: 'PostToolUse', session_id: 'p1', cwd: '/repo', tool_name: 'bash', tool_input: { command: 'make' } }], + ['opencode', { input: { tool: 'bash', sessionID: 'p1', callID: 'c', args: { command: 'make' } } }], + ['omp', { type: 'tool_result', toolCallId: 'c', toolName: 'bash', input: { command: 'make' }, content: [], isError: false, details: {} }], +] +for (const [client, payload] of SHELLS) { + test(`${client}: a shell call is the refresh alone, with no paths`, async () => { + await withStub(async (stub) => { + await delivered(client, payload, lichEnv(stub.port)) + assert.deepEqual(touchedRequest(client, stub), { session_id: LICH_SESSION_ID }) + }) + }) +} + +test('Antigravity reports run_command as the refresh alone, held', async () => { + await withStub(async (stub) => { + const payload = { conversationId: 'p1', cwd: '/repo', hookEventName: 'PostToolUse', toolCall: { id: 'c', name: 'run_command', args: { CommandLine: 'make' } } } + assert.equal(await delivered('antigravity-hold', payload, lichEnv(stub.port)), null) + assert.deepEqual(touchedRequest('antigravity-hold', stub), { session_id: LICH_SESSION_ID, hold: true }) + }) +}) + +// On a Crush older than v0.99.0 lich keeps the hook on PreToolUse: before the +// write, so it stays the refresh it was, with no paths and nothing printed. +test('a Crush PreToolUse touch is the refresh alone and prints nothing', async () => { + await withStub( + async (stub) => { + const payload = { event: 'PreToolUse', hook_event_name: 'PreToolUse', session_id: 'p1', cwd: '/repo', tool_name: 'edit', tool_input: { file_path: '/repo/a.go' } } + assert.equal(await delivered('crush-pre', payload, lichEnv(stub.port)), null) + assert.deepEqual(touchedRequest('crush-pre', stub), { session_id: LICH_SESSION_ID }) + }, + noteAnswer(NOTE), + ) +}) + +// ------------------------------------------------------------------- notes -- + +// Every note lich's fixture answers with, plus one in another script with a +// quote and a trailing newline, reaches the model as written. +const ALL_NOTES = [...NOTES, 'A sessão lich "Ação" também editou /repo/a.go.\n'] + +for (const c of [...WRITES, ...COLLECTS]) { + test(`${label(c)}: hands the model every note lich answers with, byte for byte`, async () => { + for (const note of ALL_NOTES) { + await withStub(async (stub) => { + assert.equal(await delivered(c.client, c.payload, lichEnv(stub.port)), note) + }, noteAnswer(note)) + } + }) + + test(`${label(c)}: a 204 hands the model nothing`, async () => { + await withStub(async (stub) => { + assert.equal(await delivered(c.client, c.payload, lichEnv(stub.port)), null) + }) + }) +} + +for (const h of HELD) { + test(`${label(h)}: a held touch shows nothing, whatever lich answers`, async () => { + await withStub(async (stub) => { + assert.equal(await delivered(h.client, h.payload, lichEnv(stub.port)), null) + }, noteAnswer(NOTE)) + }) +} + +// --------------------------------------------------------------- fail open -- + +const FAILURES = [ + ['a 500', { status: 500, body: JSON.stringify({ note: NOTE }) }], + ['a 200 that is not JSON', { status: 200, body: 'note' }], + ['a 200 with no note', { status: 200, body: '{}' }], + ['a 200 with an empty note', { status: 200, body: '{"note":""}' }], +] + +for (const c of [...WRITES, ...COLLECTS]) { + test(`${label(c)}: outside lich nothing is reported and nothing shown`, async () => { + await withStub(async (stub) => { + assert.equal(await delivered(c.client, c.payload, {}), null) + assert.equal(stub.requests.length, 0) + }) + }) + + test(`${label(c)}: a refused connection shows nothing`, async () => { + const stub = await startStub() + const env = lichEnv(stub.port) + await stub.close() + assert.equal(await delivered(c.client, c.payload, env), null) + }) + + for (const [what, answer] of FAILURES) { + test(`${label(c)}: ${what} shows nothing`, async () => { + await withStub(async (stub) => { + assert.equal(await delivered(c.client, c.payload, lichEnv(stub.port)), null) + }, answer) + }) + } +}