Comments worth keeping: limit-edits flags comment-heavy edits, limit-turns shows a one-line notice when a turn's diff adds too many comments.

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 182 lines1import type { EngineInterface, Register } from 'claude-code'
2import { commentsInDiff, commentsInFile, MAX_BLOCKS, reportKey, turnReport, type CommentFinding } from './comments'
3import { ADD_LIMIT } from './rules'
4import { amends, authorsHistory } from './shared/anchor'
5import { baseName, claimedWorktrees, prefixes, splitLines, worktreesOf } from './shared/diff'
6import { MEDIA_CHECK } from './shared/paths'
7import { addedSignal, densitySignal, editGuidance } from './signals'
8
9type Owned = { head: string; seen: string; baseline: Set<string>; status: string; touched: boolean }
10
11const MAX_UNTRACKED_CHARS = 512_000
12const INSTALL_ROOTS = ['.agents/skills', '.claude/skills', '.claude/plugins']
13
14let worktrees: string[] | undefined
15const owned = new Map<string, Owned>()
16const reported = new Set<string>()
17let blocks = 0
18// The report behind the last one-line notice, carried unseen to the model with the user's next prompt.
19let pendingReport: string | undefined
20const HUMAN_ORIGINS: readonly string[] = ['composer', 'bridge', 'sdk']
21
22// Built rather than typed: a literal NUL in this file makes git call it binary and stop diffing it.
23const SEP = String.fromCharCode(0)
24
25const keyOf = (path: string, line: string) => `${path}${SEP}${line}`
26
27const git = async ($: EngineInterface, cwd: string | undefined, args: string[]) => {
28 const run = await $.process.run(cwd === undefined ? ['git', ...args] : ['git', '-C', cwd, ...args])
29 return run.exitCode === 0 ? run.stdout.trim() : undefined
30}
31
32const addedComments = async ($: EngineInterface, wt: string, base: string) => {
33 const diff = await git($, wt, ['diff', '--unified=0', base])
34 const found = diff ? commentsInDiff(diff) : {}
35 for (const rel of splitLines((await git($, wt, ['ls-files', '--others', '--exclude-standard'])) ?? '')) {
36 if (!prefixes(rel)) continue
37 const text = await $.fs.read(`${wt}/${rel}`).catch(() => undefined)
38 if (text === undefined || text.length > MAX_UNTRACKED_CHARS) continue
39 const comments = commentsInFile(rel, text)
40 if (comments.length > 0) (found[rel] ??= []).push(...comments)
41 }
42 return found
43}
44
45// Decided on where the file lands: ~/.claude/skills/<name> may link back into a source checkout, which stays checked.
46const isInstalled = async ($: EngineInterface, path: string) => {
47 const home = await $.env.get('HOME')
48 if (!home) return false
49 const real = (await $.fs.stat(path, { resolve: true }).catch(() => undefined))?.realPath ?? path
50 return INSTALL_ROOTS.some((root) => real.startsWith(`${home}/${root}/`))
51}
52
53const statusOf = async ($: EngineInterface, wt: string) => (await git($, wt, ['status', '--porcelain'])) ?? ''
54
55const anchor = async ($: EngineInterface, wt: string, head: string) => {
56 const baseline = new Set<string>()
57 for (const [path, lines] of Object.entries(await addedComments($, wt, head))) {
58 for (const line of lines) baseline.add(keyOf(path, line))
59 }
60 return { head, seen: head, baseline, status: await statusOf($, wt) }
61}
62
63const claim = async ($: EngineInterface, blob: string) => {
64 if (!blob) return
65 if (worktrees === undefined) {
66 const root = await git($, undefined, ['rev-parse', '--show-toplevel'])
67 worktrees = root ? worktreesOf((await git($, root, ['worktree', 'list', '--porcelain'])) ?? '') : []
68 }
69 for (const wt of claimedWorktrees(blob, worktrees)) {
70 if (owned.has(wt)) continue
71 const head = await git($, wt, ['rev-parse', 'HEAD'])
72 if (!head) continue
73 owned.set(wt, { ...(await anchor($, wt, head)), touched: false })
74 }
75}
76
77// The command text alone kept 6aed9cb across `git reset --hard origin/dev && git cherry-pick -n 6aed9cb`, and ten dev
78// commits read as this session's. An amend replaces HEAD on the same parent instead of descending from it.
79const authoredMove = async ($: EngineInterface, wt: string, command: string | undefined, from: string, to: string) => {
80 if (command === undefined || !authorsHistory(command)) return false
81 if ((await git($, wt, ['merge-base', '--is-ancestor', from, to])) !== undefined) return true
82 if (!amends(command)) return false
83 const [was, now] = splitLines((await git($, wt, ['rev-parse', `${from}^`, `${to}^`])) ?? '')
84 return was !== undefined && was === now
85}
86
87// Between two of our own calls another agent sharing the checkout can commit, fast-forward or reset it, and every line
88// arriving that way would otherwise read as this turn's work.
89const settle = async ($: EngineInterface, command?: string) => {
90 for (const [wt, info] of owned) {
91 let next = info
92 const head = await git($, wt, ['rev-parse', 'HEAD'])
93 if (head !== undefined && head !== next.seen) {
94 next = (await authoredMove($, wt, command, next.seen, head))
95 ? { ...next, seen: head }
96 : { ...(await anchor($, wt, head)), touched: next.touched }
97 }
98 if (!next.touched) {
99 const status = await statusOf($, wt)
100 if (status !== next.status) next = { ...next, status, touched: true }
101 }
102 owned.set(wt, next)
103 }
104}
105
106const markTouched = (path: string) => {
107 for (const [wt, info] of owned) {
108 if (!info.touched && path.startsWith(`${wt}/`)) owned.set(wt, { ...info, touched: true })
109 }
110}
111
112const overBudget = async ($: EngineInterface) => {
113 const findings: CommentFinding[] = []
114 const bases: string[] = []
115 for (const [wt, info] of owned) {
116 if (!info.touched) continue
117 const before = findings.length
118 for (const [path, lines] of Object.entries(await addedComments($, wt, info.head))) {
119 const fresh = lines.filter((line) => !info.baseline.has(keyOf(path, line)))
120 const skipped = (await isInstalled($, `${wt}/${path}`)) || (await isMediaWork($, `${wt}/${path}`))
121 if (fresh.length > ADD_LIMIT && !skipped) findings.push({ path, lines: fresh })
122 }
123 if (findings.length > before) bases.push(info.head)
124 }
125 if (findings.length === 0) return undefined
126 const key = reportKey(findings)
127 if (reported.has(key) || blocks >= MAX_BLOCKS) return undefined
128 reported.add(key)
129 blocks++
130 return turnReport(findings, bases)
131}
132
133const isMediaWork = async ($: EngineInterface, path: string) =>
134 (await $.process.run(['sh', '-c', MEDIA_CHECK, 'lean', path])).exitCode === 0
135
136export const register: Register = (on) => {
137 on('prompt.submit', ($, e, next) => {
138 if (pendingReport === undefined || !HUMAN_ORIGINS.includes(e.origin.kind)) return next(e)
139 const context = [...(e.context ?? []), pendingReport]
140 pendingReport = undefined
141 return next({ ...e, context })
142 })
143
144 on('tool.call', { tool: ['Bash', 'Write', 'Edit'] }, async ($, e, next) => {
145 await claim($, e.tool === 'Bash' ? e.command : e.file_path)
146 const result = await next(e)
147 if (e.tool === 'Bash') await settle($, e.command)
148 else if (result.deny === undefined && !result.isError) markTouched(e.file_path)
149 return result
150 })
151
152 on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
153 const result = await next(e)
154 if (result.deny !== undefined || result.isError) return result
155 const path = e.file_path
156 const text = e.tool === 'Write' ? e.content : e.new_string
157 const marks = prefixes(path)
158 if (!path || !text || !marks || (await isInstalled($, path)) || (await isMediaWork($, path))) return result
159 const body = await $.fs.read(path).catch(() => undefined)
160 const findings = [addedSignal(text, marks, path), body === undefined ? undefined : densitySignal(path, body, text, marks)].filter(
161 (finding): finding is string => finding !== undefined,
162 )
163 if (findings.length === 0) return result
164 const name = baseName(path)
165 $.ui.log(`lean-comments/limit-edits: ${findings.length} signal(s) on ${name}`)
166 return { ...result, context: [...(result.context ?? []), editGuidance(name, findings)] }
167 })
168
169 // A one-line notice for the user; the report waits, unseen, for their next prompt.
170 on('turn.complete', async ($, e, next) => {
171 const result = await next(e)
172 if (e.agentId !== undefined || e.reason !== 'answer' || owned.size === 0) return result
173 await settle($)
174 const report = await overBudget($)
175 if (report !== undefined) {
176 $.ui.log('lean-comments: this turn added more comments than the budget; say "trim comments" to review them')
177 pendingReport = report
178 }
179 return result
180 })
181}
182hooks/comments.ts 53 lines1import { ADD_LIMIT, docstringLines, KEEP } from './rules'
2import { baseNote } from './shared/anchor'
3import { addedLines, OUTRANKS, prefixes, splitLines, startsWithAny } from './shared/diff'
4
5export const MAX_BLOCKS = 2
6
7export type CommentFinding = { path: string; lines: string[] }
8
9export const commentsInDiff = (diff: string): Record<string, string[]> => {
10 const added: Record<string, string[]> = {}
11 for (const { path, body } of addedLines(diff)) {
12 if (!prefixes(path)) continue
13 const stripped = body.trim()
14 if (stripped.startsWith('#!')) continue
15 ;(added[path] ??= []).push(stripped)
16 }
17 const found: Record<string, string[]> = {}
18 for (const [path, bodies] of Object.entries(added)) {
19 const marks = prefixes(path) ?? []
20 const docs = docstringLines(bodies, path)
21 bodies.forEach((body, i) => {
22 if (startsWithAny(body, marks) || docs.has(i)) (found[path] ??= []).push(body)
23 })
24 }
25 return found
26}
27
28export const commentsInFile = (rel: string, text: string): string[] => {
29 const marks = prefixes(rel)
30 if (!marks) return []
31 const lines = splitLines(text).map((line) => line.trim())
32 const docs = docstringLines(lines, rel)
33 return lines.filter((line, i) => !line.startsWith('#!') && (startsWithAny(line, marks) || docs.has(i)))
34}
35
36export const reportKey = (findings: CommentFinding[]) => JSON.stringify(findings.map((f) => [f.path, f.lines]).sort())
37
38export const turnReport = (findings: CommentFinding[], bases: readonly string[] = []) => {
39 const parts = findings.map(({ path, lines }) => {
40 const shown = lines.slice(0, 8).map((l) => ` ${l}`).join('\n')
41 const more = lines.length <= 8 ? '' : `\n ... +${lines.length - 8} more`
42 return ` ${path} - ${lines.length} added comment lines:\n${shown}${more}`
43 })
44 const note = baseNote(bases)
45 return (
46 `lean-comments/limit-turns: this turn's diff adds more comment lines than the budget of ${ADD_LIMIT} per file.\n\n` +
47 `${parts.join('\n')}\n${note === undefined ? '' : `${note}\n`}${KEEP}\n\n` +
48 'This check reads git diff, so it sees edits made through Bash, sed and ' +
49 `heredocs that the per-edit check never sees.\n${OUTRANKS}\n` +
50 '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.'
51 )
52}
53hooks/rules.ts 70 lines1import { extOf, startsWithAny } from './shared/diff'
2
3export const ADD_LIMIT = 3
4export const CONTEXT = 15
5export const MAX_DENSITY = 0.3
6export const MIN_REGION_COMMENTS = 4
7export const MAX_RUN = 5
8
9const TRIPLE_EXT = ['.py', '.pyi']
10const QUOTES = ['"""', "'''"]
11
12export const KEEP =
13 'Keep a comment that records a measured number, an observed behaviour, a ' +
14 'named bug or version pin, a trap whose obvious cleanup would silently ' +
15 'break something, or an invariant spanning processes - those are the ones ' +
16 'this codebase is built on. Delete the ones that restate the code, narrate ' +
17 'the change, or argue a decision; that reasoning belongs in the commit ' +
18 "message or the project's decision log."
19
20// Only blocks whose opening line starts with the quote: `sql = """SELECT` is a value, not prose.
21export const docstringLines = (lines: string[], path: string | undefined): Set<number> => {
22 const out = new Set<number>()
23 if (!path || !TRIPLE_EXT.includes(extOf(path))) return out
24 let quote: string | undefined
25 let pending: number[] = []
26 lines.forEach((raw, i) => {
27 const line = raw.trim()
28 if (quote === undefined) {
29 const opener = line.replace(/^[rRfFbBuU]+/, '')
30 if (!QUOTES.some((q) => opener.startsWith(q))) return
31 quote = opener.slice(0, 3)
32 pending = [i]
33 if (opener.slice(3).includes(quote)) {
34 pending.forEach((n) => out.add(n))
35 quote = undefined
36 }
37 } else {
38 pending.push(i)
39 if (line.includes(quote)) {
40 pending.forEach((n) => out.add(n))
41 quote = undefined
42 }
43 }
44 })
45 if (quote !== undefined && pending[0] !== undefined) out.add(pending[0])
46 return out
47}
48
49export const classify = (lines: string[], marks: readonly string[], firstIsFileStart: boolean, path?: string) => {
50 const docs = docstringLines(lines, path)
51 const comment: number[] = []
52 let code = 0
53 lines.forEach((raw, i) => {
54 const line = raw.trim()
55 if (line === '') return
56 if (firstIsFileStart && i === 0 && line.startsWith('#!')) return
57 if (startsWithAny(line, marks) || docs.has(i)) comment.push(i)
58 else code++
59 })
60 return { comment, code }
61}
62
63// Python's round() rounds halves to even; percentages here must print as the Python guard printed them.
64export const roundHalfEven = (value: number) => {
65 const floor = Math.floor(value)
66 const diff = value - floor
67 if (Math.abs(diff - 0.5) > 1e-9) return Math.round(value)
68 return floor % 2 === 0 ? floor : floor + 1
69}
70hooks/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/signals.ts 56 lines1import { ADD_LIMIT, classify, CONTEXT, KEEP, MAX_DENSITY, MAX_RUN, MIN_REGION_COMMENTS, roundHalfEven } from './rules'
2import { OUTRANKS, splitLines } from './shared/diff'
3
4export const addedSignal = (text: string, marks: readonly string[], path: string) => {
5 const { comment } = classify(splitLines(text), marks, true, path)
6 return comment.length > ADD_LIMIT ? `This edit adds ${comment.length} comment-only lines (soft limit ${ADD_LIMIT}).` : undefined
7}
8
9// Only an edit that adds comments of its own makes the region's density its business.
10export const densitySignal = (path: string, body: string, text: string, marks: readonly string[]) => {
11 const own = classify(splitLines(text), marks, true, path).comment.length
12 if (own === 0) return undefined
13 const lines = splitLines(body)
14 const index = body.indexOf(text)
15 if (index < 0) return undefined
16 const start = body.slice(0, index).split('\n').length - 1
17 const end = start + text.split('\n').length - 1
18 const lo = Math.max(0, start - CONTEXT)
19 const hi = Math.min(lines.length, end + CONTEXT + 1)
20 const { comment, code } = classify(lines.slice(lo, hi), marks, lo === 0, path)
21 const total = comment.length + code
22 if (total === 0) return undefined
23
24 let run = 0
25 let runStart = 0
26 let best = 0
27 let bestStart = 0
28 let previous: number | undefined
29 for (const i of comment) {
30 if (previous !== undefined && i === previous + 1) run++
31 else [run, runStart] = [1, i]
32 if (run > best) [best, bestStart] = [run, runStart]
33 previous = i
34 }
35
36 const density = comment.length / total
37 const dense = comment.length >= MIN_REGION_COMMENTS && density > MAX_DENSITY
38 const blocky = best >= MAX_RUN
39 if (!dense && !blocky) return undefined
40
41 const percent = roundHalfEven(density * 100)
42 const what = blocky
43 ? `a ${best}-line comment block at line ${lo + bestStart + 1} (region is ${percent}% comment)`
44 : `${percent}% comment - ${comment.length} comment lines against ${code} of code`
45 return (
46 `The region you edited (${path}:${lo + 1}-${hi}) carries ${what}, and this edit adds ${own} comment ` +
47 `line${own === 1 ? '' : 's'} to it. Cut yours to what earns its place; the comments you did not write are not yours to prune.`
48 )
49}
50
51export const editGuidance = (name: string, findings: string[]) =>
52 `lean-comments/limit-edits on ${name}:\n${findings.map((f) => `- ${f}`).join('\n')}\n\n` +
53 'No comments by default.\n' +
54 `${KEEP}\n${OUTRANKS}\n` +
55 'Prune, then say in your reply which comments you kept and why.'
56