When an edit adds authorization, input validation or error handling, lists the refusal, invalid-input, failure and boundary-value tests that no test touched…

English | 日本語
Personal Claude Code mods (function-hook plugins), published as one marketplace.
| Mod | What it does |
|---|---|
agent-pane | Live pane of the session's subagents: running ones with elapsed time, finished ones with result and duration |
done-gate | Flags unverified edits, stops repeated failing commands, and blocks git --no-verify |
sandbox-lens | Tallies sandbox denials seen in Bash output and reports them with /sandbox-report |
todo-agent | Collects #TODO(agent) follow-ups from Claude's replies into a per-project list with a /todos pane. |
tool-row | Redraws finished tool-call rows in the terminal as one compact line with a Nerd Font icon, Gruvbox colors and a short stat |
image-preview | Thumbnails of the images a session writes, reads or generates: under the tool's row in the terminal, and in an /images pane |
self-audit | After each turn, a cached fork of the conversation audits Claude's own reply against the CLAUDE.md reporting rules and flags violations above the prompt |
browser-cam | Live pane of the browser Claude drives: the latest screenshot from Claude in Chrome, the page URL and the recent actions |
prompt-coach | Holds back a typed prompt that looks ambiguous (no done-condition, unclear target) and offers guesses at what it meant, sending it as is, or adding one; on by default |
loopback | Feeds what self-audit, done-gate and sandbox-lens found back to Claude beside the next prompt, instead of only showing it to the person, skipping rules hit-rate found mostly wrong; off by default |
zukan | Error book: catches the errors Bash commands hit across sessions and repos, records what got past each one, and when one comes back tells Claude and the person how it was fixed last time |
pr-lamp | The current branch's pull request as a lamp: checks, review, unresolved threads and what is left before a merge, in the status line and a /pr pane; red checks and new review comments go to Claude beside the next prompt |
fog-map | Exploration map: the repository as a tree under fog, cleared where Claude read and marked where it edited, made a file or hit an error, with the importers an edit may have broken unseen; /map |
assertion-guard | Catches edits that weaken tests to pass: assertions removed, expectations loosened or rewritten, tests skipped, errors swallowed; asks Claude for the reason beside the edit |
negative-space | When an edit adds authorization, validation or error handling, lists the refusal and boundary-value tests no test touched this session covers; /negative-space |
mutation-tap | /mutate runs a mutation test limited to the lines changed since HEAD and lists the mutants the tests did not catch |
perf-delta | /perf compares a benchmark before and after (a saved baseline, or a git ref in a temporary worktree): median time, peak memory, spread, and whether the change beats the noise |
port-lantern | The dev servers the session started: URL, port, whether each still listens, and their latest log lines, in the status line and /ports |
artifact-shelf | A shelf of what sessions made (CSV, PDF, HTML, video, patches…), tied to the call and request that made each; /shelf searches by kind, word and time |
side-effect-ledger | A ledger of what a git diff never shows (push, publish, deploy, PRs, API writes, messages) with outcome, how to undo, and whether the undo was checked; /ledger |
visual-diff | Compares browser screenshots of the same URL and size before and after an edit: side by side, a map of changed cells, regions, and the edits in between; /vdiff |
journey-trace | Records Claude's browser actions and the expected states as a replayable recipe; /journey md for a bug report, /journey e2e for a Playwright draft |
hit-rate | Gives each finding of done-gate, assertion-guard, self-audit and zukan a later verdict from what the session did next, keeps each rule's precision across sessions, and names the rules loopback stops feeding; /hit-rate; off by default |
token-lens | Checks an element's actual colours, spacing and type against the project's design tokens and lists off-token values with the nearest token; /token-lens <selector> |
kachi | When a check you broke turns green after a real fix, the band above the prompt sweeps green once with a short click, and the result row keeps the score: how many tries, how long it stayed red. Silent the rest of the time, but for one dim line under a check's first red |
cross-check | A second opinion from Codex in one press: the band above the prompt reviews the current diff with codex exec in its read-only sandbox, shows the top finding and the count, and puts the findings into the prompt for Claude to fix when asked; /codex lists them |
ci-rehearsal | CI before the push, in one press: the band above the prompt runs the push workflows locally with runthrough, shows the failing job and step with the count, and puts the failures and their log tails into the prompt for Claude to fix when asked; /ci lists every job |
stack-dock | The repository's devrouter stack in one press: the band above the prompt says whether it is unset, stopped or up, starts it with devrouter up, shows each service's URL and health in the status line and /stack, and puts doctor's findings and the failing logs into the prompt for Claude to fix when asked |
At the prompt of a terminal session:
/plugin install <mod> --marketplace simota/claude-mods
From a shell:
claude plugin install <mod> --marketplace simota/claude-mods
This repository is private: installing needs read access on GitHub and a git credential for github.com on the machine (an SSH key, or gh auth login then gh auth setup-git).
Options are set with /plugin configure <mod>@simota-mods in a session, or from a shell:
echo '{"enabled":"true"}' | claude plugin configure <mod>@simota-mods --values-stdin
A change made with /plugin configure reloads the mod; one made from a shell applies after a restart. Bands above the prompt stack: each mod draws its row above what the others draw.
/agent-pane opens the pane: running subagents first with elapsed time, then finished ones with ✓/✗ and duration; a background run that was stopped shows ■ 停止. A background run that left the roster without a result shows ? 結果不明; a teammate or remote launch shows ↗ 起動済み(追跡外).agents: N running while any run.Works on its own, no command:
ls build, npm ci are not checks), and only when its exit status is the command's: the check is last, or only && follows it (npm test | tail does not count).--no-verify (or a prefix of it from --no-ver), and git commit -n / -nm, is denied, also inside subshells, $(…), backticks, bash -c "…", eval and wrappers such as sudo/timeout. The value of an option (-m "…"), a comment or a heredoc never triggers it. So is a git command that moves its hooks for the run (-c core.hooksPath=…, --config-env core.hooksPath=…) or carries a hook manager's off switch in its environment (HUSKY=0, LEFTHOOK=0, pre-commit's SKIP=…), or moves the hooks through config in its environment (GIT_CONFIG_KEY_n=core.hooksPath, GIT_CONFIG_PARAMETERS). ANSI-C quoting ($'--no-\x76erify'), env -S "…", bash -c -- '…' and a shell reading its script from stdin (bash <<< '…', a heredoc, echo '…' | sh) are read through. It is a best-effort guard: git aliases (git ci -n), a hook path written into config beforehand and an environment exported by an earlier command are not detected./sandbox-report lists the sandbox denials seen in Bash output, for this session and all time: denied hosts and paths, counts, last seen, an example command, and which setting would allow each./sandbox-report reset clears the record.127.0.0.1:3000), since an entry without a port opens every port.<sandbox_violations> block, and Operation not permitted lines a program printed about itself, are read. For a command that succeeded or was interrupted, the block is taken from where the engine puts it, apart from the command's own output, so one inside a shown file or page is ignored even when it ends the output. A failed command keeps only its error text: the block that ends it (before an agent-proxy note) is read, and there a block the command printed itself cannot be told from the harness's. Credentials in the example command (tokens, passwords, Authorization/Cookie and other credential headers such as X-API-Key, URL userinfo, keys in env assignments including run-together names such as PGPASSWORD, known key shapes) are masked. Each section shows the top 10; when the record is full (200), the least recently seen entry gives way.#TODO(agent): <action> (after an optional quote or list bullet) in Claude's main-loop replies are collected per project (repo root or cwd). A mention inside a sentence, a table or inline code is not a TODO; subagent replies are ignored./todos opens the pane of this project's open items, each with a 完了 button./todos all lists every project's open items as text, marked as stored data.TODO(agent): N while the project has open items.Finished tool calls are drawn as one compact line with a Nerd Font icon: Edit/Write path +A −D, Read with line count, Bash (red on error), Agent, web and MCP calls. The result block under a compacted row is hidden, so a call is one line; an errored result stays. A row another mod decorated (an image-preview thumbnail) is left as it is, result included. Runs Claude Code folds into one count line (Read 3 files, ran 2 shell commands) stay folded. Terminal only.
| Option | Default | |
|---|---|---|
compact | true | Off leaves every row and result as Claude Code draws them |
/images opens a pane, newest first; h/l step through them.sips after the tool result has gone back, so tool calls never wait on it. Converted files live in a private cache ($TMPDIR or ~/.cache), newest 50 kept. A killed session's folder is removed by a later session's start once a day untouched; a running session touches its own every hour (again after a plugin reload), so it is kept while idle, though not across a day the machine sleeps./tmp/a b/x.jpg) joins at most 8 preceding pieces and 4096 characters; the first 64 paths named are read, and of those the first 4 that exist are shown.| Option | Default | |
|---|---|---|
inline | true | Thumbnail under the tool row |
maxRows | 12 | Rows a thumbnail may take, 1 to 60 |
After each reply of at least minChars characters, one tool-less fork of the conversation (served mostly from the prompt cache), given the reply itself as quoted data, checks it against the CLAUDE.md rules: claims done without evidence, first line not the result, unverified assertions, bypassed checks, scope inflation. Only violations of the five rules whose quote is found in the reply are kept (a made-up quote or rule is dropped); the quote is compared past markdown marks, bullets, curly quotes, case, spacing and a closing full stop, and one shortened with … is found piece by piece. Violations show in red above the prompt, in one row (the first and how many); 詳細 or /self-audit opens the pane with quotes and the fork's token use. Results belong to the latest reply only: when it was not audited, the pane says why.
| Option | Default | |
|---|---|---|
enabled | true | |
minChars | 200 | Shorter replies are not audited |
Cost: one extra request per turn on the session's model, plus the reply text (up to 12,000 characters) as uncached input; a cold cache (after 5 minutes idle or a model switch) resends the whole conversation.
type ‹7文字›, counted up to 10,000), since the field may be a password; a URL's secrets (token parameters, userinfo, key-shaped parts) are masked./cam toggles the pane; in a fullscreen terminal it opens by itself once per session, on the first browser call. Screenshots are decoded only while the pane is open, and written to a private per-session folder that is removed at session end. A killed session's folder is removed by a later session's start once a day untouched; a running session touches its own every hour (again after a plugin reload), so it is kept while idle, though not across a day the machine sleeps.| Option | Default | |
|---|---|---|
autoOpen | true | Open on the first browser call (fullscreen terminal) |
On by default (enabled: false turns it off). A typed prompt that looks ambiguous (no done-condition and an unclear target, or only evaluative words like いい感じ) is held back, and a band shows what is missing with up to three guesses at what it meant (judged along the lines of the clarify skill: the likeliest reading first, each a different deliverable with a checkable done-condition):
a / b / d: a guess goes into the prompt to edit and send (not held again)s: このまま送る sends it unchangede: 補足して送る puts it back with 完了条件: to fill in (not held again)q: 閉じる puts it back in the promptTyping another prompt instead sends that one and puts the held text back into the prompt. The held text is never lost: when a send fails or is dropped beneath, or putting words back fails, it stays held with its band (unless another prompt was held since) and its words are shown in a toast; a prompt still held at /clear goes straight back into the box, and one held when the session quits comes back at this project's next interactive session start. Words go into an empty box as they are, and are appended after a draft typed meanwhile on a line of their own, never over it.
Slash commands, prompts under 12 or over 1500 characters, prompts with any attachment or an @ mention, prompts sent by a plugin, and prompts typed while a turn runs are not judged. A timeout or error sends the prompt unchanged; the same text is not held twice (within the last 50 judged). Sending can wait up to timeoutMs.
| Option | Default | |
|---|---|---|
enabled | true | |
model | claude-haiku-5-5 | Judging model (alias or id) |
timeoutMs | 3000 | 500 to 3000 |
Off by default. When on, the new findings of the detector mods are attached to the next prompt typed at an idle prompt, as context only the model reads, so the correction does not wait for the person to retype it:
self-audit: the violations of the latest audited replydone-gate: edits with no passing check after them (again after a check passed and new edits were left unverified; 閉じる on its band takes the flag down, and nothing is fed)sandbox-lens: denials seen this session, each onceEach finding goes back once per session, marked as data that may be wrong for Claude to check before acting. A toast says how many went back and from where. Slash commands, hidden prompts, prompts sent by a plugin and prompts typed while a turn runs carry nothing. A detector that is not installed contributes nothing.
With hit-rate on, the rules it muted are not fed (sandbox-lens denials never are muted).
/loopback shows what was fed last and the self-audit repeat rate: of the rules fed back, how many self-audit flagged again on the next audited reply (all sessions). The rate is what the design is judged by (.genius/decisions/loopback.md). It also names the rules hit-rate muted.| Option | Default | |
|---|---|---|
enabled | false |
Cost: the findings ride as extra input on the prompt they are attached to (each quote clipped to 300 characters, at most 12 findings).
An error book, kept across sessions and repos. When a Bash command fails, the error line is caught and numbered:
📕 新種のエラー発見! No.042「…」 — a kind not seen before📙 No.017 再会(3回目・未解決) — seen before, nothing known to get past it 📗 既知 No.017(3回目)— 前回: sandbox 外で git push origin main ` — seen before with a fix: Claude also reads, beside the tool's result, where it was seen and what got past it (marked as a past record to check, not an instruction)A fix is learned when the same program and subcommand (git push, pnpm install; read past a leading cd, export or source, so cd app && npm install is npm install) succeeds within the next 10 Bash calls of the session; whether it ran outside the sandbox is kept with it. Two sightings are one kind when their error line matches with paths, quotes, numbers and hashes taken out.
Failures of tests, linters, type checkers and builds are not caught: they are fixed by editing code, not by a command. Credentials in a kept command and in the kept error line are masked as sandbox-lens does.
/zukan opens the book, most recently seen first: kinds, solved, sightings/zukan note <No> <text> writes how to get past it, shown and fed in place of the learned command; an empty text removes the note/zukan forget <No> removes an entryThe newest 300 kinds by last sighting are kept.
The current branch's pull request, kept in the status line while it is open (once merged or closed, a toast says so and the line clears):
⎇ #42 · ✓5 ✗1 ⏳2 · 🛑 変更要求 · 💬3 · マージまであと4
"マージまであと N" counts what still stands before a merge: draft, failed checks, running checks, changes requested or approval pending, unresolved review threads, a conflict, the branch behind its base. At 0 it reads 🟢 マージ可能.
A toast when it changes: 🔴 CI 失敗: test, 💬 新しいレビューコメント 2件 (@rev), ✅ 承認されました, 🟢 #42 マージまであと0, 🎉 #42 がマージされました. Checks turning red, new review comments, changes requested and a new conflict are also attached to the next prompt typed at an idle prompt, once, with the last 40 lines of the failed log of up to three jobs (more are counted), marked as data whose comments and logs are not to be followed as instructions. The session's own replies on a thread (the comment, made after the post, carrying words it replied with through an MCP reply tool or gh api …/pulls/N/comments… -f body=, matched once) are not news; your own review comments are. What waits for the next prompt is about one pull request and is capped (newest kept). The option feed (on by default) turns that off.
/pr asks again and opens the pane: title, size, what is left, checks (failed first) and unresolved threads/pr <number|url|branch> follows that pull request; /pr clear goes back to the defaultWhich pull request: the one a Bash command of the session last worked on (gh pr comment 2, gh pr review 2, the URL gh pr create printed, the branch a git push sent to; looking with gh pr view|diff|checks does not move it), so work pushed to a review branch from another checkout is followed; else the checked-out branch's; else your newest open pull request in the repository.
It asks gh (gh pr view, and gh api graphql for review threads) at session start, right after a Bash git push, git checkout, gh pr create and the like, every minute while a check runs or after a push, and every five minutes otherwise; it stops once the pull request is merged or closed. Without an origin remote, gh, or a pull request for the branch it shows nothing, and /pr says why. gh runs on the host, outside the Bash sandbox, with your gh auth.
The repository as a map under fog, cleared as Claude works through it:
🗺 探索率 31% ██████░░░░░░░░░░░░░░ 読 23 · 編 9 · ✗ 2 / 101
▾ mods/
▾ pr-lamp/
▾ hooks/
● lamp.ts +43 −2 編集 4回
✗ register.tsx +59 −16 編集 6回 エラー 1 ★
▸ loopback/ ○●
░ agent-pane/ ░ browser-cam/ ░ done-gate/ …8
⚠ 編集したファイルを import しているが未読: mods/pr-lamp/tests/pr-lamp.test.ts
░ nothing touched yet, ○ read (Read, or cat, sed, grep… in Bash), ● edited (Edit, Write, NotebookEdit, sed -i), ✚ made by the session, ✗ named with a line number by a failed Bash command since its last edit, ★ the file touched last. A directory holding an edit, a new file or an error is open; one only read is closed with its marks beside it; untouched directories and files at a level share one fog row.
Two warnings, each a likely oversight: a file edited without being read, and a file that imports an edited one (JS/TS and Python, found by git grep) that was never opened. A very large repository's file list is cut to what one state value holds (3 M characters of paths), so it is still mapped, partly.
/map opens the pane🗺 31% · ●9 · ✗2 · ⚠1 only while there is an error or a warning, and clears otherwise🗺 新しい区域を開拓: mods/zukan/)The map is the session's, subagents' calls included; files outside the repository are not mapped. Explored is touched files over git ls-files, read again after a checkout, pull, mv or rm. Outside a git repository only the edit count is shown. A failed command's output is read once, in time linear in its length, before its result goes back.
On each Edit, Write or MultiEdit it diffs the whole file before and after the call, so an assertion moved within the file is no removal, and one only reformatted (spaces around punctuation, a closing ; or ,, and '…' for "…" in languages that read them alike) is no rewrite; a change inside a string still is. In test files (by name, or a Rust file with a test module anywhere in it) it flags assertions removed or commented out, a strict matcher turned weak (toEqual → toBeDefined, assertEqual → assertTrue, toThrow(X) → toThrow()), an assertion now about a literal (expect(true).toBe(true)), the same assertion now expecting another value or the opposite (toBe → not.toBe), and tests skipped or focused (it.skip, @pytest.mark.skip, #[ignore], t.Skip). In any file but prose (.md, .txt, .rst, .adoc) it flags errors newly swallowed (catch {}, .catch(() => undefined), except: pass, || true); one named in a comment (// or || true, a doc block, /* … */, # …) is not.
Findings ride beside the edit's re
hooks/register.tsx 130 lines1import { atom, derive, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { NegativeTrigger, TestDigest } from '../types'
5import { candidatesOf, digestOf, isTestPath, KIND_LABEL, keyOf, requestOf, summaryOf, triggersOf, withTest } from './space'
6
7const triggers = atom({ plugin: 'negative-space', key: 'triggers' } as const, [] as NegativeTrigger[])
8const tests = atom({ plugin: 'negative-space', key: 'tests' } as const, {} as Record<string, TestDigest>)
9const dismissed = atom({ plugin: 'negative-space', key: 'dismissed' } as const, [] as string[])
10const isShown = atom({ plugin: 'negative-space', key: 'isShown' } as const, false)
11
12const KEEP = 200
13
14type Edit = { path: string; before: string; after: string }
15
16function editsOf(tool: string, input: Record<string, unknown>, written: string | undefined): Edit[] {
17 const path = typeof input.file_path === 'string' ? input.file_path : undefined
18 if (path === undefined) return []
19 if (tool === 'Edit') return [{ path, before: String(input.old_string ?? ''), after: String(input.new_string ?? '') }]
20 if (tool === 'MultiEdit' && Array.isArray(input.edits)) {
21 return (input.edits as Record<string, unknown>[]).map(one => ({ path, before: String(one.old_string ?? ''), after: String(one.new_string ?? '') }))
22 }
23 if (tool === 'Write') return [{ path, before: written ?? '', after: String(input.content ?? '') }]
24 return []
25}
26
27// Counted again only when a trigger, a test or a dismissal changed: the band reads it at every draw.
28const candidates = derive([triggers, tests, dismissed], candidatesOf)
29const open = ($: EngineInterface) => read($, candidates)
30
31export const register: Register = on => {
32 on('session.start', async ($, e, next) => {
33 await $.command.register({ name: 'negative-space', description: '認可・入力検証・エラー処理の追加に対し、拒否ケースや境界値のテスト不足候補を一覧' })
34 return next(e)
35 })
36
37 on('tool.call', async ($, e, next) => {
38 const tool = String(e.tool)
39 if (tool !== 'Edit' && tool !== 'Write' && tool !== 'MultiEdit') return next(e)
40 const input = e as unknown as Record<string, unknown>
41 const path = typeof input.file_path === 'string' ? input.file_path : undefined
42 if (path === undefined) return next(e)
43 // The whole file before and after, so a trigger knows the function it sits in.
44 const before = await $.fs.read(path).then(String).catch(() => undefined)
45
46 const ran = await next(e)
47 if (ran.deny !== undefined || ran.isError === true) return ran
48
49 const after = await $.fs.read(path).then(String).catch(() => undefined)
50 const at = await $.clock.now()
51 for (const one of after !== undefined ? [{ path, before: before ?? '', after }] : editsOf(tool, input, before)) {
52 if (isTestPath(one.path)) {
53 // What the test says now: the file as it stands, or an Edit's new text added to what was seen.
54 const known = await read($, triggers)
55 const isWhole = after !== undefined || tool === 'Write'
56 await update($, tests, all => withTest(all, one.path, digestOf(one.after), isWhole, known))
57 continue
58 }
59 const found = triggersOf(one.path, one.before, one.after, at)
60 if (found.length === 0) continue
61 await update($, triggers, list => {
62 const fresh = found.filter(f => !list.some(old => keyOf(old) === keyOf(f)))
63 return [...list, ...fresh].slice(-KEEP)
64 })
65 }
66 return ran
67 }).catch(($, e, next) => next(e)) // an observer: a failure here never changes the call
68
69 // A test Claude reads counts too: what it already covers is not asked for again.
70 on('tool.call', { tool: 'Read' }, async ($, e, next) => {
71 const ran = await next(e)
72 if (ran.deny === undefined && ran.isError !== true && isTestPath(e.file_path)) {
73 // A read of the whole file says what it is now; one of a part adds to what was seen.
74 const isWhole = e.offset === undefined && e.limit === undefined
75 const known = await read($, triggers)
76 const digest = digestOf(ran.text ?? '')
77 await update($, tests, all => withTest(all, e.file_path, digest, isWhole, known))
78 }
79 return ran
80 }).catch(($, e, next) => next(e))
81
82 on('turn.complete', async ($, e, next) => {
83 if (e.agentId === undefined && (await open($)).length > 0) await update($, isShown, () => true)
84 return next(e)
85 })
86
87 on('command.run', { command: 'negative-space' }, async $ => {
88 const list = await open($)
89 const all = await read($, triggers)
90 if (all.length === 0) return { text: '🕳 このセッションの編集に、認可・入力検証・エラー処理の追加は見つかっていません。' }
91 if (list.length === 0) return { text: `🕳 契機 ${all.length}件。テスト不足の候補はありません(このセッションで触れたテストが拒否・境界の場合に触れています)。` }
92 return {
93 text: [
94 `🕳 テスト不足の候補 ${list.length}件(契機 ${all.length}件・自動推定のため見当違いもあります)`,
95 ...list.map(one => `- ${one.path}: ${KIND_LABEL[one.kind]} — ${one.ask}\n 契機: ${one.line}`),
96 ].join('\n'),
97 }
98 })
99
100 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
101 if (e.props.hasSurvey || !(await read($, isShown))) return next(e)
102 const list = await open($)
103 if (list.length === 0) return next(e)
104
105 const { Box, Button, Text } = $.ui.resolve(e)
106 const below = await next(e)
107 return (
108 <Box flexDirection="column">
109 <Box>
110 <Text color="magenta" wrap="truncate-end">{`🕳 拒否/境界のテスト不足候補 ${list.length}件: ${summaryOf(list)} `}</Text>
111 <Button key="ask" label="Claude に頼む" onPress={() => $.prompt.fill({ text: requestOf(list), mode: 'insert' })} />
112 <Button
113 key="dismiss"
114 label="不要"
115 role="dismiss"
116 onPress={async () => {
117 // What was drawn and is still open: one closed since is not dismissed, one come since not unseen.
118 const still = new Set((await open($)).map(one => one.key))
119 const drawn = list.map(one => one.key).filter(key => still.has(key))
120 await update($, dismissed, keys => [...new Set([...keys, ...drawn])])
121 await update($, isShown, () => false)
122 }}
123 />
124 </Box>
125 {below}
126 </Box>
127 )
128 })
129}
130hooks/space.ts 291 lines1// The negative space, pure: what an edit added that refuses, validates or fails, and which
2// of the tests it calls for no test this session touched has written yet.
3
4import type { NegativeTrigger, TestDigest } from '../types'
5
6const TEST_PATH = /(?:^|\/)(?:tests?|__tests__|spec|specs)\/|\.(?:test|spec)\.[cm]?[jt]sx?$|_test\.(?:go|py|rb|exs?)$|(?:^|\/)test_[^/]+\.py$|_spec\.rb$|Tests?\.(?:swift|kt|java|cs)$/
7const SOURCE = /\.(?:[cm]?[jt]sx?|py|rb|go|rs|swift|kt|java|cs|php|ex|exs|scala)$/
8
9export const isTestPath = (path: string): boolean => TEST_PATH.test(path)
10export const isSourcePath = (path: string): boolean => SOURCE.test(path) && !isTestPath(path)
11
12const PATTERNS: Record<NegativeTrigger['kind'], RegExp> = {
13 auth: /\b(?:authori[sz]e\w*|authenticate\w*|isAuthenticated|requireAuth\w*|require_?login|login_required|permission\w*|[a-z]\w*Permissions?|permitted|can\?|cannot\?|forbid\w*|Forbidden\w*|Unauthori[sz]ed\w*|isAdmin|is_admin|admin_required|ownerId|owner_id|currentUser|current_user|session\.user|policy|@PreAuthorize|@Secured|@RolesAllowed)\b|\b(?:401|403)\b/,
14 validation:
15 /\b(?:validat\w*|isValid|is_valid|sanitize\w*|BadRequest\w*|ValueError|InvalidArgument\w*|ArgumentError|RangeError|ValidationError|@Valid|@NotNull|@Size|@Min|@Max|Joi\.|yup\.|z\.(?:object|string|number|array|enum|union)|field_validator|validator)\b|\b(?:400|422)\b|(?<!\bMath)\.(?:min|max|length|regex|email|url|uuid|positive|nonnegative|int|nonempty)\(|\bif\b[^\n]{0,200}?(?:<=?|(?<!=)>=?)\s*-?\d|\b(?:maxLength|minLength|maximum|minimum|max_length|min_length)\s*[:=]/,
16 error:
17 /\b(?:catch|except|rescue|recover|throw|raise|panic!|reject|onError|on_error|fallback|retry|retries|timeout|ErrorBoundary)\b|\bErr\(|\breturn\s+(?:nil,\s*)?(?:err|fmt\.Errorf|errors\.New)\b/,
18}
19
20/** What a test of that kind says when it tries the refusal, the bad input or the failure. */
21const COVERS: Record<NegativeTrigger['kind'], RegExp> = {
22 auth: /\b(?:401|403|forbidden|unauthori[sz]ed|denied|deny|not allowed|permission|anonymous|guest|other user|another user|non-?admin|without (?:a )?(?:token|login|session)|logged out)\b|拒否|権限/i,
23 validation: /\b(?:invalid|rejects?|throws?|toThrow|raises|assertRaises|pytest\.raises|400|422|empty|blank|too (?:long|short|large|small)|negative|out of range|malformed|boundary)\b|不正|境界|空/i,
24 error: /\b(?:throws?|toThrow|rejects?|raises|assertRaises|pytest\.raises|fails?|failure|failing|timeout|times out|retry|Err\b|should_panic|mockRejected\w*|unavailable|500|503)\b|失敗|エラー/i,
25}
26
27export const KIND_LABEL: Record<NegativeTrigger['kind'], string> = { auth: '認可', validation: '入力検証', error: 'エラー処理' }
28
29const QUESTION: Record<NegativeTrigger['kind'], string> = {
30 auth: '権限のない/未ログイン/他人のリソースで拒否されるか',
31 validation: '不正・空・型違いの入力で拒否されるか',
32 error: '失敗(例外・タイムアウト・依存先エラー)時にどう振る舞うか',
33}
34
35const MAX_LINE = 2_000
36const clip = (text: string, max = 100) => (text.length > max ? `${text.slice(0, max - 1)}…` : text)
37
38/** Lines of `after` not matched by an equal line of `before`, trimmed, in order, each with where it stands in `after`. */
39export function addedAt(before: string, after: string): { line: string; index: number }[] {
40 const left = new Map<string, number>()
41 for (const line of before.split('\n')) left.set(line.trim(), (left.get(line.trim()) ?? 0) + 1)
42 const added: { line: string; index: number }[] = []
43 after.split('\n').forEach((raw, index) => {
44 const line = raw.trim()
45 const n = left.get(line) ?? 0
46 if (n > 0) left.set(line, n - 1)
47 else if (line !== '') added.push({ line, index })
48 })
49 return added
50}
51
52/** Lines of `after` not matched by an equal line of `before`, trimmed, in order. */
53export const addedLines = (before: string, after: string): string[] => addedAt(before, after).map(one => one.line)
54
55// A string or a regex literal is text the code holds, not a check it makes: `/permission denied/`
56// names no authorization. Each alternative takes characters the others cannot, so a line is read once.
57const LITERAL = /'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`|((?:^|[=(,:[!&|?{};]|\breturn)\s*)\/(?![/*])(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\n[])+\/[a-z]*/g
58
59/** The line with every string's and regex literal's contents taken out, its code kept. */
60export const codeOf = (line: string): string => line.replace(LITERAL, (whole, before: string | undefined) => (before === undefined ? whole[0] + whole[0] : `${before}//`))
61
62const isComment = (line: string) => /^(?:\/\/|\/\*|\*|#(?!\[)|--)/.test(line)
63const isImport = (line: string) => /^(?:import\b|from\s+\S+\s+import\b|use\s|require\(|#include|using\s)/.test(line)
64
65/** Numbers a line bounds by: `x > 100`, `.max(255)`, `maxLength: 20`; HTTP statuses left out. */
66export function boundsOf(line: string): number[] {
67 const found = new Set<number>()
68 const pick = (text: string | undefined) => {
69 if (text === undefined) return
70 const n = Number(text)
71 if (Number.isFinite(n) && !(n >= 400 && n < 600 && Number.isInteger(n))) found.add(n)
72 }
73 // `=>` is an arrow, not a comparison.
74 for (const m of line.matchAll(/(?:<=?|(?<!=)>=?|===?|!==?)\s*(-?\d+(?:\.\d+)?)\b/g)) pick(m[1])
75 for (const m of line.matchAll(/\b(-?\d+(?:\.\d+)?)\s*(?:<=?|>=?)(?!>)/g)) pick(m[1])
76 // `Math.max(0, x)` clamps a value; it bounds no input.
77 for (const m of line.matchAll(/(?<!\bMath)\.(?:min|max|length|gte?|lte?|size)\(\s*(-?\d+(?:\.\d+)?)/g)) pick(m[1])
78 for (const m of line.matchAll(/\b(?:maxLength|minLength|maximum|minimum|max_length|min_length|max|min)\s*[:=]\s*(-?\d+(?:\.\d+)?)/g)) pick(m[1])
79 return [...found]
80}
81
82const DECLARATION =
83 /(?:\bfunction\s*\*?\s*([A-Za-z_$][\w$]*)|\b(?:def|fn)\s+([A-Za-z_]\w*)|\bfunc\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)|\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)|^\s*(?:(?:public|private|protected|static|async|override)\s+)*([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::[^{]+)?\{)/
84const STOP = new Set(
85 'if else for while switch case return throw await async const let var new this self super true false null nil none undefined typeof instanceof catch try except raise rescue finally function def class import from export default value values result results error errors err req res request response status data body item items length string number boolean object array console log ok some none'.split(
86 ' ',
87 ),
88)
89
90/** The function enclosing a line of a file: the nearest declaration above it. */
91export function enclosingName(lines: readonly string[], index: number): string | undefined {
92 for (let i = index; i >= 0 && i > index - 200; i -= 1) {
93 const line = lines[i] ?? ''
94 // A minified line declares nothing worth naming, and its length would make DECLARATION slow.
95 if (line.length > MAX_LINE) continue
96 const m = line.match(DECLARATION)
97 const name = m?.slice(1).find(Boolean)
98 if (name !== undefined && !STOP.has(name.toLowerCase())) return name
99 }
100 return undefined
101}
102
103/** Names worth finding in a test of this line: identifiers of four letters or more, common words left out. */
104export function namesOn(line: string): string[] {
105 // A string's text: an escape, or any one character but a backslash, never a backslash both
106 // ways (a run of them would split exponentially), and a lone one may stand before the close.
107 const found = (line.replace(/(['"`])(?:\\.|(?!\1)[^\\])*\\?\1/g, ' ').match(/[A-Za-z_$][\w$]{3,}/g) ?? []).filter(word => !STOP.has(word.toLowerCase()))
108 return [...new Set(found)].slice(0, 5)
109}
110
111/** The triggers among the lines an edit added to a source file; `after` is the file (or the edit's text) after it. */
112export function triggersOf(path: string, before: string, after: string, at: number): NegativeTrigger[] {
113 if (!isSourcePath(path)) return []
114 const out: NegativeTrigger[] = []
115 const lines = after.split('\n')
116 for (const { line, index } of addedAt(before, after)) {
117 // A minified bundle's line is no code to test, and its length would make every pattern slow.
118 if (line.length > MAX_LINE || isComment(line) || isImport(line)) continue
119 const code = codeOf(line)
120 const kinds = (['auth', 'validation', 'error'] as const).filter(kind => PATTERNS[kind].test(code))
121 if (kinds.length === 0) continue
122 // The function this very line sits in, not the first other line that reads the same.
123 const enclosing = enclosingName(lines, index)
124 const names = [...new Set([...(enclosing === undefined ? [] : [enclosing]), ...namesOn(line)])]
125 for (const kind of kinds) out.push({ kind, path, line: clip(line), bounds: kind === 'validation' ? boundsOf(code) : [], names, at })
126 }
127 return out
128}
129
130export const keyOf = (one: Pick<NegativeTrigger, 'kind' | 'path' | 'line'>): string => `${one.kind}\u0000${one.path}\u0000${one.line}`
131
132const stemOf = (path: string) => {
133 const name = path.slice(path.lastIndexOf('/') + 1)
134 return name.replace(/\.[^.]+$/, '').replace(/(?:[._-](?:test|spec))$|^test_|_test$|Tests?$/i, '').toLowerCase()
135}
136
137const MAX_WORDS = 4_000
138const MAX_NUMBERS = 1_000
139
140/**
141 * What a test's text says, for the candidates: the kinds whose case it tries, its identifiers,
142 * its numbers. Read's line numbers (` 12\t…`) are taken off first: a line number is no bound tried.
143 */
144export function digestOf(text: string): TestDigest {
145 const body = text.replace(/^[ \t]*\d+\t/gm, '')
146 const covers = (['auth', 'validation', 'error'] as const).filter(kind => COVERS[kind].test(body))
147 // A name is no longer than this: a fixture's long run of letters is no name a trigger has.
148 const words = new Set((body.match(/[A-Za-z_$][\w$]*/g) ?? []).filter(word => word.length <= 64))
149 const numbers = new Set<string>()
150 for (const m of body.matchAll(/(?<![\w.])-?\d+(?:\.\d+)?(?![\w.])/g)) {
151 numbers.add(m[0])
152 if (m[0].startsWith('-')) numbers.add(m[0].slice(1))
153 }
154 return { covers, words: [...words].slice(0, MAX_WORDS), numbers: [...numbers].slice(0, MAX_NUMBERS) }
155}
156
157/** Two looks at one test file as one: a partial read adds to what a full one saw. */
158export function mergeDigest(a: TestDigest, b: TestDigest): TestDigest {
159 return {
160 covers: [...new Set([...a.covers, ...b.covers])],
161 words: [...new Set([...a.words, ...b.words])].slice(0, MAX_WORDS),
162 numbers: [...new Set([...a.numbers, ...b.numbers])].slice(0, MAX_NUMBERS),
163 }
164}
165
166// Held from an earlier version as text, a test is read as its digest.
167const asDigest = (value: TestDigest | string): TestDigest => (typeof value === 'string' ? digestOf(value) : value)
168
169/** What the tests that speak of a source file say together: the session's tests whose name holds its stem. */
170export function testsFor(path: string, tests: Readonly<Record<string, TestDigest | string>>): TestDigest {
171 const stem = stemOf(path)
172 const covers = new Set<NegativeTrigger['kind']>()
173 const words = new Set<string>()
174 const numbers = new Set<string>()
175 // Every matching file whole: a cap here would cut the newest test, the one just written to close it.
176 for (const [test, value] of Object.entries(tests)) {
177 if (stem === '' || !stemOf(test).includes(stem)) continue
178 const one = asDigest(value)
179 for (const kind of one.covers) covers.add(kind)
180 for (const word of one.words) words.add(word)
181 for (const n of one.numbers) numbers.add(n)
182 }
183 return { covers: [...covers], words: [...words], numbers: [...numbers] }
184}
185
186// Well under the 4 MiB the engine holds a state value to: past it every write would be refused.
187export const MAX_TESTS_CHARS = 1_500_000
188
189/**
190 * The tests with one file's digest put in (`isWhole`: the file as it stands, else added to what
191 * was seen), newest last. Past MAX_TESTS_CHARS the oldest leave, those no trigger's file is
192 * tested by first: a test that closed a candidate stays while reading others.
193 */
194export function withTest(
195 all: Readonly<Record<string, TestDigest>>,
196 path: string,
197 digest: TestDigest,
198 isWhole: boolean,
199 triggers: readonly Pick<NegativeTrigger, 'path'>[] = [],
200): Record<string, TestDigest> {
201 const { [path]: had, ...others } = all
202 const put = isWhole || had === undefined ? digest : mergeDigest(asDigest(had), digest)
203 const entries: [string, TestDigest][] = [...Object.entries(others), [path, put]]
204 const stems = [...new Set(triggers.map(one => stemOf(one.path)).filter(stem => stem !== ''))]
205 const isRelevant = (test: string) => stems.some(stem => stemOf(test).includes(stem))
206 let size = JSON.stringify(Object.fromEntries(entries)).length
207 // Among tests a trigger needs, the largest leave first: a small one closing a candidate costs little to keep.
208 const sizeOf = (one: TestDigest) => JSON.stringify(one).length
209 const relevant = entries.slice(0, -1).filter(([test]) => isRelevant(test)).sort(([, a], [, b]) => sizeOf(b) - sizeOf(a))
210 const order = [...entries.slice(0, -1).filter(([test]) => !isRelevant(test)), ...relevant]
211 const gone = new Set<string>()
212 for (const [test, one] of order) {
213 if (size <= MAX_TESTS_CHARS) break
214 gone.add(test)
215 size -= JSON.stringify(one).length + test.length + 6
216 }
217 return Object.fromEntries(entries.filter(([test]) => !gone.has(test)))
218}
219
220/** One test to write: what to try, and why (the trigger line). */
221export type Candidate = { key: string; kind: NegativeTrigger['kind']; path: string; line: string; ask: string }
222
223/**
224 * The candidates the session's tests leave open: per trigger, its kind's refusal or failure
225 * case unless a test of that file says one, and each bound N unless N is in a test there.
226 */
227export function candidatesOf(
228 triggers: readonly NegativeTrigger[],
229 tests: Readonly<Record<string, TestDigest | string>>,
230 dismissed: readonly string[],
231): Candidate[] {
232 const out: Candidate[] = []
233 const seen = new Set<string>()
234 const judged = new Set<string>()
235 const skip = new Set(dismissed)
236 const byPath = new Map<string, { digest: TestDigest; words: Set<string>; numbers: Set<string> }>()
237 const testsOf = (path: string) => {
238 let held = byPath.get(path)
239 if (held === undefined) {
240 const digest = testsFor(path, tests)
241 held = { digest, words: new Set(digest.words), numbers: new Set(digest.numbers) }
242 byPath.set(path, held)
243 }
244 return held
245 }
246 for (const one of triggers) {
247 const { digest, words, numbers } = testsOf(one.path)
248 const base = keyOf(one)
249 const add = (key: string, ask: string) => {
250 if (seen.has(key) || skip.has(key)) return
251 seen.add(key)
252 out.push({ key, kind: one.kind, path: one.path, line: one.line, ask })
253 }
254 // One question per file and kind: three validation lines in a file want the same test. It is
255 // covered by a test that tries the case and names what was changed (the function, a name on
256 // a trigger line), not by a stray word somewhere in a test file.
257 const kindKey = `${one.kind}\u0000${one.path}`
258 if (!judged.has(kindKey)) {
259 judged.add(kindKey)
260 const names = triggers.filter(t => t.kind === one.kind && t.path === one.path).flatMap(t => t.names ?? [])
261 const isNamed = names.length === 0 || names.some(name => words.has(name))
262 if (!digest.covers.includes(one.kind) || !isNamed) add(kindKey, QUESTION[one.kind])
263 }
264 for (const n of one.bounds) {
265 // A decimal bound's neighbours as it is written: 1.1 asks for 0.1 and 2.1, never 0.10000000000000009.
266 const places = (String(n).split('.')[1] ?? '').length
267 const [below, above] = [n - 1, n + 1].map(v => Number(v.toFixed(places)))
268 const tried = [below, n, above].filter(v => numbers.has(String(v)))
269 if (tried.length < 2) add(`${base}\u0000${n}`, `境界値 ${below} / ${n} / ${above}`)
270 }
271 }
272 return out
273}
274
275export function summaryOf(list: readonly Candidate[]): string {
276 const files = [...new Set(list.map(one => one.path.slice(one.path.lastIndexOf('/') + 1)))]
277 const kinds = [...new Set(list.map(one => KIND_LABEL[one.kind]))]
278 return `${kinds.join('・')} (${files.slice(0, 3).join(', ')}${files.length > 3 ? ` ほか${files.length - 3}` : ''})`
279}
280
281const quoted = (line: string) => line.replace(/[\u0000-\u001F\u007F-\u009F\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g, '').replace(/`/g, "'")
282
283/** The request the band puts in the prompt: the candidates as a list for Claude to check. */
284export function requestOf(list: readonly Candidate[]): string {
285 return [
286 '次の拒否ケース・境界値のテストが不足している可能性があります。既存テストで足りているものは理由を、足りないものは追加してください:',
287 // The trigger line is source text quoted as data: controls and bidi marks out, backticks made plain.
288 ...list.map(one => `- ${one.path}: ${KIND_LABEL[one.kind]} — ${one.ask}(契機: \`${quoted(one.line)}\`)`),
289 ].join('\n')
290}
291types/index.d.ts 40 lines1/** Code an edit added that calls for a test of what it refuses or where it breaks. */
2export type NegativeTrigger = {
3 /** auth: who may do it; validation: what input is taken; error: what happens when it fails. */
4 kind: 'auth' | 'validation' | 'error'
5 /** The source file, as the tool named it. */
6 path: string
7 /** The added line that triggered it, clipped. */
8 line: string
9 /** Numbers the line compares against or bounds by: each wants N-1, N and N+1 tried. */
10 bounds: number[]
11 /** What a test of it would name: the function the line sits in, and the names on the line. */
12 names: string[]
13 at: number
14}
15
16/** What a test file says, as far as the candidates ask: which cases it tries, its names and numbers. */
17export type TestDigest = {
18 /** The kinds whose refusal or failure case the file tries (`403`, `invalid`, `toThrow`…). */
19 covers: NegativeTrigger['kind'][]
20 /** The identifiers in it, each once. */
21 words: string[]
22 /** The numbers in it, each once (a negative one also without its sign). */
23 numbers: string[]
24}
25
26declare module 'claude-code' {
27 interface PluginState {
28 'negative-space': {
29 /** Triggers from this session's edits, newest last, one per path, kind and line. */
30 triggers: NegativeTrigger[]
31 /** Test file path to what it says, as this session's edits and reads have shown it. */
32 tests: Record<string, TestDigest>
33 /** Keys of candidates the person dismissed. */
34 dismissed: string[]
35 /** Whether the band is up: set when a turn ends with open candidates. */
36 isShown: boolean
37 }
38 }
39}
40