Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
Expand Down
2 changes: 0 additions & 2 deletions .github/assistant-guidelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,29 @@

<!-- Note: Adding a version here, also edit README.md pre-commit template. -->

## 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
Expand Down
30 changes: 22 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -135,12 +143,19 @@ printf "%s" "<your prompt>" | 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).
Expand All @@ -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.

9 changes: 5 additions & 4 deletions ai_prompt_auto_commit/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<ts>-001_<model>" sorts
# before the plain "<ts>_<model>" it followed, because '-' < '_'.
return sorted(result, key=lambda p: (p.stat().st_mtime_ns, p.name))
2 changes: 0 additions & 2 deletions ai_prompt_auto_commit/data/assistant-guidelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion ai_prompt_auto_commit/data/claude_settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
Expand Down
217 changes: 217 additions & 0 deletions ai_prompt_auto_commit/data/record_prompt.py
Original file line number Diff line number Diff line change
@@ -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

<repo root>/.prompts/<timestamp>_<model>.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 = (
"<task-notification>",
"<bash-input>",
"<bash-stdout>",
"<bash-stderr>",
"<local-command-caveat>",
"<system-reminder>",
)

# 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 "<synthetic>"
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 `<timestamp>_<model>.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())
2 changes: 1 addition & 1 deletion ai_prompt_auto_commit/interceptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading