feat(commit-lint): add structural commit-msg validator

Verbose, inconsistent commit messages make the log hard to scan. A
structural checker keeps every message short and shaped the same way.

* feat(commit-lint): validate 1-3 block message grammar and line length
* feat(commit-lint): add --install-hook for real git commit-msg hooks
* docs(commit-atomic-jj): point rule 3 at new message-format.md
* docs(commit-atomic-git): document hook install, link shared grammar
* fix(commit-atomic-jj): update stale section refs and example lines
* fix(commit-atomic): say AGENTS.md not CLAUDE.md for docs-travel rule

Claude-Session: https://claude.ai/code/session_01VZH57yueT8apHdFXffmffE
This commit is contained in:
Łukasz Boryń 2026-09-23 14:24:19 +02:00
parent af21129106
commit 045c4d94a8
6 changed files with 308 additions and 55 deletions

View File

@ -38,27 +38,23 @@ Same principles; the staging area replaces `jj split`, and there is no
- Tests for existing behaviour: own commit, unless they land with the - Tests for existing behaviour: own commit, unless they land with the
new behaviour they cover (`/bdd`). new behaviour they cover (`/bdd`).
### 3. Semantic format ### 3. Structural message format
1-3 blank-line-separated blocks: subject (`type(scope): imperative
phrase[; starts|extends|ends <REF>]`), optional justification, optional
scope bullets. Full grammar, ticket refs, and blueprint citations:
[commit-atomic-jj/message-format.md](../commit-atomic-jj/message-format.md).
Install real enforcement once per repo:
``` ```
type(scope): imperative phrase completing "this change will…" skills/productivity/commit-atomic-jj/scripts/commit-msg-check --install-hook .
``` ```
- `type` ∈ `feat`, `fix`, `refactor`, `perf`, `test`, `docs`, `build`, This is a real `git commit-msg` hook (unlike jj, plain git fires it).
`chore`, `style`. Copies the checker to `.githooks/commit-msg` and sets `core.hooksPath` —
- Imperative: **"add"**, **"fix"**, **"remove"** — never "added", teammates each run `git config core.hooksPath .githooks` once after
"adds", "now does X". pulling that directory, since the setting itself isn't versioned.
- Subject ≤ 72 chars; body bullets ≤ 90, same `type(scope):` shape.
### 4. Ticket references (optional, project-configurable) ### 4. Docs travel with the code
Project uses a ticket prefix → body verbs `starts/extends/ends <PREFIX>-N`.
No convention → omit; don't invent a prefix.
### 5. Blueprint citations
A change executing `OKF/blueprints/NNN` cites it in the body:
`implements blueprint NNN`.
### 6. Docs travel with the code
Same commit includes: updated docstring for a changed public signature; Same commit includes: updated docstring for a changed public signature;
README / CLAUDE.md for a new flag, script, env var, command; a doc under README / AGENTS.md for a new flag, script, env var, command; a doc under
`docs/` for any non-self-evident analysis result. One-line docstrings `docs/` for any non-self-evident analysis result. One-line docstrings
fine; none is not. fine; none is not.
@ -94,6 +90,8 @@ hangs the session.
force-push is the agreed plan. force-push is the agreed plan.
## See also ## See also
- [commit-atomic-jj/message-format.md](../commit-atomic-jj/message-format.md)
— the message grammar `commit-msg-check` enforces, shared with jj.
- `/commit-atomic-jj` — jj - `/commit-atomic-jj` — jj
counterpart; shared philosophy, worked split example in its counterpart; shared philosophy, worked split example in its
examples.md translates 1:1 (staging instead of `jj split`). examples.md translates 1:1 (staging instead of `jj split`).

View File

