/commit [instructions]: drafts a commit plan, confirms it in a pane and a confirm dialog, then commits; the transcript keeps only the command and the result

A Claude Code mod that adds /commit: Claude drafts a commit plan, you confirm it in a pane and a dialog, then it commits. The transcript keeps only the command and the result line, such as Committed 3f2a1c9 feat(api): add retry (2 files).
/commit
/commit only the docs, and mention the issue number
git status, the diff and the last 10 commits..env, *.pem, *.key, *.p12, names with credential or secret) and says so.Edit in editor opens the message in $VISUAL, else $EDITOR, else vi; save and close to return to the dialog. Use a waiting editor command such as zed --wait or code --wait.
The commit holds exactly what the pane showed. The mod builds it in a private index (GIT_INDEX_FILE), so files another session stages meanwhile stay out of the commit and stay staged. If the staged content, a selected file or HEAD changes between the plan and Commit, the mod drafts the plan again instead of committing; edits to files outside the plan do not.
The commit runs git commit through a shell, so the repository's hooks (such as pre-commit) run against that private index. If the commit fails, the shared index is untouched and the error shows in the pane.
At the prompt of a Claude Code terminal session:
/plugin install cc-commit-command --marketplace HuliLulu46/cc-commit-command
Answer y to add the marketplace, then pick a scope (user is first).
From a shell:
claude plugin install cc-commit-command --marketplace HuliLulu46/cc-commit-command
In the desktop app, where /plugin does not run: click + next to the prompt box, then Plugins, Add marketplace with HuliLulu46/cc-commit-command, then Add plugin.
Co-Authored-By) are added.Built against Claude Code 2.1.300. A mod is an early-access API that may change between releases.
claude plugin validate .
claude plugin test .
tsc -p .hooks/register.tsx 372 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { FileRow, View } from '../types'
5
6const COMMAND = 'commit'
7const PANE = 'cc-commit-command'
8const view = atom({ plugin: 'cc-commit-command', key: 'view' } as const, { files: [], message: '', note: '' } as View)
9
10const SUBMIT = 'Commit'
11const REGENERATE = 'Regenerate'
12const EDIT = 'Edit in editor'
13const CANCEL = 'Cancel'
14
15const SENSITIVE = /(^|\/)\.env($|\.)|\.(pem|key|p12)$|credential|secret/i
16const DIFF_LIMIT = 40_000
17
18const RULES = `- message uses Conventional Commits: <type>(<scope>): <subject>; for larger changes add a body after a blank line; type is one of feat, fix, docs, style, refactor, perf, test, build, ci, chore
19- Match the language and style of the recent commits
20- Describe only the changes in files; no attribution lines (such as Co-Authored-By)
21- Output only one JSON object {"files": [...], "message": "..."}, with no code fence or explanation`
22
23type Change = { status: string; path: string }
24type Plan = { files: string[]; message: string }
25type Repo = {
26 all: Change[]
27 // Only the staged files when the index is non-empty, otherwise all changes
28 candidates: Change[]
29 isStaged: boolean
30 branch: string
31 log: string
32 diff: string
33 // What the plan was drafted from: HEAD, and the tree of the index (staged) or of HEAD plus the candidates (otherwise)
34 head: string
35 tree: string
36}
37// adjust: new instructions given, so revise the previous version; otherwise produce a clearly different one
38type Request = Repo & { guidance: string; previous?: string; adjust?: boolean }
39type Reply = { isAnswered: boolean; text?: string; reason?: string }
40
41// Set on session.start
42let home = ''
43let cwd = ''
44
45function git($: EngineInterface, root: string, args: string[]) {
46 return $.process.run(['git', ...args], { cwd: root })
47}
48
49// Runs git against a throwaway index file, so the shared index other sessions stage into is never read or written
50async function withIndex<T>(
51 $: EngineInterface,
52 root: string,
53 fn: (run: (args: string[]) => ReturnType<typeof git>, file: string) => Promise<T>,
54): Promise<T> {
55 const path = (await git($, root, ['rev-parse', '--git-path', `cc-commit-command-${Date.now()}.index`])).stdout.trim()
56 const file = path.startsWith('/') ? path : `${root}/${path}`
57 try {
58 return await fn(args => $.process.run(['git', ...args], { cwd: root, env: { GIT_INDEX_FILE: file } }), file)
59 } finally {
60 await $.process.run(['rm', '-f', file])
61 }
62}
63
64const readHead = (head: string) => (head ? ['read-tree', head] : ['read-tree', '--empty'])
65
66const tail = (text: string, lines: number) => text.trim().split('\n').slice(-lines).join('\n')
67
68// -z format: each entry is "XY path"; renames and copies are followed by an extra entry with the original path
69function parseStatus(output: string): Change[] {
70 const parts = output.split('\0').filter(Boolean)
71 const changes: Change[] = []
72 for (let i = 0; i < parts.length; i++) {
73 const entry = parts[i] ?? ''
74 const status = entry.slice(0, 2)
75 changes.push({ status, path: entry.slice(3) })
76 if (status[0] === 'R' || status[0] === 'C') i++
77 }
78 return changes
79}
80
81async function snapshot(
82 $: EngineInterface,
83 root: string,
84 isStaged: boolean,
85 candidates: Change[],
86): Promise<{ head: string; tree: string } | string> {
87 const head = (await git($, root, ['rev-parse', '-q', '--verify', 'HEAD'])).stdout.trim()
88 const written = isStaged
89 ? await git($, root, ['write-tree'])
90 : await withIndex($, root, async run => {
91 for (const args of [readHead(head), ['add', '-A', '--', ...candidates.map(change => change.path)]]) {
92 const step = await run(args)
93 if (step.exitCode !== 0) return step
94 }
95 return run(['write-tree'])
96 })
97 if (written.exitCode !== 0) return `Reading the changes failed: ${tail(written.stderr, 3)}`
98 return { head, tree: written.stdout.trim() }
99}
100
101async function collect($: EngineInterface, root: string): Promise<Repo | string> {
102 const all = parseStatus(
103 (await git($, root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])).stdout,
104 )
105 const staged = all.filter(change => change.status[0] !== ' ' && change.status[0] !== '?')
106 const isStaged = staged.length > 0
107 const branch = (await git($, root, ['branch', '--show-current'])).stdout.trim() || 'HEAD'
108 const log = (await git($, root, ['log', '--oneline', '-10'])).stdout.trim()
109 let diff = (await git($, root, isStaged ? ['diff', '--cached'] : ['diff'])).stdout
110 if (!isStaged)
111 for (const change of all.filter(change => change.status === '??').slice(0, 20))
112 diff += (await git($, root, ['diff', '--no-index', '--', '/dev/null', change.path])).stdout
113 if (diff.length > DIFF_LIMIT) diff = `${diff.slice(0, DIFF_LIMIT)}\n… (diff too long, truncated)`
114 const candidates = isStaged ? staged : all
115 const taken = await snapshot($, root, isStaged, candidates)
116 if (typeof taken === 'string') return taken
117 return { all, candidates, isStaged, branch, log, diff, ...taken }
118}
119
120const contextOf = (r: Request) => `<repo>
121Branch: ${r.branch}
122Recent commits:
123${r.log || '(no commits yet)'}
124</repo>
125
126<candidates>
127${r.candidates.map(change => `${change.status} ${change.path}`).join('\n')}
128</candidates>
129
130<diff>
131${r.diff}
132</diff>${
133 r.guidance
134 ? `\n\nUser instructions for this commit (may add or remove files or rewrite the message):\n<guidance>\n${r.guidance}\n</guidance>`
135 : ''
136}${
137 r.previous
138 ? `\n\n${r.adjust ? 'This is the previous commit message; revise it according to <guidance>' : 'The user was not satisfied with the previous commit message; produce a clearly different version'}:\n<previous>\n${r.previous}\n</previous>`
139 : ''
140}`
141
142const forkPromptOf = (r: Request) => `This turn is not a new task: do not continue earlier work; only prepare one commit for the git changes below and output JSON as required.
143${
144 r.isStaged
145 ? '- files: the index is already chosen; return every file in <candidates> as is'
146 : '- files: pick from <candidates> the files this session changed, based on the edits and writes earlier in the conversation; skip files with no change record in the conversation, since they may come from other sessions or manual edits; files that <guidance> explicitly adds or removes follow <guidance>'
147}
148- files excludes likely sensitive files (.env, keys, credentials) unless <guidance> explicitly asks for them
149${RULES}
150
151${contextOf(r)}`
152
153const SYSTEM = `You write commit messages for git changes.
154- files returns every file in <candidates> as is
155${RULES}`
156
157function parsePlan(text: string, paths: string[]): Plan | undefined {
158 try {
159 const raw = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)) as {
160 files?: unknown
161 message?: unknown
162 }
163 if (typeof raw.message !== 'string' || !Array.isArray(raw.files)) return undefined
164 const files = raw.files.filter((file): file is string => typeof file === 'string' && paths.includes(file))
165 return { files, message: raw.message.trim() }
166 } catch {
167 return undefined
168 }
169}
170
171// The fork carries session context, so it can tell which files this session changed; with no conversation yet, fall back to sonnet, which sees only the diff
172async function generate($: EngineInterface, r: Request): Promise<{ plan: Plan; note: string } | string> {
173 const paths = r.candidates.map(change => change.path)
174 const forked = (await $.model.fork({ prompt: forkPromptOf(r) })) as Reply
175 const hasContext = forked.reason !== 'nothing-to-fork'
176 const reply = hasContext
177 ? forked
178 : ((await $.model.complete({ model: 'sonnet', system: SYSTEM, prompt: contextOf(r) })) as Reply)
179 if (!reply.isAnswered || !reply.text) return `Generation failed: ${reply.reason ?? 'the model returned nothing'}`
180 const plan = parsePlan(reply.text, paths)
181 if (!plan) return `Generation failed: the model did not return the expected format\n${tail(reply.text, 3)}`
182
183 const notes: string[] = []
184 if (r.isStaged) {
185 plan.files = paths
186 notes.push('Index already has staged changes: committing only the index')
187 } else if (!hasContext) {
188 plan.files = paths.filter(path => !SENSITIVE.test(path))
189 notes.push('No session context: selected all changes (except likely sensitive files); please review')
190 }
191 if (plan.files.some(path => SENSITIVE.test(path))) notes.push('⚠ Selected files include likely sensitive files')
192 return { plan, note: notes.join('\n') }
193}
194
195async function editMessage($: EngineInterface, message: string): Promise<{ message: string; error?: string }> {
196 const dir = `${home}/.claude/cache/cc-commit-command`
197 const file = `${dir}/COMMIT_EDITMSG`
198 await $.process.run(['mkdir', '-p', dir])
199 await $.fs.write(file, `${message}\n\n# Save and close to return to the confirm dialog; lines starting with # are ignored; an empty message keeps the original\n`)
200 // When EDITOR waits for close (e.g. zed --wait), this step blocks until the editor closes
201 const edited = await $.process.run(['/bin/sh', '-c', '${VISUAL:-${EDITOR:-vi}} "$0"', file], {
202 timeoutMs: 600_000,
203 })
204 if (edited.exitCode !== 0) return { message, error: `Editor exited with code ${edited.exitCode}: ${tail(edited.stderr, 2)}` }
205 const text = (await $.fs.read(file))
206 .split('\n')
207 .filter(line => !line.startsWith('#'))
208 .join('\n')
209 .trim()
210 return { message: text || message }
211}
212
213// Commits exactly the reviewed content from a private index: the staged tree as a whole, or the plan's files from the
214// candidates' tree on top of HEAD. Staging done meanwhile in the shared index stays out of the commit and stays staged.
215async function commit($: EngineInterface, root: string, repo: Repo, plan: Plan) {
216 return withIndex($, root, async (run, file) => {
217 const steps = repo.isStaged
218 ? [['read-tree', repo.tree]]
219 : [readHead(repo.head), ['reset', '-q', repo.tree, '--', ...plan.files]]
220 for (const args of steps) {
221 const step = await run(args)
222 if (step.exitCode !== 0) return { error: `Staging failed: ${tail(step.stderr, 3)}` }
223 }
224 // $.process.run disables repo hooks when running git directly; going through sh runs pre-commit and other hooks
225 const done = await $.process.run(['/bin/sh', '-c', 'git commit -F -'], {
226 cwd: root,
227 env: { GIT_INDEX_FILE: file },
228 stdin: plan.message,
229 timeoutMs: 600_000,
230 })
231 if (done.exitCode !== 0) return { error: `Commit failed:\n${tail(done.stderr || done.stdout, 5)}` }
232 // The shared index still holds the old content of the committed files; move them up to the new HEAD
233 if (!repo.isStaged) await git($, root, ['reset', '-q', '--', ...plan.files])
234 return { hash: (await git($, root, ['rev-parse', '--short', 'HEAD'])).stdout.trim() }
235 })
236}
237
238const rowsOf = (repo: Repo, plan: Plan | undefined): FileRow[] =>
239 repo.all.map(change => ({
240 ...change,
241 isSelected: plan?.files.includes(change.path) ?? false,
242 isSensitive: SENSITIVE.test(change.path),
243 }))
244
245export const register: Register = on => {
246 on('session.start', async ($, e, next) => {
247 home = (await $.env.get('HOME')) ?? ''
248 cwd = e.cwd
249 // No immediate: mid-turn the model may still be editing files, so wait for the turn to end before committing
250 await $.command.register({
251 name: COMMAND,
252 description: 'Draft a commit plan, confirm it in a dialog, then commit',
253 argumentHint: '[instructions]',
254 })
255 return next(e)
256 })
257
258 // Intermediate steps go only to the pane, confirm dialog and status line; the returned text is the only result line in the transcript
259 on('command.run', { command: COMMAND }, async ($, e) => {
260 const top = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { cwd })
261 if (top.exitCode !== 0) return { text: 'Not committed: current directory is not a git repository' }
262 const root = top.stdout.trim()
263 const first = await collect($, root)
264 if (typeof first === 'string') return { text: `Not committed: ${first}` }
265 if (first.all.length === 0) return { text: 'Not committed: no changes' }
266 let repo = first
267
268 let request: Request = { ...repo, guidance: e.args.trim() }
269 let plan: Plan | undefined
270 let note = ''
271 let notice = ''
272 let needsPlan = true
273 try {
274 for (;;) {
275 if (needsPlan) {
276 needsPlan = false
277 $.ui.status('Drafting commit plan…')
278 const generated = await generate($, request)
279 $.ui.status(undefined)
280 if (typeof generated === 'string') note = generated
281 else ({ plan, note } = generated)
282 note = [notice, note].filter(Boolean).join('\n')
283 notice = ''
284 }
285 await update($, view, () => ({ files: rowsOf(repo, plan), message: plan?.message ?? '', note }))
286 await $.ui.open({ id: PANE, title: `commit · ${repo.branch}` })
287
288 const answer = await $.ui
289 .ask('What would you like to do with this commit?', { header: 'commit', options: [SUBMIT, REGENERATE, EDIT, CANCEL] })
290 .catch(() => CANCEL)
291 if (answer === CANCEL) return { text: 'Cancelled, nothing committed' }
292 if (answer === REGENERATE) {
293 request = { ...request, previous: plan?.message, adjust: false }
294 needsPlan = true
295 } else if (answer === EDIT) {
296 if (!plan) continue
297 const edited = await editMessage($, plan.message)
298 plan = { ...plan, message: edited.message }
299 note = edited.error ?? note
300 } else if (answer === SUBMIT) {
301 if (!plan || plan.files.length === 0 || !plan.message) {
302 note = 'No files or commit message to commit'
303 continue
304 }
305 // A snapshot that no longer reads (a candidate gone from disk) has moved too. Unstaged, only the plan's files
306 // count, so another session editing some other file does not send the plan back.
307 const now = await snapshot($, root, repo.isStaged, repo.candidates)
308 const hasMoved =
309 typeof now === 'string' ||
310 now.head !== repo.head ||
311 (repo.isStaged
312 ? now.tree !== repo.tree
313 : (await git($, root, ['diff-tree', '--quiet', repo.tree, now.tree, '--', ...plan.files])).exitCode !== 0)
314 if (hasMoved) {
315 const fresh = await collect($, root)
316 if (typeof fresh === 'string') return { text: `Not committed: ${fresh}` }
317 if (fresh.all.length === 0) return { text: 'Not committed: no changes' }
318 repo = fresh
319 request = { ...fresh, guidance: request.guidance }
320 notice = 'Changes moved since the plan; drafted again'
321 needsPlan = true
322 continue
323 }
324 const result = await commit($, root, repo, plan)
325 if ('hash' in result) {
326 const subject = plan.message.split('\n')[0]
327 return { text: `Committed ${result.hash} ${subject} (${plan.files.length} ${plan.files.length === 1 ? 'file' : 'files'})` }
328 }
329 note = result.error
330 } else {
331 // The dialog's Other option: revision instructions typed by the user
332 const guidance = [request.guidance, answer].filter(Boolean).join('; ')
333 request = { ...request, guidance, previous: plan?.message, adjust: true }
334 needsPlan = true
335 }
336 }
337 } finally {
338 $.ui.status(undefined)
339 await $.ui.close({ id: PANE })
340 }
341 })
342
343 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
344 const { Box, Text } = $.ui.resolve(e)
345 const { files, message, note } = await read($, view)
346 const selected = files.filter(file => file.isSelected)
347 const skipped = files.filter(file => !file.isSelected)
348 const rowOf = (file: FileRow) => ` ${file.status} ${file.path}${file.isSensitive ? ' ⚠ likely sensitive' : ''}`
349 return (
350 <Box flexDirection="column">
351 <Text bold>{`To commit (${selected.length})`}</Text>
352 {selected.map(file => (
353 <Text>{rowOf(file)}</Text>
354 ))}
355 {skipped.length > 0 && <Text bold>{`Not committed (${skipped.length})`}</Text>}
356 {skipped.map(file => (
357 <Text dimColor>{rowOf(file)}</Text>
358 ))}
359 <Text> </Text>
360 {(message || '(no commit message yet)').split('\n').map(line => (
361 <Text>{line || ' '}</Text>
362 ))}
363 {note && <Text> </Text>}
364 {note &&
365 note.split('\n').map(line => (
366 <Text color="yellow">{line}</Text>
367 ))}
368 </Box>
369 )
370 })
371}
372types/index.d.ts 15 lines1export type FileRow = { status: string; path: string; isSelected: boolean; isSensitive: boolean }
2
3export type View = {
4 files: FileRow[]
5 message: string
6 // Hint at the bottom of the pane: no session context, commit failure reason, etc.
7 note: string
8}
9
10declare module 'claude-code' {
11 interface PluginState {
12 'cc-commit-command': { view: View }
13 }
14}
15