Docs worth keeping: docs-review asks Haiku whether new text will be read again, docs-no-repeat-code flags lines that may restate code, limit-docs shows a…

Bakhtiyar Ospanov's agent skills, and Claude Code mods: plugins built on function hooks.
For any agent the skills CLI supports:
npx skills add bahaospanov/skills --skill <skill>
Or in Claude Code, all of them as one plugin, invoked as /bahaospanov-skills:<skill>:
/plugin marketplace add bahaospanov/skills
/plugin install bahaospanov-skills@bahaospanov
Pick one: installing both leaves every skill twice.
Reachable only when you type them (Claude Code: disable-model-invocation: true; Codex: policy.allow_implicit_invocation: false in agents/openai.yaml).
Model- or user-reachable.
### Playbook block of its AGENTS.md. Its MR description is mattpocock/skills pr (MIT), whose Summary visuals come from Dex Horthy's HumanLayer show-me (MIT).prototype (MIT), its UI branch reworked: whole flows, options grouped by stage in a one-click panel.Early access; the API changes between releases.
One mod per purpose. Why each one and each of its rules exists: STORY.md.
| Mod | Purpose |
|---|---|
| git-gates | Git work happens on the user's word |
| git-tidy | Git history stays tidy |
| git-cleanup | Merged work is cleaned up once it shipped |
| issue-first | Feature work starts from an issue, and each commit names its own |
| lean-docs | Docs worth keeping |
| lean-comments | Comments worth keeping |
| lean-scripts | Scripts worth keeping |
| close-countdown | A Herdr pane counts down before it closes |
| traffic-light | The band says whether the session's work is done |
Haiku reviews are gated in code first, so a call that cannot fail the review costs no model call. End-of-turn checks read the git diff of repos the turn touched, Bash edits included, and show at most two one-line notices a session; the report reaches Claude with your next message and is acted on when you ask.
Pushing is a deploy, so the agent needs the user's word in the current turn: the prompt that opened it or one typed while it ran. If a consent check itself fails, the call is blocked.
| Check | Runs on | Needs | Then |
|---|---|---|---|
| consent | git commit, push, with or without git's own options (git -C dir push); opening a PR/MR; PR/MR merge | commit, push, ship, deploy, pr, mr, tag or release typed in the current turn (a message typed while it runs or a background task's report does not withdraw it); a push needs one of them other than commit; opening needs pr, mr, pull request, merge request or ship; merge needs "merge", and "merge request" is not it; a protected branch must be named. A negated keyword ("don't push") does not count, and a no to the act itself refuses it, standing grant included, unless the turn also asks for it | Call denied |
| grants | Later commits in the session | A message asking for a commit per task, or the grant tool after an authorizing message | Commits spend the grant; pushes never |
Protected branches come from a repo's own push policy file. Integration branches are the protected ones; with no policy, the remote's default branch and any of dev, develop, main, master that exist. Deleting a branch on origin needs no keyword when origin's head of it already sits in an integration branch.
The rules' text lives in the playbook; the commit-order, follow-up and feature refusals name the part.
| Check | Runs on | Needs | Then |
|---|---|---|---|
| messages | A git commit | Conventional Commits subject, no Co-Authored-By trailer naming Claude or Anthropic (in the message or a --trailer flag) and no "Generated with Claude Code" line | Commit denied |
| message advice | A git commit | No reviewer pre-answers ("no X changed"); then Haiku: a body only when the cause is subtle | Commit runs; the user gets the advice |
| fresh base | Opening an MR/PR: gh pr create, glab mr create, a GitLab API POST to merge_requests | The source branch, as origin has it, contains the target's latest commit, fetched first; skipped when the message says not to rebase | Call denied |
| landed branch | A git push | The branch's pushed head already sits in a protected branch, and the message names no new MR | Push denied |
| every commit works | A git push of 2 to 15 commits no remote has | Sonnet: no commit removes something a later one stops using, or uses something a later one adds; skipped when the message says the order is fine | Push denied |
| one commit per change | A git push of new commits to a branch whose commits not yet in an integration branch number 2 to 15, pushed or not | No fixup!, squash! or amend! subject; then Sonnet: no later commit spends most of its diff fixing, reworking or extending lines an earlier one added, or matches an earlier one's API contract change in another app; skipped when the message says to keep the commits | Push held: the agent shows the user the reason and asks; any answer lets the same commits through |
| one feature per MR | A git push of new commits to a branch whose commits not yet in an integration branch number 1 to 15, pushed or not | Its commit messages name at most one issue; then Sonnet: no piece of it could ship alone apart from the rest; skipped when the message says one MR or to keep them together | Push held: the agent shows the user the features, recommends a branch and MR each, and asks; any answer lets the branch through for the session |
Integration branches are found as git-gates finds them.
Merged is not shipped: a branch is cleaned up and its issue filled in only once the pipeline holding the merge has passed. Closing the issue is left to you.
| Check | Runs on | Needs | Then |
|---|---|---|---|
| merged first | Removing a branch, local or on origin; removing a worktree keeps its branch and is not held | The branch sits in an integration branch, a merged PR/MR has it as source branch, or the current turn's message says it merged (or to abandon it) | Call denied |
| pipeline first | Removing a worktree or branch, local or on origin; rewriting an issue's body (checklist ticks, How to test) | The work (the branch, the commit a squash merge landed as, or the newest integration commit naming the issue) landed and a pipeline holding it passed; skipped when the message says not to wait | Call denied while it runs or after it failed; a GitLab pipeline parked at manual or skipped holds nothing back |
| stale work | The end of a turn | A branch the session committed to or pushed that sits in an integration branch, its worktree clean, no pipeline holding it still running or failed | Removes the worktree and the branch, local and on origin, fast-forwards a local integration branch behind origin, and prints one line saying what went; the worktree the session works in stays |
Integration branches are found as git-gates finds them. A branch sits in an integration branch when its head does, or when every commit of it has a copy there (a rebase merge). Pipelines are read with gh on GitHub and, on GitLab, with the gitlab_token option: a read_api token, asked when the plugin is enabled, kept in the keychain on macOS and in ~/.claude/.credentials.json elsewhere. With no token or no pipeline holding the work, the pipeline check holds nothing back and a log line says why; merged first still applies, and on GitLab sees a squash merge only with the token.
| Check | Runs on | Needs | Then |
|---|---|---|---|
| feature issue | A feat commit | An issue (#107, #BLK-23) at the end of the subject, or in the branch name (feat/catalog-menu-107), or "no issue" typed by the user in the current turn | Commit denied; Claude looks for the issue, else drafts one and asks the user before creating it |
| issue number | A git commit | The issue or ticket your messages or the branch name, at the end of the subject | Commit runs; the user gets the suggestion |
A repo with no remote has no issue tracker: feature issue is skipped, and only a ticket (#BLK-23) counts as an issue. Issues you typed bind only commits in the session's repo and its worktrees; a branch ending in its issue number (perf/mobile-lcp-89) lets the subject end with that one instead. Enabled in a repo's own .claude/settings.json, it applies to everyone working there.
| Check | Runs on | Flags | Then |
|---|---|---|---|
| docs-review | A doc grown in a git checkout | Haiku: text nobody reads after the task (runbooks, setup pages, narration) | Claude gets the reason |
| docs-no-repeat-code | A doc line being written | Identifiers that already appear together in one code file | Claude gets the hint; the write goes ahead |
| limit-docs | The end of a turn | New or grown docs, prose outweighing code, doc lines repeating code | A one-line notice; say "trim docs" to act on it |
No check reads a skill's folder, the one holding SKILL.md, or anything under it: a skill is read again on every use.
Media and marketing work is out of scope too: a file its own checkout ignores (a local reels/ or renders/ folder) or one under a folder holding a .lean-skip file.
No comments by default: keep the ones that record a measured number, a trap or an invariant, cut the ones that restate the code or narrate the change.
| Check | Runs on | Flags | Then |
|---|---|---|---|
| limit-edits | A Write or Edit | More than 3 added comment lines, or a comment-heavy region around an edit that adds comments | Claude gets the guidance |
| limit-turns | The end of a turn | More than 3 new comment lines per file in the turn's diff | A one-line notice; say "trim comments" to act on it |
No check reads a file installed under ~/.agents/skills, ~/.claude/skills or ~/.claude/plugins: it is someone else's code. A link from there into a checkout is followed, and the file is checked.
Media and marketing work is out of scope too: a file its own checkout ignores (a local reels/ or renders/ folder) or one under a folder holding a .lean-skip file.
| Check | Runs on | Flags | Then |
|---|---|---|---|
| scripts-review | A script written or grown in a git checkout | Haiku: scripts you could just type again when needed | Claude gets the reason |
A script is a shell file, a file in a scripts, bin, tools or ops folder, or one starting with a shebang. A skill's folder is skipped: the skill runs its scripts on every use.
Media and marketing work is out of scope too: a file its own checkout ignores (a local reels/ or renders/ folder) or one under a folder holding a .lean-skip file.
A Herdr subtask closing its own pane shows it first, so whoever watches can stop it.
| Part | What it does |
|---|---|
close_pane_later tool | Closes this session's Herdr pane, or pane, after seconds (default 60) and returns at once; note is shown beside the countdown |
| The band | ⏻ Closing this pane in 42s · <note> [ ✋ Keep open ] [ ❌ Close now ] above the prompt, a draining bar under it |
| Cancel | A message typed into the session, ✋ Keep open or /keep-open; ❌ Close now closes the pane at once |
It runs herdr pane close, so the session needs herdr on its PATH and a Herdr pane (HERDR_PANE_ID).
A band above the prompt says whether you can leave the session.
| Light | When |
|---|---|
| 🟢 safe to leave | The PR is merged into dev, develop, main or master and every GitHub Actions run of that push passed; a run a newer push cancelled is judged by the newer one |
| 🟡 waiting on PR | The PR is open, failing checks included, or merged with its pipeline still running |
| 🔴 working | Claude is asking you, a turn is running where the light would be green, the repo holds uncommitted or unpushed work, there is no PR, it closed unmerged or merged elsewhere, the pipeline failed, or work began after the PR merged |
The repo is the one Claude last edited a file in. A feature branch is judged by its own PR; on an integration branch, or once the worktree is gone, by the PR a gh pr command last printed. A turn that changes nothing, such as a question, ends green again. A turn that edits a file git does not ignore, or creates a commit, branch, worktree, issue or PR, leaves that merged PR unable to turn the light green: green waits for the new work's PR. The light refreshes after git and gh commands, and every 30 seconds while yellow. /traffic-light prints it; /traffic-light demo shows each color.
It runs git and gh, so the session needs both on its PATH and gh signed in.
Mods load only with function hooks enabled, so export this in your shell profile first:
export CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1
Without it Claude Code skips the mods silently. Then, in Claude Code:
/plugin marketplace add bahaospanov/skills
/plugin install <mod>@bahaospanov
One folder per mod. tsconfig.json and types/ are shared. An installed mod carries only its own folder, so code two mods share is copied into each one's hooks/shared/.
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude --plugin-dir ./<mod> --debug
Saving a file under <mod>/hooks/ reloads the mod. Repeat --plugin-dir to load several.
npm run typecheck # tsc over every mod and its tests
npm run check:shared # hooks/shared/ copies are identical across mods
npm run check:continuations # every mod sending follow-up prompts is named where git-gates reads them
npm run check:version # every plugin.json carries package.json's version
claude plugin validate ./<mod> # what the engine sees the module hook and call
claude plugin test ./<mod> # the mod's tests/
types/ is written by /plugin-types types, run inside a session started as above. Regenerate, never edit, when:
head -1 types/claude-code.d.ts vs claude --version)$ is enabled or disabledCommit the result; git diff types/ shows what the update changed.
hooks/register.ts 235 lines1import type { EngineInterface, Register } from 'claude-code'
2import { addedDocLines, docBudgetOfDiff, docNotesOf, docPathsOf, isChangeset, MAX_BLOCKS, repeatMessage, SKILL, tokensOf, turnReport, type RepeatHint } from './docs'
3import { DOCUMENTATION } from './prompts'
4import { amends, authorsHistory } from './shared/anchor'
5import { baseName, claimedWorktrees, isDoc, nonBlankCount, splitLines, worktreesOf } from './shared/diff'
6import { dirOf, isDotfileOrTemp, isTrim, MEDIA_CHECK } from './shared/paths'
7import { MODEL, promptFor, SYSTEM, verdictOf, type Review, type Verdict } from './shared/verdict'
8
9const DOCS_REVIEW: Review = { name: 'docs-review', prompt: DOCUMENTATION, status: 'judging docs' }
10
11type Owned = { head: string; seen: string; status: string; touched: boolean }
12
13let worktrees: string[] | undefined
14const owned = new Map<string, Owned>()
15const reported = new Set<string>()
16let blocks = 0
17// The report behind the last one-line notice, carried unseen to the model with the user's next prompt.
18let pendingReport: string | undefined
19const HUMAN_ORIGINS: readonly string[] = ['composer', 'bridge', 'sdk']
20
21const git = async ($: EngineInterface, cwd: string | undefined, args: string[]) => {
22 const run = await $.process.run(cwd === undefined ? ['git', ...args] : ['git', '-C', cwd, ...args])
23 return run.exitCode === 0 ? run.stdout.trim() : undefined
24}
25
26const filesStating = async ($: EngineInterface, root: string, tokens: string[]) => {
27 const sets: Set<string>[] = []
28 for (const token of tokens.slice(0, 4)) {
29 const listing = (await git($, root, ['grep', '-l', '-F', '--', token])) ?? ''
30 sets.push(new Set(splitLines(listing).filter((file) => !isDoc(file))))
31 }
32 const [first, ...rest] = sets
33 return first === undefined ? [] : [...first].filter((file) => rest.every((set) => set.has(file))).sort()
34}
35
36const statusOf = async ($: EngineInterface, wt: string) => (await git($, wt, ['status', '--porcelain'])) ?? ''
37
38const claim = async ($: EngineInterface, blob: string) => {
39 if (!blob) return
40 if (worktrees === undefined) {
41 const root = await git($, undefined, ['rev-parse', '--show-toplevel'])
42 worktrees = root ? worktreesOf((await git($, root, ['worktree', 'list', '--porcelain'])) ?? '') : []
43 }
44 for (const wt of claimedWorktrees(blob, worktrees)) {
45 if (owned.has(wt)) continue
46 const head = await git($, wt, ['rev-parse', 'HEAD'])
47 if (head) owned.set(wt, { head, seen: head, status: await statusOf($, wt), touched: false })
48 }
49}
50
51// The command text alone kept 6aed9cb across `git reset --hard origin/dev && git cherry-pick -n 6aed9cb`, and ten dev
52// commits read as this session's. An amend replaces HEAD on the same parent instead of descending from it.
53const authoredMove = async ($: EngineInterface, wt: string, command: string | undefined, from: string, to: string) => {
54 if (command === undefined || !authorsHistory(command)) return false
55 if ((await git($, wt, ['merge-base', '--is-ancestor', from, to])) !== undefined) return true
56 if (!amends(command)) return false
57 const [was, now] = splitLines((await git($, wt, ['rev-parse', `${from}^`, `${to}^`])) ?? '')
58 return was !== undefined && was === now
59}
60
61// Between two of our own calls another agent sharing the checkout can commit, fast-forward or reset it, and every line
62// arriving that way would otherwise read as this turn's work.
63const settle = async ($: EngineInterface, command?: string) => {
64 for (const [wt, info] of owned) {
65 let next = info
66 const head = await git($, wt, ['rev-parse', 'HEAD'])
67 if (head !== undefined && head !== next.seen) {
68 next = (await authoredMove($, wt, command, next.seen, head))
69 ? { ...next, seen: head }
70 : { ...next, head, seen: head, status: await statusOf($, wt) }
71 }
72 if (!next.touched) {
73 const status = await statusOf($, wt)
74 if (status !== next.status) next = { ...next, status, touched: true }
75 }
76 owned.set(wt, next)
77 }
78}
79
80const markTouched = (path: string) => {
81 for (const [wt, info] of owned) {
82 if (!info.touched && path.startsWith(`${wt}/`)) owned.set(wt, { ...info, touched: true })
83 }
84}
85
86// A skill is instructions read on every use, never a one-time page. The SKILL.md being created does not exist yet when
87// the pre-write check runs, so it is matched by name; the walk stops at the checkout's root.
88const inSkillFolder = async ($: EngineInterface, path: string, root: string) => {
89 if (baseName(path) === SKILL) return true
90 for (let dir = dirOf(path); dir === root || dir.startsWith(`${root}/`); dir = dirOf(dir)) {
91 if (await $.fs.exists(`${dir}/${SKILL}`)) return true
92 if (dir === root) break
93 }
94 return false
95}
96
97const isMediaWork = async ($: EngineInterface, path: string) =>
98 (await $.process.run(['sh', '-c', MEDIA_CHECK, 'lean', path])).exitCode === 0
99
100const repeatedFact = async ($: EngineInterface, path: string, added: string, old: string) => {
101 if (!isDoc(path) || nonBlankCount(added) <= nonBlankCount(old)) return undefined
102 const root = await git($, dirOf(path), ['rev-parse', '--show-toplevel'])
103 if (!root || isChangeset(path) || (await inSkillFolder($, path, root)) || (await isMediaWork($, path))) return undefined
104 for (const line of splitLines(added)) {
105 if (old.includes(line)) continue
106 const tokens = tokensOf(line)
107 if (tokens.length < 2) continue
108 const common = await filesStating($, root, tokens)
109 if (common.length > 0) return repeatMessage(tokens, common.slice(0, 2).join(', '), line)
110 }
111 return undefined
112}
113
114// The loader follows $ only into functions of this file, so the model call lives here, not in shared/verdict.ts.
115const judge = async ($: EngineInterface, review: Review, input: object): Promise<Verdict | undefined> => {
116 $.ui.status(review.status)
117 try {
118 const result = await $.model.complete({ model: MODEL, system: SYSTEM, prompt: promptFor(review, input) })
119 const reply = result.isAnswered ? result.text : `(${result.reason})`
120 const verdict = verdictOf(reply)
121 if (verdict === undefined) $.ui.log(`lean-docs/${review.name}: no verdict: ${reply.slice(0, 120)}`)
122 return verdict
123 } finally {
124 $.ui.status(undefined)
125 }
126}
127
128const docNotes = async ($: EngineInterface, wt: string, base: string) => {
129 const diff = (await git($, wt, ['diff', '--unified=0', base])) ?? ''
130 const untracked = splitLines((await git($, wt, ['ls-files', '--others', '--exclude-standard'])) ?? '').filter(isDoc)
131 const exempt = new Set<string>()
132 for (const rel of new Set([...docPathsOf(diff), ...untracked])) {
133 if (isChangeset(rel) || (await inSkillFolder($, `${wt}/${rel}`, wt)) || (await isMediaWork($, `${wt}/${rel}`))) exempt.add(rel)
134 }
135 const { perDoc, code, newDocs } = docBudgetOfDiff(diff, exempt)
136 for (const rel of untracked) {
137 if (exempt.has(rel)) continue
138 newDocs.add(rel)
139 const text = await $.fs.read(`${wt}/${rel}`).catch(() => undefined)
140 if (text !== undefined) perDoc[rel] = (perDoc[rel] ?? 0) + nonBlankCount(text)
141 }
142 const hints: RepeatHint[] = []
143 for (const { path, body } of addedDocLines(diff, exempt)) {
144 if (hints.length >= 4) break
145 const tokens = tokensOf(body)
146 if (tokens.length < 2) continue
147 const common = await filesStating($, wt, tokens)
148 if (common.length > 0) hints.push({ path, where: common.slice(0, 2).join(', '), tokens: tokens.slice(0, 3) })
149 }
150 return docNotesOf(perDoc, code, newDocs, hints)
151}
152
153const overBudget = async ($: EngineInterface) => {
154 const notes: string[] = []
155 const bases: string[] = []
156 for (const [wt, info] of owned) {
157 if (!info.touched) continue
158 const found = await docNotes($, wt, info.head)
159 if (found.length > 0) bases.push(info.head)
160 notes.push(...found)
161 }
162 if (notes.length === 0) return undefined
163 const key = JSON.stringify([...notes].sort())
164 if (reported.has(key) || blocks >= MAX_BLOCKS) return undefined
165 reported.add(key)
166 blocks++
167 return turnReport(notes, bases)
168}
169
170export const register: Register = (on) => {
171 on('prompt.submit', ($, e, next) => {
172 if (pendingReport === undefined || !HUMAN_ORIGINS.includes(e.origin.kind)) return next(e)
173 const context = [...(e.context ?? []), pendingReport]
174 pendingReport = undefined
175 return next({ ...e, context })
176 })
177
178 on('tool.call', { tool: ['Bash', 'Write', 'Edit'] }, async ($, e, next) => {
179 await claim($, e.tool === 'Bash' ? e.command : e.file_path)
180 const result = await next(e)
181 if (e.tool === 'Bash') await settle($, e.command)
182 else if (result.deny === undefined && !result.isError) markTouched(e.file_path)
183 return result
184 })
185
186 on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
187 const added = e.tool === 'Write' ? e.content : e.new_string
188 const old = e.tool === 'Write' ? await $.fs.read(e.file_path).catch(() => '') : e.old_string
189 const reason = await repeatedFact($, e.file_path, added, old)
190 // Names meeting in one code file hint at a repeat without proving one, so it advises and the write goes ahead.
191 const result = await next(e)
192 if (reason === undefined || result.deny !== undefined || result.isError) return result
193 return { ...result, context: [...(result.context ?? []), reason] }
194 })
195
196 on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
197 const path = e.file_path
198 if (!isDoc(path) || isDotfileOrTemp(path, await $.env.get('HOME'), await $.env.get('TMPDIR'))) return next(e)
199 const replaced = e.tool === 'Write' ? await $.fs.read(path).catch(() => '') : ''
200 const result = await next(e)
201 if (result.deny !== undefined || result.isError) return result
202 const added = e.tool === 'Write' ? e.content : e.new_string
203 const removed = e.tool === 'Write' ? replaced : e.old_string
204 if (isTrim(added, removed)) return result
205 const root = await git($, dirOf(path), ['rev-parse', '--show-toplevel'])
206 if (root === undefined || isChangeset(path) || (await inSkillFolder($, path, root)) || (await isMediaWork($, path))) return result
207
208 const tool_input =
209 e.tool === 'Write'
210 ? { file_path: path, content: e.content }
211 : { file_path: path, old_string: e.old_string, new_string: e.new_string, replace_all: e.replace_all }
212 const verdict = await judge($, DOCS_REVIEW, {
213 hook_event_name: 'PostToolUse',
214 tool_name: e.tool,
215 tool_input,
216 cwd: await $.session.cwd(),
217 })
218 if (verdict?.ok !== false) return result
219 $.ui.log(`lean-docs/docs-review: ${verdict.reason}`)
220 return { ...result, context: [...(result.context ?? []), `lean-docs/docs-review: ${verdict.reason}`] }
221 })
222
223 on('turn.complete', async ($, e, next) => {
224 const result = await next(e)
225 if (e.agentId !== undefined || e.reason !== 'answer' || owned.size === 0) return result
226 await settle($)
227 const report = await overBudget($)
228 if (report !== undefined) {
229 $.ui.log('lean-docs: this turn added a lot of prose; say "trim docs" to review it')
230 pendingReport = report
231 }
232 return result
233 })
234}
235hooks/docs.ts 95 lines1import { baseNote } from './shared/anchor'
2import { addedLines, isDoc, OUTRANKS, prefixes, startsWithAny } from './shared/diff'
3
4export const DOC_RATIO = 2.0
5export const DOC_FLOOR = 40
6export const DOC_BLOCK = 2
7export const MAX_BLOCKS = 2
8
9const TOKEN = /`([^`\n]{3,60})`/g
10
11export const DOC_ASK =
12 'A document earns a file only if it stays useful AFTER the task is done.\n' +
13 'The test: could a human execute this in one sitting, with you guiding them ' +
14 'live? Then it is a conversation, not a document - guide them and write ' +
15 'nothing. Once the task is done such a page is dead weight: it clogs the ' +
16 'repo and every future context window, and it rots because nobody runs it ' +
17 'again to notice it is wrong.\n' +
18 'EARNS a file: something run repeatedly; something needed when you are NOT ' +
19 'there (recovery, on-call, onboarding); a durable why that outlives the ' +
20 'change.\n' +
21 'DOES NOT: a one-time cutover or migration you are about to run together; a ' +
22 'narration of work just completed; a procedure whose only reader is the ' +
23 'person you are already talking to.\n' +
24 'Second test, applied to every added line: does the code, a config file, or ' +
25 'another page ALREADY say this? Prose that repeats a fact is worse than no ' +
26 'prose - it is another copy to keep in sync, and it is the copy that will ' +
27 'drift and start lying. Point at the existing source instead of restating ' +
28 'it, or add nothing.'
29
30export type RepeatHint = { path: string; where: string; tokens: string[] }
31
32export const SKILL = 'SKILL.md'
33
34export const docPathsOf = (diff: string) => [...new Set(addedLines(diff).map(({ path }) => path).filter(isDoc))]
35
36// `changeset version` folds a changeset into CHANGELOG.md and deletes it: one-time by design, never a page that rots.
37export const isChangeset = (path: string) => /(^|\/)\.changeset\/[^/]+\.md$/.test(path)
38
39export const docBudgetOfDiff = (diff: string, skip: ReadonlySet<string> = new Set()) => {
40 const perDoc: Record<string, number> = {}
41 const newDocs = new Set<string>()
42 let code = 0
43 for (const { path, body, isNewFile } of addedLines(diff)) {
44 if (skip.has(path)) continue
45 if (isNewFile && isDoc(path)) newDocs.add(path)
46 const stripped = body.trim()
47 if (stripped === '') continue
48 if (isDoc(path)) {
49 perDoc[path] = (perDoc[path] ?? 0) + 1
50 continue
51 }
52 const marks = prefixes(path)
53 if (!marks || !startsWithAny(stripped, marks)) code++
54 }
55 return { perDoc, code, newDocs }
56}
57
58export const tokensOf = (line: string) => [...line.matchAll(TOKEN)].map((m) => m[1] ?? '').filter((t) => !t.includes(' '))
59
60export const addedDocLines = (diff: string, skip: ReadonlySet<string> = new Set()) =>
61 addedLines(diff).filter(({ path }) => isDoc(path) && !skip.has(path)).map(({ path, body }) => ({ path, body }))
62
63export const repeatMessage = (tokens: string[], where: string, line: string) =>
64 `lean-docs/docs-no-repeat-code: this line repeats ${tokens.slice(0, 3).join('/')}, already stated in ${where}:\n ${line.trim().slice(0, 160)}\n` +
65 'A duplicated fact is a second copy to keep in sync, and it is the copy that drifts. ' +
66 'If the line restates that file, point at the source instead; if the names only meet there, keep it.'
67
68export const docNotesOf = (perDoc: Record<string, number>, code: number, newDocs: Set<string>, hints: RepeatHint[]) => {
69 const notes: string[] = []
70 for (const path of Object.keys(perDoc).sort()) {
71 const n = perDoc[path] ?? 0
72 if (newDocs.has(path)) notes.push(`NEW document ${path} (${n} lines)`)
73 else if (n > DOC_BLOCK) notes.push(`${path} grew by ${n} lines`)
74 }
75 for (const hint of hints.slice(0, 4)) {
76 notes.push(`${hint.path} repeats ${hint.tokens.join('/')} - already stated in ${hint.where}; point at it instead of copying it`)
77 }
78 const docs = Object.values(perDoc).reduce((sum, n) => sum + n, 0)
79 if (docs >= DOC_FLOOR && docs > DOC_RATIO * Math.max(code, 1)) {
80 notes.push(`${docs} lines of prose against ${code} of code (${(docs / Math.max(code, 1)).toFixed(1)}:1)`)
81 }
82 return notes
83}
84
85export const turnReport = (notes: string[], bases: readonly string[] = []) => {
86 const note = baseNote(bases)
87 return (
88 `lean-docs/limit-docs: prose outweighs the change.\n ${notes.join('\n ')}\n` +
89 `${note === undefined ? '' : `${note}\n`}${DOC_ASK}\n\n` +
90 'This check reads git diff, so it sees edits made through Bash, sed and ' +
91 `heredocs that the per-write checks never see.\n${OUTRANKS}\n` +
92 'The user saw a one-line note about this. When they ask to trim, cut what does not earn its place, then say what you kept and why.'
93 )
94}
95hooks/prompts.ts 13 lines1// Moved verbatim from the `prompt` hook in ~/.claude/settings.json; `$ARGUMENTS` is the hook input as JSON.
2
3export const DOCUMENTATION = `Reviewer for NEW OR GROWN DOCUMENTATION. $ARGUMENTS
4GATE FIRST, and this decides most calls. Judge ONLY when tool_input.file_path ends in .md, .markdown or .rst AND the path is inside a project checkout. Anything else - source code of any language, config, a path under a home-directory dotfile tree, a temp or scratch directory - return ok=true with NO reason and nothing else. Never judge code, never judge comments, never judge whether an edit should have been made.
5FIRST, decide whether this is a TRIM. If the edit removes more than it adds - an Edit whose new_string is empty or shorter than its old_string, or a Write whose content is shorter than the file already on disk - return ok=true with NO reason and nothing else. Removing documentation is always allowed. You judge what gets WRITTEN, never what gets removed, and never whether a removal was wise. A rewrap, a reshuffle or a reworded paragraph that leaves the file shorter is a trim, not a new page.
6Judge the ADDED text (new_string, or content for a Write) on one question: after the work it describes is finished, will anyone read it again? Judge an addition to an existing page as strictly as a new page.
7NO -> ok=false, reason: 'one-time procedure - guide them live; this page rots the moment the task ends'.
8YES -> ok=true. YES means run repeatedly, needed when you are absent (recovery, on-call, onboarding), or a durable why that outlives the change.
9Judge a page by the reason it EXISTS, not by its best paragraph. Setup and enablement pages - create the account, paste the credential, add the CI variable, verify it worked - are ok=false even when they also carry two or three durable facts, and even when every line is individually accurate. That mixture is the usual way a one-time procedure argues its way in. The durable facts belong where they are read: a comment at the line that would break, or the decision log. Turning something on happens once, so 'how to set up X' is never a page; 'why X is deliberately off for Y' can be a line somewhere permanent.
10Examples. ok=false: a cutover or migration runbook for a change being made now; a section narrating what was just done or measured. ok=true: a disaster-recovery procedure; a why that stops a future reader from 'cleaning up' something load-bearing.
11Also ok=false if the text restates what the code, a config file, an error string, or another page already says; if a reader could learn it from the diff; or if it records the OBVIOUS thing to do (a password on a datastore, a lock around read-modify-write, a version pin).
12Reason: quote the offending lines. Under 60 words, no preamble.`
13hooks/shared/anchor.ts 15 lines1// A checkout is shared: HEAD moving is this session's work only when one of its own commands wrote the commit.
2// A fast-forward by another agent, a reset or a rebase carries history this session never authored.
3const AUTHORS_HISTORY = /\bgit\b[^;&|]*\b(?:commit|merge|am|cherry-pick|revert)\b/
4
5export const authorsHistory = (command: string) => AUTHORS_HISTORY.test(command)
6
7export const amends = (command: string) => /\bgit\b[^;&|]*\bcommit\b[^;&|]*\s--amend\b/.test(command)
8
9export const shortSha = (sha: string) => sha.slice(0, 7)
10
11export const baseNote = (bases: readonly string[]) => {
12 const shown = [...new Set(bases.map(shortSha))]
13 return shown.length === 0 ? undefined : `Diff base: ${shown.join(', ')} - the HEAD the checkout carried when this session first touched it.`
14}
15hooks/shared/diff.ts 87 lines1const SKIP_EXT = ['.md', '.markdown', '.rst', '.txt', '.json', '.lock']
2const DOC_EXT = ['.md', '.markdown', '.rst']
3const HASH_EXT = [
4 '.sh', '.bash', '.zsh', '.fish', '.py', '.rb', '.pl', '.r',
5 '.yml', '.yaml', '.toml', '.ini', '.cfg', '.conf', '.tf', '.tfvars',
6 '.gitignore', '.dockerignore', '.env', '.example', '.properties',
7]
8const HASH_BASE = ['dockerfile', 'makefile', 'justfile', 'rakefile', 'gemfile', 'procfile']
9const SLASH_EXT = [
10 '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.go', '.java', '.c', '.h',
11 '.cc', '.cpp', '.hpp', '.cs', '.rs', '.swift', '.kt', '.kts', '.scala',
12 '.php', '.scss', '.less', '.css', '.dart', '.proto', '.gradle',
13]
14const MARKUP_EXT = ['.html', '.htm', '.vue', '.svelte', '.xml', '.svg']
15const DASH_EXT = ['.sql', '.lua', '.hs', '.elm']
16
17export const OUTRANKS =
18 "This outranks matching the file's existing comment density, and it " +
19 'outranks any skill or template instructing you to add a header or ' +
20 'rationale block.'
21
22export const baseName = (path: string) => path.slice(path.lastIndexOf('/') + 1)
23
24// As Python's os.path.splitext: leading dots are not an extension, so `.gitignore` has none.
25export const extOf = (path: string) => {
26 const rest = baseName(path).replace(/^\.+/, '')
27 const dot = rest.lastIndexOf('.')
28 return dot > 0 ? rest.slice(dot).toLowerCase() : ''
29}
30
31export const isDoc = (path: string) => DOC_EXT.includes(extOf(path))
32
33export const splitLines = (text: string) => {
34 const lines = text.split(/\r\n|\r|\n/)
35 if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()
36 return lines
37}
38
39export const nonBlankCount = (text: string) => splitLines(text).filter((line) => line.trim() !== '').length
40
41export const prefixes = (path: string): string[] | undefined => {
42 const base = baseName(path).toLowerCase()
43 const ext = extOf(path)
44 if (SKIP_EXT.includes(ext)) return undefined
45 if (base.startsWith('dockerfile') || HASH_BASE.includes(base)) return ['#']
46 const marks: string[] = []
47 if (HASH_EXT.includes(ext)) marks.push('#')
48 if (SLASH_EXT.includes(ext)) marks.push('//', '/*', '*/', '*')
49 if (MARKUP_EXT.includes(ext)) marks.push('<!--', '-->', '//', '/*', '*/', '*')
50 if (DASH_EXT.includes(ext)) marks.push('--')
51 return marks.length > 0 ? marks : undefined
52}
53
54export const startsWithAny = (line: string, marks: readonly string[]) => marks.some((mark) => line.startsWith(mark))
55
56export type DiffLine = { path: string; body: string; isNewFile: boolean }
57
58export const addedLines = (diff: string): DiffLine[] => {
59 const out: DiffLine[] = []
60 let path: string | undefined
61 let isNewFile = false
62 for (const line of splitLines(diff)) {
63 if (line.startsWith('--- ')) {
64 isNewFile = line.slice(4).trim() === '/dev/null'
65 continue
66 }
67 if (line.startsWith('+++ ')) {
68 const raw = line.slice(4).trim()
69 path = raw === '/dev/null' ? undefined : raw.slice(2)
70 continue
71 }
72 if (path === undefined || !line.startsWith('+') || line.startsWith('+++')) continue
73 out.push({ path, body: line.slice(1), isNewFile })
74 }
75 return out
76}
77
78export const worktreesOf = (porcelain: string) =>
79 splitLines(porcelain)
80 .filter((line) => line.startsWith('worktree '))
81 .map((line) => line.slice('worktree '.length))
82
83export const claimedWorktrees = (blob: string, known: string[]) => {
84 const hits = known.filter((wt) => blob.includes(wt))
85 return hits.filter((wt) => !hits.some((other) => other !== wt && other.startsWith(wt)))
86}
87hooks/shared/paths.ts 24 lines1const TEMP_ROOTS = ['/tmp/', '/private/tmp/', '/var/folders/', '/private/var/folders/']
2
3export const dirOf = (path: string) => {
4 const slash = path.lastIndexOf('/')
5 return slash > 0 ? path.slice(0, slash) : slash === 0 ? '/' : '.'
6}
7
8export const isDotfileOrTemp = (path: string, home: string | undefined, tmpdir: string | undefined) =>
9 (home !== undefined && path.startsWith(`${home}/.`)) ||
10 TEMP_ROOTS.some((root) => path.startsWith(root)) ||
11 (tmpdir !== undefined && tmpdir !== '' && path.startsWith(tmpdir))
12
13export const isTrim = (added: string, removed: string) => added.length < removed.length
14
15// `sh -c MEDIA_CHECK lean <path>` exits 0 for media and marketing work (a reel, a brand sheet): the file's own checkout
16// ignores it, or a folder between it and that checkout's root holds a .lean-skip marker. Run from the file's checkout,
17// a worktree under a main repo's ignored .worktrees/ still counts as code.
18export const MEDIA_CHECK = [
19 'd=$(dirname "$1"); while [ ! -d "$d" ]; do d=$(dirname "$d"); done; cd "$d" || exit 1',
20 'git check-ignore -q -- "$1" 2>/dev/null && exit 0',
21 'r=$(git rev-parse --show-toplevel 2>/dev/null) || exit 1; x=$(pwd -P)',
22 'while :; do [ -e "$x/.lean-skip" ] && exit 0; { [ "$x" = "$r" ] || [ "$x" = / ]; } && exit 1; x=$(dirname "$x"); done',
23].join('\n')
24hooks/shared/verdict.ts 27 lines1export const MODEL = 'claude-haiku-4-5-20251001'
2
3export const SYSTEM =
4 'You are a hook reviewer. Reply with one JSON object and nothing else: {"ok": true} or {"ok": false, "reason": "..."}.'
5
6export type Verdict = { ok: true } | { ok: false; reason: string }
7
8export type Review = { name: string; prompt: string; status: string }
9
10export const promptFor = (review: Review, input: object) => review.prompt.replace('$ARGUMENTS', () => JSON.stringify(input))
11
12export const verdictOf = (reply: string): Verdict | undefined => {
13 const json = reply.match(/\{[\s\S]*\}/)
14 if (!json) return undefined
15 let parsed: unknown
16 try {
17 parsed = JSON.parse(json[0])
18 } catch {
19 return undefined
20 }
21 if (typeof parsed !== 'object' || parsed === null || !('ok' in parsed) || typeof parsed.ok !== 'boolean') {
22 return undefined
23 }
24 if (parsed.ok) return { ok: true }
25 return { ok: false, reason: 'reason' in parsed && typeof parsed.reason === 'string' ? parsed.reason : '' }
26}
27