Denies a new agent working file (plan, evidence, prototype, scratch, report, probe test) outside .claude/work/, which is gitignored, with a per-repo allow…

A mod (a plugin that adds a hook to Claude Code) that denies a new agent working file outside .claude/work/. Plans, evidence, prototypes and reports then stay out of your repo. At session start it also removes old entries from .claude/work/.
Agents write plans, scratch notes, reports and probe tests into the repo as they work. These files end up in commits.
work-folder denies the write and tells Claude to use .claude/work/<topic>/ instead. That folder is gitignored. Nobody deletes its folders afterwards, and probe runs can fill them with gigabytes, so work-folder removes each entry that has not changed for a day.
/plugin marketplace add cpeaustriajc/cj-stack
/plugin install work-folder@cj-stack
To see that it is on, run claude plugin list and look for work-folder. The mod is optional: cj-stack does not install it.
reports/x.md with the Write tool.reports/ is a planning folder..claude/work/ instead.If you keep such files in the repo on purpose, add them to the allow list below.
The hook checks the Write and NotebookEdit tools. It judges the path from the nearest folder that holds a .git entry.
| Event | Decision |
|---|---|
| A new file matches a deny pattern | Deny, and name the pattern and the fix. |
| A new file matches an allow entry | Pass. |
| The file already exists | Pass. |
The path is under a tool folder such as .claude/ or .github/ | Pass. |
| The path is outside any git repo | Pass. |
| The allow file is not valid | Deny, and name the file and the fix. |
| The file system check fails on a path that could match | Deny with "could not check". |
The deny patterns are:
| Pattern | Example |
|---|---|
Prototype, scratch, recovery, spike or .local folders | prototypes/x/index.html |
reports/ and planning folders under docs/ | docs/plans/x.md |
| Test artifact and evidence folders | .e2e-evidence/run.sh |
A loose .md, .html or .txt file at the repo root | validate.html |
| Findings, report, plan or numbered evidence file names | 107-EVIDENCE.md |
| Probe and temporary test file names | zz-probe-load.spec.ts |
Root files such as README.md and CLAUDE.md pass. The full lists are in hooks/register.ts.
At session start, the hook finds the repo root from the session folder and lists .claude/work/. It judges each entry there (a topic folder or a loose file) by the newest file in it.
| Entry | Decision |
|---|---|
No file in it changed for keepDays days | Remove it with git clean -ffdX, and show a toast that names it. |
One file in it changed in the last keepDays days | Keep the whole entry. |
| A file in it is tracked by git | Keep that file: git clean -X removes only ignored files. |
keepDays is 0 | Do nothing. |
keepDays is not valid | Do nothing, and show a toast that names the file and the fix. |
git clean fails | The session starts. The debug log names the failed hook. |
To keep a file in the repo, create .claude/work-folder.json at the repo root:
{ "allow": ["path/prefix/", "glob/**/*.md"] }
An entry that ends with / is a path prefix. Any other entry is a glob.
keepDays in .claude/work-folder.json: the days without a change before the cleanup removes an entry. The default is 1; 0 turns the cleanup off. Example: { "allow": [], "keepDays": 7 } keeps evidence for a week of review.
To turn the mod off, run claude plugin disable work-folder@cj-stack.
.claude/work/ to .gitignore. If git does not ignore that folder, the cleanup removes nothing..claude/work/ is cleaned by a session there.keepDays..claude/work/ or retry.hooks/register.ts 207 lines1import type { Hook, Register } from 'claude-code'
2
3type Api = Parameters<Hook<'tool.call'>>[0]
4
5const MOD = 'work-folder'
6const CONFIG = '.claude/work-folder.json'
7const WORK = '.claude/work'
8const KEEP_DAYS = 1
9const DAY = 86_400_000
10
11const TOOL_FOLDERS = new Set([
12 '.claude', '.agents', '.agent', '.codex', '.cursor', '.gemini', '.grok', '.muse', '.qwen', '.kimi', '.kimi-code',
13 '.trae', '.codebuddy', '.comate', '.lingma', '.qoder', '.windsurf', '.devin', '.kiro', '.roo', '.cline',
14 '.clinerules', '.continue', '.junie', '.opencode', '.factory', '.augment', '.kilo', '.kilocode', '.github',
15 '.vscode', '.idea',
16])
17
18const ROOT_DOCS = new Set([
19 'readme', 'claude', 'claude.local', 'agents', 'agents.override', 'gemini', 'qwen', 'codebuddy', 'codebuddy.local',
20 'warp', 'changelog', 'contributing', 'security', 'code_of_conduct', 'license', 'notice', 'llms', 'llms-full',
21])
22
23const RULES: { why: string; test: (folders: string[], base: string, rel: string) => boolean }[] = [
24 {
25 why: 'a prototype, scratch, recovery, research-notes, spike or .local folder',
26 test: f => f.some(s => ['prototypes', '.scratch', '.recovery', 'research_notes'].includes(s) || s.startsWith('spike-') || s.endsWith('.local')),
27 },
28 {
29 why: 'a reports/ or docs/ planning folder',
30 test: (_f, _b, rel) => /^(reports|docs\/(stories|epics|research|perf|qa|implementation|plans|plan|notes))\//.test(rel),
31 },
32 {
33 why: 'a test artifact or evidence folder',
34 test: f => f.some(s => ['artifacts', '.e2e-evidence', 'test-results'].includes(s)),
35 },
36 {
37 why: 'a loose document at the repo root',
38 test: (f, b) => f.length === 0 && /\.(md|html|txt)$/.test(b) && !ROOT_DOCS.has(b.replace(/\.[^.]*$/, '').toLowerCase()),
39 },
40 {
41 why: 'a findings, report, plan or numbered evidence file name',
42 test: (_f, b) =>
43 /^\d+-[A-Z][A-Z0-9-]*\.md$/.test(b) ||
44 /^\d+-[a-z-]*verification\.json$/.test(b) ||
45 /^(findings|report|summary|scores)\.md$/i.test(b) ||
46 /-(report|plan|draft)\.md$/.test(b) ||
47 /-decisions-[^/]*\.md$/.test(b),
48 },
49 {
50 why: 'a probe or temporary test file name',
51 test: (_f, b) => b.startsWith('zz-probe-') || b.startsWith('test_zz_') || b.endsWith('_tmp.py'),
52 },
53]
54
55function reason(rel: string): string | undefined {
56 const segs = rel.split('/')
57 if (TOOL_FOLDERS.has(segs[0])) return undefined
58 const base = segs[segs.length - 1]
59 const folders = segs.slice(0, -1)
60 return RULES.find(r => r.test(folders, base, rel))?.why
61}
62
63// Every tail is a possible rel, as the root is unknown before fs; the claude-owned runner has no fs hook.
64function mayMatch(segs: string[]): boolean {
65 return segs.some(
66 (_s, i) => !TOOL_FOLDERS.has(segs[i - 1]) && !TOOL_FOLDERS.has(segs[i - 2]) && reason(segs.slice(i).join('/')) !== undefined,
67 )
68}
69
70function globToRegExp(glob: string): RegExp {
71 const src = glob
72 .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
73 .replace(/\*\*\//g, '\u0000')
74 .replace(/\*\*/g, '\u0001')
75 .replace(/\*/g, '[^/]*')
76 .replace(/\u0000/g, '(?:.*/)?')
77 .replace(/\u0001/g, '.*')
78 return new RegExp(`^${src}$`)
79}
80
81function allowed(rel: string, allow: string[]): boolean {
82 return allow.some(a => (a.endsWith('/') ? rel.startsWith(a) : globToRegExp(a).test(rel)))
83}
84
85function parseAllow(text: string): string[] {
86 const data = JSON.parse(text) as unknown
87 if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('not a JSON object')
88 const allow = (data as { allow?: unknown }).allow
89 if (allow === undefined) return []
90 if (!Array.isArray(allow) || !allow.every(a => typeof a === 'string')) throw new Error('"allow" is not an array of strings')
91 return allow
92}
93
94function parseKeepDays(text: string): number {
95 const data = JSON.parse(text) as unknown
96 if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('not a JSON object')
97 const days = (data as { keepDays?: unknown }).keepDays
98 if (days === undefined) return KEEP_DAYS
99 if (typeof days !== 'number' || !Number.isFinite(days) || days < 0) throw new Error('"keepDays" is not a number of days, 0 or more')
100 return days
101}
102
103async function repoRoot($: Api, path: string): Promise<string | undefined> {
104 const norm = path.replace(/\\/g, '/')
105 const lead = norm.startsWith('/') ? '/' : ''
106 const segs = norm.split('/').filter(Boolean)
107 for (let i = segs.length; i > 0; i--) {
108 const dir = lead + segs.slice(0, i).join('/')
109 if (await $.fs.exists(`${dir}/.git`)) return dir
110 }
111 return undefined
112}
113
114// Symbolic links are not followed: their own mtimeMs is 0 and git clean removes only the link.
115async function changedSince($: Api, path: string, cutoff: number): Promise<boolean> {
116 const stat = await $.fs.stat(path)
117 if (stat.mtimeMs > cutoff) return true
118 if (stat.kind !== 'dir' || stat.isLink) return false
119 for (const entry of await $.fs.list(path)) {
120 if (entry.kind === 'dir' ? await changedSince($, `${path}/${entry.name}`, cutoff) : entry.mtimeMs > cutoff) return true
121 }
122 return false
123}
124
125async function cleanWork($: Api, cwd: string): Promise<void> {
126 const root = await repoRoot($, cwd)
127 if (root === undefined || !(await $.fs.exists(`${root}/${WORK}`))) return
128 const config = `${root}/${CONFIG}`
129 let days = KEEP_DAYS
130 if (await $.fs.exists(config)) {
131 try {
132 days = parseKeepDays((await $.fs.read(config)) as string)
133 } catch (err) {
134 $.ui.toast(`${MOD}: ${config} is not valid (${(err as Error).message}). Fix it to { "keepDays": 1 }, or delete it. Nothing in ${WORK} was cleaned.`)
135 return
136 }
137 }
138 if (days === 0) return
139 const cutoff = (await $.clock.now()) - days * DAY
140 const stale: string[] = []
141 for (const entry of await $.fs.list(`${root}/${WORK}`)) {
142 if (!(await changedSince($, `${root}/${WORK}/${entry.name}`, cutoff))) stale.push(entry.name)
143 }
144 if (stale.length === 0) return
145 const { exitCode, stderr } = await $.process.run(['git', 'clean', '-ffdX', '--', ...stale.map(n => `${WORK}/${n}`)], { cwd: root })
146 if (exitCode !== 0) throw new Error(`git clean exited ${exitCode}: ${stderr.trim()}`)
147 $.ui.toast(`${MOD}: cleaned ${stale.length} ${stale.length === 1 ? 'entry' : 'entries'} in ${WORK} not changed for ${days} ${days === 1 ? 'day' : 'days'}: ${stale.join(', ')}`)
148}
149
150async function judge($: Api, path: string): Promise<string | undefined> {
151 const abs = path.replace(/\\/g, '/')
152 const segs = abs.split('/').filter(Boolean)
153 if (!mayMatch(segs)) return undefined
154 if (await $.fs.exists(abs)) return undefined
155 let root: string | undefined
156 for (let i = segs.length - 1; i >= 0 && root === undefined; i--) {
157 const dir = `/${segs.slice(0, i).join('/')}`.replace(/^\/$/, '')
158 if (await $.fs.exists(`${dir}/.git`)) root = dir
159 }
160 if (root === undefined) return undefined
161 const rel = abs.slice(root.length + 1)
162 const why = reason(rel)
163 if (!why) return undefined
164 const config = `${root}/${CONFIG}`
165 let allow: string[] = []
166 if (await $.fs.exists(config)) {
167 const text = (await $.fs.read(config)) as string
168 try {
169 allow = parseAllow(text)
170 } catch (err) {
171 return `${MOD}: ${config} is not valid (${(err as Error).message}). Fix it to { "allow": ["path/prefix/", "glob/**/*.md"] }, or delete it.`
172 }
173 }
174 if (allowed(rel, allow)) return undefined
175 return (
176 `${MOD}: ${rel} looks like an agent working file (${why}). Write it under .claude/work/<topic>/ instead; ` +
177 `that folder is gitignored. If a person keeps this file in the repo, add it to "allow" in ${CONFIG}.`
178 )
179}
180
181export const register: Register = on => {
182 on('session.start', async ($, e, next) => {
183 const result = await next(e)
184 try {
185 await cleanWork($, e.cwd)
186 } catch (cause) {
187 throw new Error(`${MOD}: could not clean ${WORK}`, { cause })
188 }
189 return result
190 })
191
192 const guard = (path: string, why = 'no answer') =>
193 mayMatch(path.replace(/\\/g, '/').split('/').filter(Boolean))
194 ? { deny: `${MOD}: could not check ${path} (${why}). Write it under .claude/work/<topic>/ instead, or retry.` }
195 : undefined
196
197 on('tool.call', { tool: 'Write' }, async ($, e, next) => {
198 const deny = await judge($, e.file_path)
199 return deny ? { deny } : next(e)
200 }).catch(($, e, next) => (next.called ? next(e) : (guard(e.file_path, next.error.message) ?? next(e))))
201
202 on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => {
203 const deny = await judge($, e.notebook_path)
204 return deny ? { deny } : next(e)
205 }).catch(($, e, next) => (next.called ? next(e) : (guard(e.notebook_path, next.error.message) ?? next(e))))
206}
207