diff --git a/.claude/settings.json b/.claude/settings.json index d42490d..7b99da2 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -6,7 +6,7 @@ { "id": "ai-prompt-auto-commit", "type": "command", - "command": "input=$(cat); ts=$(date +%Y-%m-%dT%H-%M-%S); model=$(printf '%s' \"$input\" | jq -r '.model // \"claude-sonnet-4-6\"'); root=$(git rev-parse --show-toplevel 2>/dev/null || pwd); mkdir -p \"$root/.prompts\"; printf '%s' \"$input\" | jq -r '.prompt' > \"$root/.prompts/${ts}_${model}.txt\"", + "command": "f=\"${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/record-prompt.py\"; [ -f \"$f\" ] && python3 \"$f\"; exit 0", "version": "0.0.9" } ] diff --git a/.github/assistant-guidelines.md b/.github/assistant-guidelines.md index a0de3a2..e5b1f4a 100644 --- a/.github/assistant-guidelines.md +++ b/.github/assistant-guidelines.md @@ -2,8 +2,6 @@ version: "0.0.9" --- - - # Assistant Guidelines for `.prompts` Storage These guidelines tell the assistant exactly how to write prompt files in this repository. diff --git a/.gitignore b/.gitignore index 0699456..2a1351c 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ build/ .pytest_cache/ /ai-prompt-auto-commit-test /.prompts/ +# generated from ai_prompt_auto_commit/data/record_prompt.py by prepare-ai-repository +/.claude/hooks/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 32b1346..df68bd0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,6 +13,7 @@ repos: - id: detect-private-key - id: end-of-file-fixer - id: name-tests-test + args: [--pytest-test-first] # this project names tests test_*.py - id: trailing-whitespace - repo: local diff --git a/CHANGES.md b/CHANGES.md index 2feaf2f..65d53ce 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,29 @@ +## v0.0.10 + +- fix: the recorded model is now the model that actually answered. Every + prompt was recorded as `claude-sonnet-4-6` before, whichever model you + were using. +- fix: only prompts you wrote yourself are recorded. Turns that Claude Code + injects on its own, such as background-task notifications, were being + written to `.prompts/` and copied into commit messages. +- fix: `jq` is no longer needed. It was never listed as a requirement, and + without it prompt files were silently written empty. +- fix: two prompts sent within the same second no longer overwrite each + other. +- fix: `prepare-ai-repository` no longer adds a blank line to + `.github/assistant-guidelines.md` every time it runs. +- The Claude Code hook now lives in `.claude/hooks/record-prompt.py`, + installed by `prepare-ai-repository`. Re-run it to upgrade. +- fix: prompts recorded in the same second are now listed in the order you + sent them. A numbered file sorted ahead of the one it followed. +- fix: `record-ai-prompt` took its sequence number from the wrong part of + the timestamp, so numbering jumped to whatever the minute happened to be. +- dev: `name-tests-test` enforces this project's own `test_*.py` naming + instead of failing on every test file. + ## v0.0.9 - fix: ensure newline before automatically added gitignore entry diff --git a/README.md b/README.md index d39be2f..f169f4b 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Automatically records every AI prompt you send and appends them to your git comm ## How it works -1. **Claude Code** saves every prompt to `.prompts/` as a timestamped Markdown file (via a `UserPromptSubmit` hook in `.claude/settings.json`). Other models can also be instructed to do so. +1. **Claude Code** saves every prompt to `.prompts/` as a timestamped file, named after the model that answered it (via a `UserPromptSubmit` hook in `.claude/settings.json`, which runs `.claude/hooks/record-prompt.py`). Only prompts you actually wrote are recorded — the turns Claude Code injects on its own, such as background-task notifications, are skipped. Other models can also be instructed to record prompts. 2. On `git commit`, the **`prepare-commit-msg`** hook reads all pending prompts and appends them to the commit message under an `AI Prompts:` section. 3. After the commit, the **`post-commit`** hook moves the used prompts to `.prompts/committed/`, tagged with the commit hash, so they are archived but not reused. @@ -71,6 +71,7 @@ pre-commit run --hook-stage manual prepare-ai-repository This runs the one-time setup (using the `manual` stage) and will: - Create a `.prompts/` directory with a `.gitignore` that prevents prompt files from being committed +- Install the prompt-recording script as `.claude/hooks/record-prompt.py` - Install the Claude Code `UserPromptSubmit` hook into `.claude/settings.json` so prompts are recorded automatically (merges safely with existing settings) ## Updating @@ -93,19 +94,26 @@ This pre-commit supports the following AI models: | Model | ID in commit message | | --- | --- | -| Claude Sonnet 4.6 | `claude-sonnet-4-6` | -| Claude Opus 4.6 | `claude-opus-4-6` | -| Claude Haiku 4.5 | `claude-haiku-4-5-20251001` | -| Any future Claude model | recorded automatically | +| Any Claude model | recorded automatically, e.g. `claude-opus-5` or `claude-sonnet-4-6` | | GitHub Copilot | manual prompt recording | +Claude model IDs are taken verbatim from the session transcript, so new models +need no change here. + ### Claude -The recording is done automatically through the hooks. +The recording is done automatically through the hooks. The model name is read +from the session transcript, which records a model only once it has answered. +The name is therefore the model that answered the previous turn: after a +`/model` switch, the first prompt you send is still attributed to the model +you switched away from, and only the ones after that are right. A prompt sent +before the assistant has answered even once — the first prompt of a session — +is recorded as `unknown`, because at that point nothing has stated which model +is answering. #### Trouble Shooting -If no files are created in `.promts`: +If no files are created in `.prompts`: - Restart the editor or session. - Or open /hooks in Claude Code (the UI menu) to reload config. @@ -135,12 +143,19 @@ printf "%s" "" | record-ai-prompt ## File layout ```text +.claude/ + settings.json ← calls the hook below on each prompt + hooks/ + record-prompt.py ← installed by prepare-ai-repository .prompts/ 2026-04-12T20-35-51_claude-sonnet-4-6.txt ← pending (not yet committed) committed/ 2026-04-12T20-10-00_claude-sonnet-4-6_a2e1ca7....txt ← archived after commit ``` +`.claude/hooks/record-prompt.py` is rewritten every time `prepare-ai-repository` +runs, so edit the copy in this project rather than the one in your repository. + ## Changelog You can view the versions in the [change log](CHANGES.md). @@ -156,4 +171,3 @@ To release a new version: ## Related work - [cairn](https://github.com/pimalaya/cairn) - Tool-free convention that keeps, beside your code, a living spec of what the system does now plus a dated log of how it got there, readable by any agent, human or AI. - diff --git a/ai_prompt_auto_commit/common.py b/ai_prompt_auto_commit/common.py index 305e52e..6403b3c 100644 --- a/ai_prompt_auto_commit/common.py +++ b/ai_prompt_auto_commit/common.py @@ -22,8 +22,9 @@ def get_prompt_files() -> list[Path]: """Return a list of pending prompt files.""" repo_root = _repo_root() prompts_dir = repo_root / PROMPTS_DIRECTORY - result= [] + result = [] for ending in FILE_ENDINGS: - result.extend(sorted(prompts_dir.glob(f"*{ending}"))) - return result - + result.extend(prompts_dir.glob(f"*{ending}")) + # By write time, not by name: a sequence-numbered "-001_" sorts + # before the plain "_" it followed, because '-' < '_'. + return sorted(result, key=lambda p: (p.stat().st_mtime_ns, p.name)) diff --git a/ai_prompt_auto_commit/data/assistant-guidelines.md b/ai_prompt_auto_commit/data/assistant-guidelines.md index a0de3a2..e5b1f4a 100644 --- a/ai_prompt_auto_commit/data/assistant-guidelines.md +++ b/ai_prompt_auto_commit/data/assistant-guidelines.md @@ -2,8 +2,6 @@ version: "0.0.9" --- - - # Assistant Guidelines for `.prompts` Storage These guidelines tell the assistant exactly how to write prompt files in this repository. diff --git a/ai_prompt_auto_commit/data/claude_settings.json b/ai_prompt_auto_commit/data/claude_settings.json index d42490d..7b99da2 100644 --- a/ai_prompt_auto_commit/data/claude_settings.json +++ b/ai_prompt_auto_commit/data/claude_settings.json @@ -6,7 +6,7 @@ { "id": "ai-prompt-auto-commit", "type": "command", - "command": "input=$(cat); ts=$(date +%Y-%m-%dT%H-%M-%S); model=$(printf '%s' \"$input\" | jq -r '.model // \"claude-sonnet-4-6\"'); root=$(git rev-parse --show-toplevel 2>/dev/null || pwd); mkdir -p \"$root/.prompts\"; printf '%s' \"$input\" | jq -r '.prompt' > \"$root/.prompts/${ts}_${model}.txt\"", + "command": "f=\"${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/record-prompt.py\"; [ -f \"$f\" ] && python3 \"$f\"; exit 0", "version": "0.0.9" } ] diff --git a/ai_prompt_auto_commit/data/record_prompt.py b/ai_prompt_auto_commit/data/record_prompt.py new file mode 100755 index 0000000..1aedfba --- /dev/null +++ b/ai_prompt_auto_commit/data/record_prompt.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Claude Code `UserPromptSubmit` hook: record one prompt in `.prompts/`. + +`prepare-ai-repository` installs a copy of this script into a repository as +`.claude/hooks/record-prompt.py` and points `.claude/settings.json` at it. +Edit the original bundled with ai-prompt-auto-commit, not the installed copy: +the copy is overwritten on every run of `prepare-ai-repository`. + +The hook payload arrives as JSON on stdin and the prompt is written to + + /.prompts/_.txt + +Two things this script is careful about: + +* Only genuine user-authored turns are recorded. Claude Code also submits + machine-injected turns through this hook — task notifications, peer + messages, auto-continuation, scheduled wakeups — and those are not prompts. +* The model name is read out of the session transcript. There is no model in + the hook payload, and guessing produces an attribution record that quietly + lies; `unknown` is written instead when it cannot be established. + +Nothing is ever written to stdout: for `UserPromptSubmit`, stdout is injected +into the conversation as additional context. Failures are reported on stderr +and the hook still exits 0, because a recording hook must not block a prompt. + +Depends on the standard library only, so that a repository using +ai-prompt-auto-commit needs nothing beyond the Python it already requires. +""" + +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +from datetime import datetime +from pathlib import Path + +HOOK_VERSION = "0.0.0" # replaced with the package version at install time + +PROMPTS_DIRECTORY = ".prompts" +FILE_EXTENSION = ".txt" +UNKNOWN_MODEL = "unknown" + +# A model name goes into a filename, where `_` separates it from the timestamp +# and `/` would be a directory. Gateway and proxy setups report ids such as +# "anthropic/claude-opus-5", so anything outside this set is folded to `-`. +UNSAFE_IN_FILENAME = re.compile(r"[^A-Za-z0-9.@+-]+") + +# `source` names who authored the turn. `user` is the interactive composer and +# `sdk` the non-interactive entrypoint (`-p` / Agent SDK); both are the human. +# Everything else — `system` (task notifications, peer/channel messages, +# auto-continuation), `loop_wakeup`, `schedule_wakeup`, `poll_event` — is +# machine-injected. The field is documented as possibly absent while it rolls +# out, so a payload without it falls through to the prefix check below. +HUMAN_SOURCES = frozenset({"user", "sdk"}) + +# Machine-injected turns are wrapped in one of these tags. Belt and braces for +# payloads that carry no `source`. +SYNTHETIC_PREFIXES = ( + "", + "", + "", + "", + "", + "", +) + +# Transcripts grow without bound, and this runs on every prompt, so only the +# tail is read; a full scan is the fallback when the tail holds no answer. +TAIL_BYTES = 1 << 20 + + +def _model_of(line: str) -> str: + """Return the model of a transcript line, or "" if it names none.""" + try: + entry = json.loads(line) + except ValueError: + return "" + if not isinstance(entry, dict) or entry.get("type") != "assistant": + return "" + if entry.get("isSidechain"): + return "" # a subagent's model, not the one answering this prompt + message = entry.get("message") + model = message.get("model", "") if isinstance(message, dict) else "" + if not isinstance(model, str) or model.startswith("<"): + return "" # placeholders such as "" + return model + + +def _last_model(lines: list[str]) -> str: + for line in reversed(lines): + model = _model_of(line) + if model: + return model + return "" + + +def _tail_lines(path: Path) -> list[str]: + with path.open("rb") as fh: + if path.stat().st_size > TAIL_BYTES: + fh.seek(-TAIL_BYTES, 2) + fh.readline() # discard the partial line the seek landed in + return fh.read().decode("utf-8", "replace").splitlines() + + +def model_from_transcript(transcript_path: str) -> str: + """Return the model of the most recent main-agent turn in the transcript. + + Falls back to `unknown`, which is what the first prompt of a session gets: + no assistant has spoken yet. + """ + if not transcript_path: + return UNKNOWN_MODEL + path = Path(transcript_path) + if not path.is_file(): + return UNKNOWN_MODEL + try: + model = _last_model(_tail_lines(path)) + if not model and path.stat().st_size > TAIL_BYTES: + model = _last_model(path.read_text(encoding="utf-8", errors="replace").splitlines()) + except OSError: + return UNKNOWN_MODEL # an unreadable transcript costs the name, not the prompt + return _safe_model(model) if model else UNKNOWN_MODEL + + +def _safe_model(model: str) -> str: + # Leading dots too: a model name must not become a hidden file or "..". + return UNSAFE_IN_FILENAME.sub("-", model).strip("-.") or UNKNOWN_MODEL + + +def should_record(payload: dict) -> bool: + """True when the payload carries a prompt the human actually wrote.""" + source = payload.get("source") + if source is not None and source not in HUMAN_SOURCES: + return False + prompt = payload.get("prompt") + if not isinstance(prompt, str) or not prompt.strip(): + return False + return not prompt.lstrip().startswith(SYNTHETIC_PREFIXES) + + +def repo_root(cwd: str) -> Path | None: + """The git root containing *cwd*, or *cwd* itself outside a repository. + + None when the payload names a directory that does not exist: guessing + somewhere else to write would file the prompt under an unrelated project. + """ + fallback = Path(cwd) if cwd else Path.cwd() + if not fallback.is_dir(): + return None + try: + toplevel = subprocess.check_output( + ["git", "rev-parse", "--show-toplevel"], + cwd=fallback, + text=True, + stderr=subprocess.DEVNULL, + ).strip() + except (OSError, subprocess.CalledProcessError): + return fallback + return Path(toplevel) if toplevel else fallback + + +def _write_new(prompts_dir: Path, timestamp: str, model: str, text: str) -> Path: + """Write to `_.txt`, sequence-numbered if that is taken. + + Creating the file exclusively is what makes the sequence safe: two sessions + recording into the same repository in the same second would otherwise both + see a free name and one would overwrite the other. + """ + for seq in range(1000): + suffix = "" if seq == 0 else f"-{seq:03d}" + dest = prompts_dir / f"{timestamp}{suffix}_{model}{FILE_EXTENSION}" + try: + fd = os.open(dest, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) + except FileExistsError: + continue + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(text) + return dest + raise OSError(f"no free prompt filename for {timestamp} in {prompts_dir}") + + +def record(payload: dict) -> Path | None: + """Write the prompt to `.prompts/`; return the file, or None if skipped.""" + if not should_record(payload): + return None + root = repo_root(payload.get("cwd", "")) + if root is None: + return None + prompts_dir = root / PROMPTS_DIRECTORY + prompts_dir.mkdir(parents=True, exist_ok=True) + model = model_from_transcript(payload.get("transcript_path", "")) + timestamp = datetime.now().strftime("%Y-%m-%dT%H-%M-%S") + return _write_new(prompts_dir, timestamp, model, payload["prompt"].rstrip("\n") + "\n") + + +def main() -> int: + try: + # The payload is UTF-8 JSON whatever the locale claims, so decode it as + # UTF-8 rather than letting a cp1252 stdin lose the prompt. + raw = sys.stdin.buffer.read().decode("utf-8", "replace") + payload = json.loads(raw or "{}") + except ValueError: + return 0 # not our payload; say nothing + if not isinstance(payload, dict): + return 0 + try: + record(payload) + except Exception as error: # never block a prompt over a recording failure + print(f"record-prompt: {error}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ai_prompt_auto_commit/interceptor.py b/ai_prompt_auto_commit/interceptor.py index a8127e0..13f13d6 100644 --- a/ai_prompt_auto_commit/interceptor.py +++ b/ai_prompt_auto_commit/interceptor.py @@ -72,7 +72,7 @@ def next_prompt_filename(prompts_dir: Path, timestamp: str, model: str) -> Path: numbers: list[int] = [] for name in existing: try: - seq = int(name.split("-")[3]) + seq = int(name.split("_", 1)[0].rsplit("-", 1)[1]) except (IndexError, ValueError): continue numbers.append(seq) diff --git a/ai_prompt_auto_commit/prepare_repository.py b/ai_prompt_auto_commit/prepare_repository.py index dcea87f..bb3cc3c 100644 --- a/ai_prompt_auto_commit/prepare_repository.py +++ b/ai_prompt_auto_commit/prepare_repository.py @@ -7,6 +7,10 @@ import json import sys from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from importlib.abc import Traversable from . import common from .common import PROMPTS_DIRECTORY @@ -19,10 +23,21 @@ """ +# The UserPromptSubmit hook script, bundled as package data and installed into +# the target repository. It cannot import this package — the console scripts +# live in pre-commit's isolated cache venv, which is not on the assistant's +# PATH — so a self-contained copy is placed where the hook can reach it. +HOOK_SCRIPT_DATA = "record_prompt.py" +HOOK_SCRIPT_FILENAME = "record-prompt.py" +HOOK_VERSION_PATTERN = r'(?m)^HOOK_VERSION = ".*"' + +def get_data_path(file_name: str) -> "Traversable": + """Return the path of a bundled data file.""" + return importlib.resources.files("ai_prompt_auto_commit.data").joinpath(file_name) + def get_data(file_name: str) -> str: """Return the contents of a bundled data file.""" - ref = importlib.resources.files("ai_prompt_auto_commit.data").joinpath(file_name) - return ref.read_text(encoding="utf-8") + return get_data_path(file_name).read_text(encoding="utf-8") def get_default_claude_settings() -> dict: """Return the bundled claude_settings.json with the package version injected into the hook.""" @@ -31,11 +46,23 @@ def get_default_claude_settings() -> dict: settings["hooks"]["UserPromptSubmit"][0]["hooks"][0]["version"] = PACKAGE_VERSION return settings +def get_default_hook_script() -> str: + """Return the bundled hook script with the package version injected.""" + content = get_data(HOOK_SCRIPT_DATA) + return re.sub( + HOOK_VERSION_PATTERN, + f'HOOK_VERSION = "{PACKAGE_VERSION}"', + content, + count=1, + ) + def get_default_assistant_guidelines() -> str: """Return the bundled assistant-guidelines.md content with the package version header.""" content = get_data("assistant-guidelines.md") - content = re.sub(r"(?m)^---\n(:?[^-]|[^\n]-)*\n---\n", "", content) - return ASSISTANT_GUIDELINES_HEADER + content + content = re.sub(r"(?m)^---\n(?:[^-]|[^\n]-)*\n---\n", "", content) + # The header supplies its own blank line; without this the file grows one + # more of them on every run. + return ASSISTANT_GUIDELINES_HEADER + content.lstrip("\n") def prepare_repository( prompts_directory:str = PROMPTS_DIRECTORY,) -> int: @@ -76,6 +103,15 @@ def prepare_repository( claude_dest = repo_root / ".claude" dest_file = claude_dest / "settings.json" + # Install the hook script the settings above point at. Always rewritten, + # so an outdated copy cannot survive an upgrade. + hooks_dest = claude_dest / "hooks" + hooks_dest.mkdir(parents=True, exist_ok=True) + script_file = hooks_dest / HOOK_SCRIPT_FILENAME + script_file.write_text(get_default_hook_script(), encoding="utf-8") + script_file.chmod(0o755) + print(f"Created or updated {script_file}") + settings = json.loads(dest_file.read_text(encoding="utf-8")) if dest_file.exists() else {} matchers = settings.setdefault("hooks", {}).setdefault("UserPromptSubmit", []) diff --git a/tests/test_append_to_commit_msg.py b/tests/test_append_to_commit_msg.py index 86967f1..fa5ee58 100644 --- a/tests/test_append_to_commit_msg.py +++ b/tests/test_append_to_commit_msg.py @@ -2,6 +2,7 @@ from __future__ import annotations +import time from pathlib import Path from ai_prompt_auto_commit.append import append_to_commit_msg @@ -101,3 +102,15 @@ def test_model_extracted_from_filename(repo: Path) -> None: msg = _commit_msg(repo) append_to_commit_msg(msg) assert "claude-haiku-4-5-20251001: write a test" in msg.read_text(encoding="utf-8") + + +def test_same_second_prompts_are_appended_in_the_order_written(repo: Path) -> None: + """Sequence-numbered names sort before the plain one ('-' < '_'), so + ordering has to come from when the file was written, not from its name.""" + _write_prompt(repo, "2026-01-01T10-00-00_claude-opus-5.md", "first") + time.sleep(0.01) + _write_prompt(repo, "2026-01-01T10-00-00-001_claude-opus-5.md", "second") + msg = _commit_msg(repo) + append_to_commit_msg(msg) + content = msg.read_text(encoding="utf-8") + assert content.index("first") < content.index("second") diff --git a/tests/test_interceptor.py b/tests/test_interceptor.py index b996d19..103ae7c 100644 --- a/tests/test_interceptor.py +++ b/tests/test_interceptor.py @@ -99,3 +99,12 @@ def test_no_model_uses_last_used(run_main, prompts_dir: Path) -> None: def test_no_model_no_prior_files_raises(run_main) -> None: with pytest.raises(SystemExit, match="no prompt files found"): run_main(["--prompt", "oops"]) + + +def test_next_prompt_filename_reads_the_sequence_not_the_minute(prompts_dir: Path) -> None: + """The timestamp is full of dashes; the sequence is the last one.""" + (prompts_dir / "2026-04-17T09-22-17-001_my-model.txt").write_text("a\n") + from ai_prompt_auto_commit.interceptor import next_prompt_filename + + nxt = next_prompt_filename(prompts_dir, "2026-04-17T09-22-17", "my-model") + assert nxt.name == "2026-04-17T09-22-17-002_my-model.txt" diff --git a/tests/test_prepare_repository.py b/tests/test_prepare_repository.py index d9ff0fd..1f53592 100644 --- a/tests/test_prepare_repository.py +++ b/tests/test_prepare_repository.py @@ -4,10 +4,17 @@ import importlib.metadata import json +import os from pathlib import Path from ai_prompt_auto_commit.common import PROMPTS_DIRECTORY -from ai_prompt_auto_commit.prepare_repository import get_default_claude_settings, get_default_assistant_guidelines, prepare_repository +from ai_prompt_auto_commit.prepare_repository import ( + HOOK_SCRIPT_FILENAME, + get_default_assistant_guidelines, + get_default_claude_settings, + get_default_hook_script, + prepare_repository, +) # --------------------------------------------------------------------------- @@ -183,3 +190,66 @@ def test_claude_settings_hook_updated_on_rerun(repo: Path) -> None: def test_prepare_repository_returns_zero(repo: Path) -> None: assert prepare_repository() == 0 assert repo.is_dir() + + +# --------------------------------------------------------------------------- +# .claude/hooks/record-prompt.py +# --------------------------------------------------------------------------- + +def test_hook_script_installed(repo: Path) -> None: + script = repo / ".claude" / "hooks" / HOOK_SCRIPT_FILENAME + assert script.is_file() + assert os.access(script, os.X_OK) + + +def test_hook_script_version_matches_package(repo: Path) -> None: + script = repo / ".claude" / "hooks" / HOOK_SCRIPT_FILENAME + expected = importlib.metadata.version("ai-prompt-auto-commit") + assert f'HOOK_VERSION = "{expected}"' in script.read_text(encoding="utf-8") + + +def test_hook_script_refreshed_on_rerun(repo: Path) -> None: + script = repo / ".claude" / "hooks" / HOOK_SCRIPT_FILENAME + script.write_text("# stale\n", encoding="utf-8") + prepare_repository() + assert script.read_text(encoding="utf-8") == get_default_hook_script() + + +def test_hook_command_invokes_the_script(repo: Path) -> None: + hook = get_default_claude_settings()["hooks"]["UserPromptSubmit"][0]["hooks"][0] + assert HOOK_SCRIPT_FILENAME in hook["command"] + + +def test_hook_command_has_no_hardcoded_model(repo: Path) -> None: + """Regression: the model was defaulted to a constant, so every prompt lied.""" + hook = get_default_claude_settings()["hooks"]["UserPromptSubmit"][0]["hooks"][0] + assert "claude-" not in hook["command"] + + +def test_hook_command_does_not_require_jq(repo: Path) -> None: + """jq was an undocumented hard dependency; failure was silent.""" + hook = get_default_claude_settings()["hooks"]["UserPromptSubmit"][0]["hooks"][0] + assert "jq" not in hook["command"] + + +def test_get_default_assistant_guidelines_is_idempotent(repo: Path) -> None: + """Re-running prepare_repository() must leave the file byte-identical. + + This does not pin the blank-line fix on its own — the generator reads the + bundled data file, so it was always stable across two calls. The round + trip below is what pins it. + """ + guidelines = repo / ".github" / "assistant-guidelines.md" + before = guidelines.read_text(encoding="utf-8") + prepare_repository() + assert guidelines.read_text(encoding="utf-8") == before + + +def test_assistant_guidelines_survives_the_release_round_trip(monkeypatch) -> None: + """`./release` copies the generated .github/ file back over the bundled + one, so generating from an already-generated file must be a no-op.""" + import ai_prompt_auto_commit.prepare_repository as pr + + generated = pr.get_default_assistant_guidelines() + monkeypatch.setattr(pr, "get_data", lambda name: generated) + assert pr.get_default_assistant_guidelines() == generated diff --git a/tests/test_record_prompt.py b/tests/test_record_prompt.py new file mode 100644 index 0000000..a6eecb8 --- /dev/null +++ b/tests/test_record_prompt.py @@ -0,0 +1,295 @@ +"""Tests for the bundled UserPromptSubmit hook script (data/record_prompt.py). + +The script is installed into a target repository as +`.claude/hooks/record-prompt.py`, so it is loaded here straight from the +package data directory rather than imported as a module. +""" + +from __future__ import annotations + +import importlib.util +import json +import os +import subprocess +import sys +import types +from pathlib import Path + +import pytest + +from ai_prompt_auto_commit.prepare_repository import HOOK_SCRIPT_DATA, get_data_path + + +@pytest.fixture(scope="module") +def hook() -> types.ModuleType: + """The bundled hook script, loaded as a module.""" + path = get_data_path(HOOK_SCRIPT_DATA) + spec = importlib.util.spec_from_file_location("_record_prompt_under_test", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _payload(**overrides: object) -> dict: + payload = { + "hook_event_name": "UserPromptSubmit", + "prompt": "why does the redirect fail?", + "source": "user", + "cwd": ".", + "transcript_path": "", + } + payload.update(overrides) + return payload + + +def _transcript(path: Path, entries: list[dict]) -> Path: + path.write_text("".join(json.dumps(e) + "\n" for e in entries), encoding="utf-8") + return path + + +def _assistant(model: str, **extra: object) -> dict: + return {"type": "assistant", "message": {"model": model}, **extra} + + +# --------------------------------------------------------------------------- +# should_record — only genuine user-authored turns +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize("source", ["user", "sdk"]) +def test_human_sources_are_recorded(hook, source: str) -> None: + assert hook.should_record(_payload(source=source)) + + +@pytest.mark.parametrize("source", ["system", "loop_wakeup", "schedule_wakeup", "poll_event"]) +def test_machine_injected_sources_are_dropped(hook, source: str) -> None: + assert not hook.should_record(_payload(source=source)) + + +def test_missing_source_defaults_to_recording(hook) -> None: + payload = _payload() + del payload["source"] + assert hook.should_record(payload) + + +@pytest.mark.parametrize("prompt", [ + "\nb7cljujii\n", + "pytest -k compat", + "Command did not complete within its 120s timeout", + "Caveat: The messages below were generated", + "background context", +]) +def test_synthetic_turns_dropped_even_without_source(hook, prompt: str) -> None: + payload = _payload(prompt=prompt) + del payload["source"] + assert not hook.should_record(payload) + + +@pytest.mark.parametrize("prompt", ["", " \n "]) +def test_empty_prompt_is_dropped(hook, prompt: str) -> None: + assert not hook.should_record(_payload(prompt=prompt)) + + +def test_slash_command_is_a_real_prompt(hook) -> None: + assert hook.should_record(_payload(prompt="/review-and-push")) + + +# --------------------------------------------------------------------------- +# model_from_transcript — read the model, never guess it +# --------------------------------------------------------------------------- + +def test_model_is_last_assistant_model(hook, tmp_path: Path) -> None: + t = _transcript(tmp_path / "t.jsonl", [ + {"type": "user", "message": {"content": "hi"}}, + _assistant("claude-sonnet-4-6"), + _assistant("claude-opus-5"), + ]) + assert hook.model_from_transcript(str(t)) == "claude-opus-5" + + +def test_sidechain_model_is_ignored(hook, tmp_path: Path) -> None: + """A subagent's model must not be attributed to the user's prompt.""" + t = _transcript(tmp_path / "t.jsonl", [ + _assistant("claude-opus-5"), + _assistant("claude-haiku-4-5-20251001", isSidechain=True), + ]) + assert hook.model_from_transcript(str(t)) == "claude-opus-5" + + +def test_synthetic_model_is_ignored(hook, tmp_path: Path) -> None: + t = _transcript(tmp_path / "t.jsonl", [ + _assistant("claude-opus-5"), + _assistant(""), + ]) + assert hook.model_from_transcript(str(t)) == "claude-opus-5" + + +def test_malformed_lines_are_tolerated(hook, tmp_path: Path) -> None: + t = tmp_path / "t.jsonl" + t.write_text('not json\n{"type": "assistant", "message": {"model": "m-1"}}\n{\n', encoding="utf-8") + assert hook.model_from_transcript(str(t)) == "m-1" + + +@pytest.mark.parametrize("path", ["", "/nonexistent/transcript.jsonl"]) +def test_unreadable_transcript_yields_unknown(hook, path: str) -> None: + assert hook.model_from_transcript(path) == hook.UNKNOWN_MODEL + + +def test_transcript_without_assistant_turns_yields_unknown(hook, tmp_path: Path) -> None: + """The first prompt of a session: no assistant has spoken yet.""" + t = _transcript(tmp_path / "t.jsonl", [ + {"type": "mode", "mode": "normal"}, + {"type": "user", "message": {"content": "hi"}}, + ]) + assert hook.model_from_transcript(str(t)) == hook.UNKNOWN_MODEL + + +def test_model_found_beyond_the_tail_window(hook, tmp_path: Path) -> None: + """Only the tail is read normally; a far-away model must still be found.""" + padding = [{"type": "user", "message": {"content": "x" * 4096}}] * 512 + t = _transcript(tmp_path / "t.jsonl", [_assistant("claude-opus-5")] + padding) + assert t.stat().st_size > hook.TAIL_BYTES + assert hook.model_from_transcript(str(t)) == "claude-opus-5" + + +# --------------------------------------------------------------------------- +# record() — file naming and content +# --------------------------------------------------------------------------- + +def test_prompt_written_with_model_from_transcript(hook, tmp_path: Path) -> None: + t = _transcript(tmp_path / "t.jsonl", [_assistant("claude-opus-5")]) + dest = hook.record(_payload(cwd=str(tmp_path), transcript_path=str(t))) + assert dest is not None + assert dest.parent == tmp_path / ".prompts" + assert dest.name.endswith("_claude-opus-5.txt") + assert dest.read_text(encoding="utf-8") == "why does the redirect fail?\n" + + +def test_machine_injected_turn_writes_nothing(hook, tmp_path: Path) -> None: + assert hook.record(_payload(cwd=str(tmp_path), source="system")) is None + assert not (tmp_path / ".prompts").exists() + + +def test_second_prompt_in_the_same_second_is_not_overwritten(hook, tmp_path: Path) -> None: + payload = _payload(cwd=str(tmp_path)) + first = hook.record(payload) + second = hook.record(dict(payload, prompt="and now?")) + assert first != second + assert first.read_text(encoding="utf-8") == "why does the redirect fail?\n" + assert second.read_text(encoding="utf-8") == "and now?\n" + + +# --------------------------------------------------------------------------- +# main() — the actual hook contract: JSON on stdin, nothing on stdout +# --------------------------------------------------------------------------- + +def _run_hook(payload: dict, cwd: Path) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, str(get_data_path(HOOK_SCRIPT_DATA))], + input=json.dumps(payload), + capture_output=True, + text=True, + cwd=cwd, + ) + + +def test_hook_writes_nothing_to_stdout(tmp_path: Path) -> None: + """UserPromptSubmit stdout is injected into the prompt as context.""" + result = _run_hook(_payload(cwd=str(tmp_path)), tmp_path) + assert result.stdout == "" + assert result.returncode == 0 + assert len(list((tmp_path / ".prompts").glob("*.txt"))) == 1 + + +def test_hook_survives_garbage_on_stdin(tmp_path: Path) -> None: + result = subprocess.run( + [sys.executable, str(get_data_path(HOOK_SCRIPT_DATA))], + input="not json at all", + capture_output=True, + text=True, + cwd=tmp_path, + ) + assert result.returncode == 0 + assert result.stdout == "" + + +# --------------------------------------------------------------------------- +# never lose a prompt: the hook must fail soft, whatever goes wrong +# --------------------------------------------------------------------------- + +def test_hook_command_exits_zero_when_the_script_is_missing(tmp_path: Path) -> None: + """Claude Code erases the prompt on exit 2, which python3 returns for a + missing file. A repository whose script was never installed must degrade + to not recording, not to swallowing what the user typed.""" + from ai_prompt_auto_commit.prepare_repository import get_default_claude_settings + + command = get_default_claude_settings()["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"] + result = subprocess.run( + ["sh", "-c", command], + input=json.dumps(_payload()), + capture_output=True, + text=True, + cwd=tmp_path, # no .claude/hooks/record-prompt.py here + env={"PATH": os.environ["PATH"]}, + ) + assert result.returncode == 0, result.stderr + + +def test_unreadable_transcript_yields_unknown_not_a_crash(hook, tmp_path: Path) -> None: + t = _transcript(tmp_path / "t.jsonl", [_assistant("claude-opus-5")]) + t.chmod(0o000) + try: + assert hook.model_from_transcript(str(t)) == hook.UNKNOWN_MODEL + finally: + t.chmod(0o600) + + +def test_prompt_still_recorded_when_the_transcript_is_unreadable(hook, tmp_path: Path) -> None: + t = _transcript(tmp_path / "t.jsonl", [_assistant("claude-opus-5")]) + t.chmod(0o000) + try: + dest = hook.record(_payload(cwd=str(tmp_path), transcript_path=str(t))) + finally: + t.chmod(0o600) + assert dest is not None and dest.name.endswith(f"_{hook.UNKNOWN_MODEL}.txt") + + +def test_non_utf8_locale_still_records_the_prompt(tmp_path: Path) -> None: + """The payload is always UTF-8 JSON; the locale must not get a say.""" + env = dict(os.environ, LC_ALL="C", LANG="C", PYTHONIOENCODING="", PYTHONUTF8="0") + env.pop("PYTHONIOENCODING") + result = subprocess.run( + [sys.executable, str(get_data_path(HOOK_SCRIPT_DATA))], + input=json.dumps(_payload(prompt="hvorfor feiler kalenderoppslaget?"), ensure_ascii=False).encode("utf-8"), + capture_output=True, + cwd=tmp_path, + env=env, + ) + assert result.returncode == 0, result.stderr + written = list((tmp_path / ".prompts").glob("*.txt")) + assert len(written) == 1 + assert written[0].read_text(encoding="utf-8") == "hvorfor feiler kalenderoppslaget?\n" + + +@pytest.mark.parametrize("model, expected", [ + ("anthropic/claude-opus-5", "anthropic-claude-opus-5"), + ("some_model", "some-model"), # `_` separates timestamp from model + ("../../escape", "escape"), +]) +def test_model_name_is_made_safe_for_a_filename(hook, tmp_path: Path, model: str, expected: str) -> None: + t = _transcript(tmp_path / "t.jsonl", [_assistant(model)]) + dest = hook.record(_payload(cwd=str(tmp_path), transcript_path=str(t))) + assert dest is not None + assert dest.parent == tmp_path / ".prompts" + assert dest.name.endswith(f"_{expected}.txt") + + +def test_missing_cwd_records_nowhere_at_all(hook, tmp_path: Path) -> None: + """Not merely "does not create the missing tree": falling back to the + process cwd files the prompt under whatever repository the hook happened + to be run from.""" + gone = tmp_path / "deleted" / "deeply" + before = sorted(Path.cwd().rglob(".prompts/*.txt")) + assert hook.record(_payload(cwd=str(gone))) is None + assert not gone.exists() + assert sorted(Path.cwd().rglob(".prompts/*.txt")) == before diff --git a/tox.ini b/tox.ini index 990b630..193af0c 100644 --- a/tox.ini +++ b/tox.ini @@ -7,4 +7,3 @@ deps = pytest commands = pytest -