@ -31,35 +31,17 @@ description: Atomic-commit discipline with jujutsu — read every diff line befo
- Test additions for an existing feature are their own change unless - Test additions for an existing feature are their own change unless
they accompany a new behaviour landing in the same diff. they accompany a new behaviour landing in the same diff.
### 3. Semantic format ### 3. Structural message format
``` 1-3 blank-line-separated blocks: subject (`type(scope): imperative
type(scope): imperative phrase completing "this change will…" phrase[; starts|extends|ends <REF>]`), optional justification, optional
``` scope bullets. `scripts/commit-msg-check` validates it mechanically —
- `type` ∈ `feat`, `fix`, `refactor`, `perf`, `test`, `docs`, `build`, see [message-format.md](message-format.md) for the full grammar,
`chore`, `style`. examples, ticket refs, and blueprint citations.
- Imperative voice: **"add"**, **"fix"**, **"remove"**, **"update"** —
never "added", "adding", "adds", "now does X".
- Subject ≤ 72 chars. Body bullets ≤ 90 chars.
- Body uses the same `type(scope): imperative` shape per sub-change.
### 4. Ticket references (optional, project-configurable) ### 4. Docs travel with the code
If the project uses a ticket prefix (e.g. `DRAKE-42`, `JIRA-101`,
`CIRI-7`), use these verbs in the body:
- `starts <PREFIX>-N` — first commit on a ticket.
- `extends <PREFIX>-N` — incremental progress.
- `ends <PREFIX>-N` — final commit closing the ticket.
If the project has no ticket convention, omit. Don't invent a prefix.
### 5. Blueprint citations
A change executing an `OKF/blueprints/NNN` blueprint (`/rig`)
cites it in the body: `implements blueprint NNN`. Readers trace the diff to
its justification without leaving the log.
### 6. Docs travel with the code
The same `jj describe` must include any of: The same `jj describe` must include any of:
- Updated docstring for a changed public function signature. - Updated docstring for a changed public function signature.
- Updated README / CLAUDE.md for a new CLI flag, script, env var, or - Updated README / AGENTS.md for a new CLI flag, script, env var, or
command. command.
- A new doc under `docs/` for any analysis whose result is **not - A new doc under `docs/` for any analysis whose result is **not
self-evident from reading the code** (e.g. a derived statistic, a self-evident from reading the code** (e.g. a derived statistic, a
@ -71,10 +53,15 @@ The same `jj describe` must include any of:
``` ```
jj diff # 1. read every line jj diff # 1. read every line
jj describe -m 'type(scope): ...' # 2. one concern? seal it (foreground) S=skills/productivity/commit-atomic-jj/scripts/commit-msg-check
jj diff --revision @- # 3. verify the message matches what shipped $S <(printf '%s' "$MSG") # 2. validate structure (jj has no hook)
jj new -m 'WIP' # 4. open a fresh empty @ for the next unit jj describe -m "$MSG" # 3. one concern? seal it (foreground)
jj diff --revision @- # 4. verify the message matches what shipped
jj new -m 'WIP' # 5. open a fresh empty @ for the next unit
``` ```
Step 2 is mandatory, not optional — jj has no native hook to enforce it
(nothing in `jj help` or `jj config schema` as of 0.38), so the skill
itself is the only enforcement point.
Mixed diff (more than one concern) → split **before** describing, minding Mixed diff (more than one concern) → split **before** describing, minding
which side the selected paths land on ([anti-patterns.md](anti-patterns.md)): which side the selected paths land on ([anti-patterns.md](anti-patterns.md)):
@ -96,6 +83,8 @@ commits, past-tense messages, missing scope, deferred docs, skipped
`jj new`, backgrounded mutations, headless editors, `split`'s parent side. `jj new`, backgrounded mutations, headless editors, `split`'s parent side.
## See also ## See also
- [message-format.md](message-format.md) — full block grammar, config,
and hook-install details for `scripts/commit-msg-check`.
- [examples.md](examples.md) — a real before/after where a working copy is - [examples.md](examples.md) — a real before/after where a working copy is
split into two atomic commits with proper messages. split into two atomic commits with proper messages.
- `/style-r` - `/style-r`

View File

@ -27,7 +27,7 @@ greppable and the change's footprint visible at a glance.
"I'll update the README after." You won't. Docstrings, README sections, "I'll update the README after." You won't. Docstrings, README sections,
CLAUDE.md updates for a new flag or env var — same change or it doesn't CLAUDE.md updates for a new flag or env var — same change or it doesn't
ship. See SKILL.md §6 *"Docs travel with the code"*. ship. See SKILL.md §4 *"Docs travel with the code"*.
## Skipping `jj new` after describe ## Skipping `jj new` after describe

View File

@ -38,11 +38,11 @@ commit; the remaining paths stay in `@`. Adjust per `jj` version.)
### Commit A — the bug fix (lands first; ticket starts here) ### Commit A — the bug fix (lands first; ticket starts here)
``` ```
fix(indication/assemble_expr): defensive copy of input data.table; starts DRAKE-NN1 fix(assemble_expr): defensive copy of input data.table; starts DRAKE-42
* fix(indication/assemble_expr): copy() at boundary to stop in-place mutation; extends DRAKE-NN1 * fix(assemble_expr): copy at boundary, stop in-place mutation; extends DRAKE-42
* test(indication/assemble_expr): add idempotence test; extends DRAKE-NN1 * test(assemble_expr): add idempotence test; extends DRAKE-42
* docs(indication/assemble_expr): note reference-semantics contract; extends DRAKE-NN1 * docs(assemble_expr): note reference-semantics contract; extends DRAKE-42
``` ```
Why this works: Why this works:
@ -52,14 +52,14 @@ Why this works:
- The test ships with the fix (see - The test ships with the fix (see
`/bdd`). `/bdd`).
- The docstring update ships with the fix (see - The docstring update ships with the fix (see
[SKILL.md §5](SKILL.md)). [SKILL.md §4](SKILL.md)).
### Commit B — the style refactor ### Commit B — the style refactor
``` ```
refactor(base): replace source() with box::use for dw_hippie; ends DRAKE-NN2 refactor(base): replace source() with box::use for dw_hippie; ends DRAKE-43
* refactor(base/dw_base_data): swap source() for ./dw_hippie box import; ends DRAKE-NN2 * refactor(base): swap source() for ./dw_hippie box import; ends DRAKE-43
``` ```
Why this works: Why this works:

View File

@ -0,0 +1,89 @@
# commit-atomic-jj message format
Structural grammar checked by `scripts/commit-msg-check` — mechanical,
run it rather than eyeballing.
## Blocks
A message is 1 to 3 blocks, each separated by exactly one blank line. No
leading or trailing blank line; no doubled blank line between blocks.
**Block 1 — subject (always required, exactly one line, ≤80 chars)**
```
type(scope): imperative phrase
type(scope): imperative phrase; starts|extends|ends <REF>
```
`type` is one of `build, chore, ci, docs, feat, fix, perf, refactor,
revert, style, test` — the full Conventional Commits set. A repo can add
its own via `.commit-lint.toml` at repo root:
```toml
extra_types = ["hotfix"]
```
`<REF>` matches `[A-Z][A-Z0-9]*-[0-9]+` (e.g. `B-024`, `DRAKE-42`). The
`;` is reserved for this trailer — never use it inside the phrase itself.
Never starts with `-` or `*`.
**Block 2 — justification (optional, 1-2 lines, ≤80 chars each)**
Plain English: why this change exists. Two lines max, no more. The
"plain English" part is a style rule, not something the script checks —
skip jargon (refute, provenance, leverage, utilize…) and write like
you're explaining it to a teammate, not defending a thesis.
**Block 3 — scope bullets (optional, must come after block 2 if both
are present)**
```
* type(scope): imperative phrase
* type(scope): imperative phrase; starts|extends|ends <REF>
```
Same grammar as block 1, one per line, each prefixed `* ` exactly. Use
when the change has more than one distinct scope worth listing
separately; skip it for a single-concern commit.
A lone second block is classified by shape: lines starting `* ` are
block 3, anything else is block 2. So valid shapes are `[1]`, `[1,2]`,
`[1,3]`, `[1,2,3]` — never bullets before prose.
## Blueprint work
No separate citation convention — express it in the same grammar:
```
docs(blueprint): implement blueprint NNN
```
or as a block 3 bullet when it's one of several changes in the commit.
## Examples
Trivial fix, block 1 only:
```
fix(parser): reject trailing commas
```
With justification:
```
fix(parser): reject trailing commas
Old parser crashed on trailing commas. Users hit this often.
```
Multi-scope refactor:
```
refactor(auth): split login module
Module grew too big to review well. Splitting keeps each piece small.
* fix(auth): correct token refresh
* test(auth): add refresh coverage; ends B-024
```
## Enforcement
`commit-msg-check <message-file>` validates structure; all violations
are hard errors, no warning tier. `commit-msg-check --install-hook
[repo-dir]` copies the script to `<repo>/.githooks/commit-msg` and sets
`core.hooksPath` for the current clone — `core.hooksPath` is local
config, not versioned, so each teammate runs `git config core.hooksPath
.githooks` once after pulling the directory.
jj has no native hook mechanism (checked: nothing in `jj help` or `jj
config schema` as of 0.38) — SKILL.md's workflow runs the script against
the message before `jj describe` instead of relying on a hook.

View File

@ -0,0 +1,177 @@
#!/usr/bin/env python3
"""Validate commit message structure. Usage: commit-msg-check <message-file>
commit-msg-check --install-hook [repo-dir]
Errors (exit 1): more than 3 blank-line-separated blocks; a leading,
trailing, or doubled blank line; a line over 80 chars; block 1 absent,
multi-line, or not `type(scope): phrase[; starts|extends|ends REF]` with
`type` from the closed set (build, chore, ci, docs, feat, fix, perf,
refactor, revert, style, test — extend via `.commit-lint.toml`'s
`extra_types`); block 2 present but not 1-2 plain lines; block 3 present
but a line not `* type(scope): phrase[; ...]`, or ordered before block 2.
`--install-hook` copies this script into `<repo-dir>/.githooks/commit-msg`
(default: cwd's repo) and points `core.hooksPath` at it. That config is
per-clone, not versioned — each teammate runs
`git config core.hooksPath .githooks` once after pulling the directory.
See message-format.md for the grammar in prose.
"""
import re
import subprocess
import sys
from pathlib import Path
MAX_LEN = 80
DEFAULT_TYPES = {
"build", "chore", "ci", "docs", "feat", "fix",
"perf", "refactor", "revert", "style", "test",
}
BLOCK1_RE = re.compile(r"^(?P<head>[a-z]+\([^()]+\): [^;]+)(?:; (?P<trailer>.+))?$")
HEAD_RE = re.compile(r"^(?P<type>[a-z]+)\((?P<scope>[^()]+)\): (?P<phrase>.+)$")
TRAILER_RE = re.compile(r"^(starts|extends|ends) [A-Z][A-Z0-9]*-[0-9]+$")
def load_extra_types(root):
config = root / ".commit-lint.toml"
if not config.exists():
return set()
match = re.search(r"extra_types\s*=\s*\[([^\]]*)\]", config.read_text())
if not match:
return set()
return {v.strip().strip("\"'") for v in match.group(1).split(",") if v.strip()}
def git_root(start):
try:
out = subprocess.run(
["git", "rev-parse", "--show-toplevel"], cwd=start,
capture_output=True, text=True, check=True,
)
return Path(out.stdout.strip())
except (subprocess.CalledProcessError, FileNotFoundError):
return None
def check_line_shape(line, errors, where, allowed_types):
"""Validate one `type(scope): phrase[; verb REF]` line, sans any bullet marker."""
m = BLOCK1_RE.match(line)
if not m:
errors.append(f"{where}: not 'type(scope): phrase' shape: {line!r}")
return
head = HEAD_RE.match(m.group("head"))
if not head:
errors.append(f"{where}: missing scope or phrase: {line!r}")
return
if head.group("type") not in allowed_types:
errors.append(
f"{where}: type {head.group('type')!r} not in "
f"{sorted(allowed_types)}"
)
trailer = m.group("trailer")
if trailer is not None and not TRAILER_RE.fullmatch(trailer):
errors.append(
f"{where}: trailer must be 'starts|extends|ends REF' "
f"(REF like B-024): {trailer!r}"
)
def split_blocks(lines, errors):
blocks, current, blank_run = [], [], 0
for line in lines:
if line == "":
blank_run += 1
if current:
blocks.append(current)
current = []
else:
if blank_run > 1:
errors.append(f"doubled blank line before: {line!r}")
blank_run = 0
current.append(line)
if current:
blocks.append(current)
return blocks
def check_message(text, extra_types):
allowed_types = DEFAULT_TYPES | extra_types
lines = [l for l in text.splitlines() if not l.lstrip().startswith("#")]
errors = []
if not lines:
return ["empty message"]
if lines[0] == "":
errors.append("leading blank line")
if lines[-1] == "":
errors.append("trailing blank line")
for i, line in enumerate(lines, 1):
if len(line) > MAX_LEN:
errors.append(f"line {i}: over {MAX_LEN} chars: {line!r}")
blocks = split_blocks(lines, errors)
if len(blocks) > 3:
errors.append(f"too many blocks (max 3): got {len(blocks)}")
subject = blocks[0] if blocks else []
if len(subject) != 1:
errors.append(f"block 1 must be a single line, got {len(subject)}")
elif subject[0][:1] in ("-", "*"):
errors.append(f"block 1 must not start with a bullet marker: {subject[0]!r}")
elif subject:
check_line_shape(subject[0], errors, "block 1", allowed_types)
rest = blocks[1:]
kinds = ["bullets" if b[0].startswith("* ") else "prose" for b in rest]
if kinds == ["bullets", "prose"]:
errors.append("block 3 (bullets) must come after block 2 (justification)")
elif len(kinds) == 2 and kinds[0] == kinds[1]:
errors.append(f"two {kinds[0]} blocks in a row — only one of each allowed")
for block, kind in zip(rest, kinds):
label = "block 3" if kind == "bullets" else "block 2"
if kind == "prose":
if len(block) > 2:
errors.append(f"{label} must be 1-2 lines, got {len(block)}")
else:
for line in block:
if not line.startswith("* "):
errors.append(f"{label}: bullet must start with '* ': {line!r}")
continue
check_line_shape(line[2:], errors, label, allowed_types)
return errors
def install_hook(argv):
start = Path(argv[0]).resolve() if argv else Path.cwd()
root = git_root(start) or start
hooks_dir = root / ".githooks"
hooks_dir.mkdir(exist_ok=True)
dest = hooks_dir / "commit-msg"
dest.write_bytes(Path(__file__).read_bytes())
dest.chmod(dest.stat().st_mode | 0o111)
subprocess.run(["git", "config", "core.hooksPath", ".githooks"], cwd=root, check=True)
print(f"installed {dest}")
print(f"core.hooksPath set to .githooks in {root}")
print("teammates: after pulling, run `git config core.hooksPath .githooks` once")
return 0
def main(argv):
if len(argv) >= 2 and argv[1] == "--install-hook":
return install_hook(argv[2:])
if len(argv) != 2:
print("usage: commit-msg-check <message-file> | --install-hook [repo-dir]",
file=sys.stderr)
return 2
path = Path(argv[1])
root = git_root(path.parent) or Path.cwd()
errors = check_message(path.read_text(), load_extra_types(root))
for line in errors:
print(f"ERROR {line}")
print(f"{len(errors)} error(s)")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main(sys.argv))