SLOPSHOPPER

perf-delta

/perf runs a benchmark command several times and compares it with its baseline (saved earlier, or a git ref run in a temporary worktree): median wall time…

newpanecommandtoaststatusprocess
★ 1v0.1.1MITupdated 2026-10-16simota/claude-mods/mods/perf-delta
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · perf-delta
│ ┃ perf-delta ✕ › fix the failing auth test and add an audit log call │ ┃ まだ計測していません。 │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /perf │ ⎿ perf-delta: ⏱ まだ計測していません。/perf <コマンド> で計測します。 │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · perf-delta
まだ計測していません。
README

claude-mods

English | 日本語

Personal Claude Code mods (function-hook plugins), published as one marketplace.

ModWhat it does
agent-paneLive pane of the session's subagents: running ones with elapsed time, finished ones with result and duration
done-gateFlags unverified edits, stops repeated failing commands, and blocks git --no-verify
sandbox-lensTallies sandbox denials seen in Bash output and reports them with /sandbox-report
skill-hintSuggests up to three matching skills above the prompt from what was typed; never invokes them.
todo-agentCollects #TODO(agent) follow-ups from Claude's replies into a per-project list with a /todos pane.
context-meterBand above the prompt with a Gruvbox sparkline of context use per turn, plus tokens and cost
tool-rowRedraws finished tool-call rows in the terminal as one compact line with a Nerd Font icon, Gruvbox colors and a short stat
image-previewThumbnails of the images a session writes, reads or generates: under the tool's row in the terminal, and in an /images pane
self-auditAfter 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
context-dietTrims the skill listing to what the project kind needs (off by default); /context-diet shows what was dropped and the tokens saved
browser-camLive pane of the browser Claude drives: the latest screenshot from Claude in Chrome, the page URL and the recent actions
prompt-coachHolds 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
loopbackFeeds 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
zukanError 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-lampThe 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-mapExploration 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-guardCatches 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-spaceWhen 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
handoff-capsuleBefore a compaction and at session end, keeps the goal, decisions, open items, commands to reproduce and files touched; the next session picks which parts to bring back
port-lanternThe dev servers the session started: URL, port, whether each still listens, and their latest log lines, in the status line and /ports
artifact-shelfA 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
focus-hudOne status line: goal, target, what is running and for how long, and what the session waits on; /focus
side-effect-ledgerA 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
trust-labelLabels external text (web, issues, logs, browser pages, services) with its source beside the result and flags candidate injected instructions; a heuristic, never a safety verdict; /trust
visual-diffCompares 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-traceRecords 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-rateGives 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-lensChecks 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>

Install

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).

Usage

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

  • /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 ↗ 起動済み(追跡外).
  • In a fullscreen terminal the pane opens by itself once per session, on the first Agent call (a reload does not reopen it).
  • The status line shows agents: N running while any run.

done-gate

Works on its own, no command:

  • A turn that edited files without a passing test, lint, typecheck or build afterwards leaves a band: 未検証の変更があります. It stays until a check succeeds or 閉じる is pressed. Only the program a command runs counts (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).
  • The second identical failure of the same Bash command tells Claude to stop retrying and diagnose the root cause (again after the command has succeeded in between).
  • Any git command with --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-lens

  • /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.
  • Hints only: it never changes sandbox settings. A loopback or private address keeps its port in the hint (127.0.0.1:3000), since an entry without a port opens every port.
  • A <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.

skill-hint

After a prompt is sent, up to three skills matching it show above the prompt (💡 skill候補: /coding-debug …), only ones that exist in the session. Nothing is invoked; 閉じる or the next prompt (a slash command included) clears it. A prompt that already names a skill (/name anywhere, or a hyphenated skill name such as coding-debug) gets no hint; built-in commands such as /clear and path segments such as src/review/ do not count as naming one. Plugin skills (plugin:name) are suggested by their full name.

todo-agent

  • Lines starting with #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.
  • The status line shows TODO(agent): N while the project has open items.

context-meter

A band with a sparkline of context use per turn and ctx 63% ▲4 · 126k · turn in 120k / out 8k · $1.23: the context size of the last request, then the whole turn's input/output (shown when the turn reported usage). The percentage turns yellow from 50% and red from 80%.

OptionDefault
bandtrueDraw the band (samples are recorded either way)

tool-row

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.

OptionDefault
compacttrueOff leaves every row and result as Claude Code draws them

image-preview

  • Images a session writes, reads, or that a Bash command produces (png, jpg, jpeg, webp, gif) get a thumbnail under that tool's row in the terminal (kitty graphics: Ghostty, kitty).
  • /images opens a pane, newest first; h/l step through them.
  • Non-PNG files are converted with macOS 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.
  • A Bash command and its output are searched for image paths in time linear in their length, before the result goes back. A path split at spaces (/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.
OptionDefault
inlinetrueThumbnail under the tool row
maxRows12Rows a thumbnail may take, 1 to 60

self-audit

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; 詳細 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.

OptionDefault
enabledtrue
minChars200Shorter 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.

context-diet

Off by default. When on, the skill listing is trimmed to what the project kind needs (Swift, Android, Rust, web, Python, Go, detected from the repo root and one level below). Coding, quality, planning and research skills are always kept; red-team, dynamic-*, persona and operation skills are dropped; image, design, ux-scan and brand-scan are dropped for Rust, Python and Go. Only the main loop's listing is reported. A dropped skill named in a prompt is still described for that prompt.

  • /context-diet shows the project kind, what was kept and dropped in the latest listing, and the tokens saved (estimate). A listing it cannot read reliably goes out unchanged.
  • /context-diet on|off|reset overrides the option for this session. Switching rebuilds the listing, so the prompt cache misses once.
OptionDefault
enabledfalse
keepComma list of names or prefix* never dropped; wins over drop
dropComma list of names or prefix* always dropped

browser-cam

  • While Claude drives a browser (Claude in Chrome, Claude Browser, or a remote device's browser), a pane shows the latest screenshot, the page title and URL, and the last 8 actions with ✓/✗. The URL comes only from the navigate call or the tab tools' own header, never from page text. Text typed or filled in is shown as its length only (type ‹7文字›), 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.
  • The desktop app shows the title and URL, a caption and the actions, without the picture.
OptionDefault
autoOpentrueOpen on the first browser call (fullscreen terminal)

prompt-coach

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 unchanged
  • e: 補足して送る puts it back with 完了条件: to fill in (not held again)
  • q: 閉じる puts it back in the prompt

Typing 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.

OptionDefault
enabledtrue
modelclaude-haiku-5-5Judging model (alias or id)
timeoutMs3000500 to 3000

loopback

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 reply
  • done-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 once

Each 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.
OptionDefault
enabledfalse

Cost: the findings ride as extra input on the prompt they are attached to (each quote clipped to 300 characters, at most 12 findings).

zukan

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 entry

The newest 300 kinds by last sighting are kept.

pr-lamp

The current branch's pull request, kept in the status line while you work:

⎇ #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), ✅ Approved, 🟢 #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 default

Which 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.

fog-map

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/  ░ context-diet/  …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
  • The status line keeps 🗺 31% · ●9 · ✗2 · ⚠1
  • A toast at 25, 50, 75 and 100% explored, and when an edit first reaches a new area (🗺 新しい区域を開拓: mods/zukan/)

The map is the session's, subagents' calls included; files outside the repository ar

Source 3 files
hooks/register.tsx 246 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { PerfReport, PerfSample } from '../types'
5import { baselineKey, commandStderr, isSafeRef, isTimeout, MIN_RUNS, parseArgs, parseTime, reportLines, statsOf, verdictOf } from './delta'
6
7const PANE = 'perf-delta'
8const TITLE = '性能差'
9const BASELINES = 'baselines'
10const KEEP_BASELINES = 30
11
12const report = atom({ plugin: 'perf-delta', key: 'report' } as const, null as PerfReport | null)
13
14type Settings = { runs: number; timeoutMs: number }
15
16// Whether /usr/bin/time takes -l (BSD, macOS) or -v (GNU), learned once per load.
17let timeFlag: '-l' | '-v' | null | undefined
18let isBusy = false
19
20async function flagOf($: EngineInterface): Promise<'-l' | '-v' | null> {
21  if (timeFlag !== undefined) return timeFlag
22  const exists = await $.fs.exists('/usr/bin/time').catch(() => false)
23  const os = exists ? await $.process.run(['uname', '-s']).catch(() => undefined) : undefined
24  timeFlag = !exists ? null : os?.stdout.trim() === 'Darwin' ? '-l' : '-v'
25  return timeFlag
26}
27
28/** One warm-up run, then `runs` measured ones, in `cwd`. Throws on a failing run. */
29async function measure($: EngineInterface, cwd: string, command: string, label: string, s: Settings): Promise<PerfSample> {
30  const flag = await flagOf($)
31  const argv = flag === null ? ['/bin/sh', '-c', command] : ['/usr/bin/time', flag, '/bin/sh', '-c', command]
32  const timesMs: number[] = []
33  const rssBytes: number[] = []
34  for (let i = 0; i <= s.runs; i += 1) {
35    await update($, report, old => (old === null ? null : { ...old, note: `${label}: ${i === 0 ? 'ウォームアップ' : `${i}/${s.runs} 回目`}` }))
36    const started = await $.clock.now()
37    let failure: unknown
38    const ran = await $.process.run(argv, { cwd, timeoutMs: s.timeoutMs }).catch(err => {
39      failure = err
40      return undefined
41    })
42    const elapsed = (await $.clock.now()) - started
43    // The run rejects both when it outlasts the timeout and when it cannot start (a missing folder).
44    if (ran === undefined && !isTimeout(elapsed, s.timeoutMs)) {
45      throw new Error(`${label}: 起動できませんでした — ${failure instanceof Error ? failure.message : String(failure)}`.slice(0, 300))
46    }
47    if (ran === undefined) throw new Error(`${label}: ${s.timeoutMs / 1000}秒以内に終わりませんでした`)
48    if (ran.exitCode !== 0) throw new Error(`${label}: 終了コード ${ran.exitCode}${commandStderr(ran.stderr) === '' ? '' : ` — ${commandStderr(ran.stderr).slice(-300)}`}`)
49    if (i === 0) continue
50    const parsed = parseTime(ran.stderr)
51    // time(1) reports to 10 ms: under a second the host clock's own measure is the finer one.
52    timesMs.push(parsed.wallMs !== undefined && (parsed.wallMs >= 1000 || elapsed <= 0) ? parsed.wallMs : elapsed)
53    if (parsed.rssBytes !== undefined) rssBytes.push(parsed.rssBytes)
54  }
55  return { label, command, at: await $.clock.now(), timesMs, rssBytes }
56}
57
58type Baselines = Record<string, PerfSample>
59const baselinesOf = async ($: EngineInterface): Promise<Baselines> => ((await $.store.get(BASELINES)) as Baselines | undefined) ?? {}
60
61async function saveBaseline($: EngineInterface, key: string, sample: PerfSample): Promise<void> {
62  const all = { ...(await baselinesOf($)), [key]: { ...sample, label: '基準' } }
63  const kept = Object.entries(all)
64    .sort(([, a], [, b]) => b.at - a.at)
65    .slice(0, KEEP_BASELINES)
66  await $.store.set(BASELINES, Object.fromEntries(kept))
67}
68
69async function git($: EngineInterface, cwd: string, argv: string[]) {
70  return $.process.run(['git', ...argv], { cwd, timeoutMs: 120_000 }).catch(() => undefined)
71}
72
73const tmpOf = async ($: EngineInterface): Promise<string> => ((await $.env.get('TMPDIR')) || '/tmp').replace(/\/+$/, '')
74// Its folder's name carries when it was made, then a random part mktemp chose.
75const WORKTREE = /\/perf-delta-(\d+)-[\w]+$/
76// The longest a run can take is about 8.5 hours (51 runs of at most 10 minutes): past this a
77// worktree of ours is left over from a run cut short (a reload, a crash). Ours are locked while
78// they run, so a locked one waits longer: a laptop asleep mid-run may pass the wall-clock bound.
79const STALE_MS = 12 * 60 * 60_000
80const LOCKED_STALE_MS = 48 * 60 * 60_000
81
82/** The folder below the repository's top that cwd is, as git reads it: right in a linked worktree too. */
83async function folderOf($: EngineInterface, cwd: string): Promise<string> {
84  const ran = await git($, cwd, ['rev-parse', '--show-prefix'])
85  return ran?.exitCode === 0 ? ran.stdout.trim().replace(/\/+$/, '') : ''
86}
87
88/**
89 * Removes a worktree of ours, locked or not. When git cannot (a process still writing in it), its
90 * folder goes and then its registration alone: never a prune, which would drop the person's own
91 * worktrees whose folders are away (an unmounted disk).
92 */
93async function dropWorktree($: EngineInterface, root: string, dir: string): Promise<void> {
94  const remove = () => git($, root, ['worktree', 'remove', '--force', '--force', '--', dir])
95  if ((await remove())?.exitCode === 0) return
96  if (WORKTREE.test(dir)) await $.process.run(['rm', '-rf', '--', dir], { timeoutMs: 120_000 }).catch(() => undefined)
97  await remove()
98}
99
100/** Worktrees of ours a run cut short left registered in the repository, by when each was made. */
101async function dropStale($: EngineInterface, root: string): Promise<void> {
102  const now = await $.clock.now()
103  const tmp = await tmpOf($)
104  // git lists a worktree by its real path: TMPDIR on macOS is under /var, a link to /private/var.
105  const real = (await $.fs.stat(tmp, { resolve: true }).catch(() => undefined))?.realPath ?? tmp
106  const listed = await git($, root, ['worktree', 'list', '--porcelain'])
107  for (const block of listed?.exitCode === 0 ? listed.stdout.split('\n\n') : []) {
108    const dir = block.match(/^worktree (.+)$/m)?.[1] ?? ''
109    const made = Number(dir.match(WORKTREE)?.[1] ?? NaN)
110    const isOurs = dir.startsWith(`${tmp}/`) || dir.startsWith(`${real}/`)
111    const age = /^locked\b/m.test(block) ? LOCKED_STALE_MS : STALE_MS
112    if (isOurs && now - made > age) await dropWorktree($, root, dir)
113  }
114}
115
116/** Runs `command` in a temporary worktree of `ref`, in the same folder below the top. */
117async function measureRef($: EngineInterface, root: string, below: string, ref: string, command: string, s: Settings): Promise<PerfSample> {
118  // A folder only this user can have made: a name another could guess and fill first is none.
119  const made = await $.process.run(['mktemp', '-d', `${await tmpOf($)}/perf-delta-${await $.clock.now()}-XXXXXX`]).catch(() => undefined)
120  const dir = made?.exitCode === 0 ? made.stdout.trim() : ''
121  if (!WORKTREE.test(dir)) throw new Error('一時フォルダを作れませんでした(TMPDIR を確認してください)')
122  // Locked while it runs, so another session's start never takes it for one left behind.
123  const added = await git($, root, ['worktree', 'add', '--lock', '--detach', '--', dir, ref])
124  if (added?.exitCode !== 0) {
125    await dropWorktree($, root, dir)
126    throw new Error(`git worktree add ${ref} に失敗: ${added?.stderr.trim().slice(-200) ?? ''}`)
127  }
128  try {
129    const inside = below === '' ? dir : `${dir}/${below}`
130    if (below !== '' && !(await $.fs.exists(inside).catch(() => false))) throw new Error(`${ref} には ${below} がありません(このフォルダはその時点のコミットにありません)`)
131    return await measure($, inside, command, ref, s)
132  } finally {
133    await dropWorktree($, root, dir)
134  }
135}
136
137function toastOf(r: PerfReport): string {
138  const t = verdictOf(r.before === undefined ? undefined : statsOf(r.before.timesMs), r.after === undefined ? undefined : statsOf(r.after.timesMs))
139  if (r.before === undefined) return '⏱ 基準を保存しました'
140  if (t.deltaPct === undefined) return '⏱ 計測しました'
141  const word = t.verdict === 'faster' ? '速くなった' : t.verdict === 'slower' ? '遅くなった' : t.verdict === 'few' ? '回数が少なく判定できません' : 'ばらつきの範囲内'
142  return `⏱ ${t.deltaPct > 0 ? '+' : ''}${t.deltaPct.toFixed(1)}% ${word} — /perf`
143}
144
145export const register: Register = (on, options) => {
146  const settings: Settings = {
147    // At least MIN_RUNS: with fewer no difference is ever called.
148    runs: Math.max(MIN_RUNS, Math.min(50, Math.round(Number(options.runs ?? 5)) || 5)),
149    timeoutMs: Math.max(5, Math.min(600, Number(options.timeoutSec ?? 300) || 300)) * 1000,
150  }
151
152  on('session.start', async ($, e, next) => {
153    await $.command.register({
154      name: 'perf',
155      description: 'ベンチマークの変更前後を比較(/perf <cmd> · /perf base <cmd> · /perf ref <git-ref> <cmd> · /perf show)',
156      argumentHint: '<cmd> | base <cmd> | ref <git-ref> <cmd> | show | clear [cmd]',
157    })
158    const started = await next(e)
159    // Worktrees of ours a run cut short left: cleaned after the start, not holding it up.
160    const root = (await $.session.repo())?.root
161    if (root !== undefined) $.clock.after(0, () => void dropStale($, root).catch(() => undefined))
162    return started
163  })
164
165  on('command.run', { command: 'perf' }, async ($, e) => {
166    const { mode, ref, command } = parseArgs(e.args)
167    const root = (await $.session.repo())?.root ?? (await $.session.cwd())
168    const cwd = await $.session.cwd()
169    const below = await folderOf($, cwd)
170
171    if (mode === 'show') {
172      const shown = await read($, report)
173      if (shown === null) return { text: '⏱ まだ計測していません。/perf <コマンド> で計測します。' }
174      await $.ui.open({ id: PANE, title: TITLE })
175      return { text: [`⏱ ${shown.command}`, ...reportLines(shown.before, shown.after)].join('\n') }
176    }
177    if (mode === 'clear') {
178      const all = await baselinesOf($)
179      const kept = command === '' ? {} : Object.fromEntries(Object.entries(all).filter(([key]) => key !== baselineKey(root, command, below)))
180      await $.store.set(BASELINES, kept)
181      return { text: `⏱ 基準を${command === '' ? 'すべて' : ''}削除しました。` }
182    }
183    if (command === '') return { text: '⏱ 計測するコマンドを指定してください。' }
184    if (mode === 'ref' && (ref === undefined || !isSafeRef(ref))) return { text: `⏱ git ref として使えない値です: ${ref ?? ''}` }
185    if (isBusy) return { text: '⏱ 計測中です。終わるまでお待ちください。' }
186
187    const key = baselineKey(root, command, below)
188    const saved = (await baselinesOf($))[key]
189    isBusy = true
190    await update($, report, (): PerfReport => ({ status: 'running', command, note: '準備中' }))
191    $.ui.status('⏱ 計測中')
192    $.clock.after(0, () => {
193      void (async () => {
194        try {
195          if (mode === 'base') {
196            const after = await measure($, cwd, command, '基準', settings)
197            await saveBaseline($, key, after)
198            await update($, report, (): PerfReport => ({ status: 'done', command, after }))
199          } else if (mode === 'ref') {
200            const before = await measureRef($, root, below, ref as string, command, settings)
201            const after = await measure($, cwd, command, '現在', settings)
202            await update($, report, (): PerfReport => ({ status: 'done', command, before, after }))
203          } else {
204            const after = await measure($, cwd, command, saved === undefined ? '基準' : '現在', settings)
205            if (saved === undefined) await saveBaseline($, key, after)
206            await update($, report, (): PerfReport => ({ status: 'done', command, ...(saved === undefined ? {} : { before: saved }), after }))
207          }
208          const done = await read($, report)
209          if (done !== null) $.ui.toast(toastOf(done))
210        } catch (err) {
211          await update($, report, (): PerfReport => ({ status: 'failed', command, note: err instanceof Error ? err.message : String(err) }))
212          $.ui.toast('⏱ 計測に失敗しました — /perf show')
213        } finally {
214          isBusy = false
215          $.ui.status(undefined)
216        }
217      })()
218    })
219    await $.ui.open({ id: PANE, title: TITLE })
220    const plan =
221      mode === 'ref' ? `${ref} を一時 worktree で計測してから現在を計測` : mode === 'base' || saved === undefined ? '基準として計測(次回の /perf と比較)' : `保存済みの基準(${new Date(saved.at).toLocaleString()})と比較`
222    return { text: `⏱ ${command}: ${plan}。ウォームアップ1回 + ${settings.runs}回。` }
223  })
224
225  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
226    const { Box, Text } = $.ui.resolve(e)
227    const shown = await read($, report)
228    if (shown === null) return <Text dimColor>まだ計測していません。</Text>
229    const lines = reportLines(shown.before, shown.after)
230    const color = (line: string) => (line.includes('悪化') ? 'red' : line.includes('改善') ? 'green' : line.includes('⚠') ? 'yellow' : undefined)
231    return (
232      <Box flexDirection="column">
233        <Text bold wrap="truncate-end">{`⏱ ${shown.command}`}</Text>
234        {shown.status === 'running' && <Text color="cyan">{`計測中… ${shown.note ?? ''}`}</Text>}
235        {shown.status === 'failed' && <Text color="red">{`失敗: ${shown.note ?? ''}`}</Text>}
236        {shown.status === 'done' && shown.before === undefined && <Text dimColor>基準として保存しました。変更後にもう一度 /perf を実行すると比較します。</Text>}
237        {lines.map((line, index) => (
238          <Text key={`l-${index}`} color={color(line)} bold={!line.startsWith(' ')} wrap="truncate-end">
239            {line}
240          </Text>
241        ))}
242      </Box>
243    )
244  })
245}
246
hooks/delta.ts 116 lines
1// The comparison, pure: what /usr/bin/time said of a run, the statistics of a side, and
2// whether two sides differ by more than their noise.
3
4import type { PerfSample } from '../types'
5
6/** Wall time (ms) and peak memory (bytes) from `/usr/bin/time -l` (macOS) or `-v` (GNU). */
7export function parseTime(stderr: string): { wallMs?: number; rssBytes?: number } {
8  const out: { wallMs?: number; rssBytes?: number } = {}
9  const bsdReal = stderr.match(/^\s*([\d.]+)\s+real\b/m)
10  if (bsdReal?.[1] !== undefined) out.wallMs = Number(bsdReal[1]) * 1000
11  const bsdRss = stderr.match(/^\s*(\d+)\s+maximum resident set size/m)
12  if (bsdRss?.[1] !== undefined) out.rssBytes = Number(bsdRss[1])
13  const gnuWall = stderr.match(/Elapsed \(wall clock\) time \([^)]*\):\s*(?:(\d+):)?(\d+):([\d.]+)/)
14  if (gnuWall !== null) out.wallMs = (Number(gnuWall[1] ?? 0) * 3600 + Number(gnuWall[2]) * 60 + Number(gnuWall[3])) * 1000
15  const gnuRss = stderr.match(/Maximum resident set size \(kbytes\):\s*(\d+)/)
16  if (gnuRss?.[1] !== undefined) out.rssBytes = Number(gnuRss[1]) * 1024
17  return out
18}
19
20/** The lines /usr/bin/time added, taken off what the command itself wrote to stderr. */
21export function commandStderr(stderr: string): string {
22  return stderr
23    .split('\n')
24    .filter(line => !/^\s*[\d.]+\s+(?:real|user|sys)\b|^\s*\d+\s+[a-z][a-z ()-]+$|^\s*(?:Command being timed|User time|System time|Percent of CPU|Elapsed|Average|Maximum resident|Major|Minor|Voluntary|Involuntary|Swaps|File system|Socket|Signals|Page size|Exit status)\b/.test(line))
25    .join('\n')
26    .trim()
27}
28
29export type Stats = { n: number; median: number; mean: number; stdev: number; cv: number; min: number; max: number }
30
31export function statsOf(values: readonly number[]): Stats | undefined {
32  if (values.length === 0) return undefined
33  const sorted = [...values].sort((a, b) => a - b)
34  const n = sorted.length
35  const mid = Math.floor(n / 2)
36  const median = n % 2 === 1 ? (sorted[mid] as number) : ((sorted[mid - 1] as number) + (sorted[mid] as number)) / 2
37  const mean = sorted.reduce((sum, v) => sum + v, 0) / n
38  const stdev = n < 2 ? 0 : Math.sqrt(sorted.reduce((sum, v) => sum + (v - mean) ** 2, 0) / (n - 1))
39  return { n, median, mean, stdev, cv: mean === 0 ? 0 : (stdev / mean) * 100, min: sorted[0] as number, max: sorted[n - 1] as number }
40}
41
42export type Verdict = 'faster' | 'slower' | 'noise' | 'few' | 'unknown'
43
44/** Runs a side needs before a difference is called: with fewer there is no spread to weigh it by. */
45export const MIN_RUNS = 3
46
47/**
48 * Whether the medians differ by more than the noise: more than twice the larger standard
49 * deviation and more than 1% of the baseline, each side measured at least MIN_RUNS times. A
50 * lower value is better (time, memory).
51 */
52export function verdictOf(before: Stats | undefined, after: Stats | undefined): { verdict: Verdict; deltaPct?: number } {
53  if (before === undefined || after === undefined || before.median === 0) return { verdict: 'unknown' }
54  const delta = after.median - before.median
55  const deltaPct = (delta / before.median) * 100
56  if (before.n < MIN_RUNS || after.n < MIN_RUNS) return { verdict: 'few', deltaPct }
57  const noise = 2 * Math.max(before.stdev, after.stdev)
58  if (Math.abs(delta) <= noise || Math.abs(deltaPct) < 1) return { verdict: 'noise', deltaPct }
59  return { verdict: delta < 0 ? 'faster' : 'slower', deltaPct }
60}
61
62/**
63 * Whether a run that rejected did so at its time limit (else it could not start: a folder gone).
64 * A second's slack: a timer fires a little early, and the wall clock can step.
65 */
66export const isTimeout = (elapsedMs: number, timeoutMs: number): boolean => elapsedMs >= timeoutMs - 1000
67
68export const ms = (v: number): string => (v >= 10_000 ? `${(v / 1000).toFixed(1)}s` : v >= 1000 ? `${(v / 1000).toFixed(2)}s` : `${v.toFixed(v < 10 ? 1 : 0)}ms`)
69export const mb = (v: number): string => `${(v / 1024 / 1024).toFixed(v >= 100 * 1024 * 1024 ? 0 : 1)}MB`
70export const pct = (v: number): string => `${v > 0 ? '+' : ''}${v.toFixed(1)}%`
71
72const WORD: Record<Verdict, string> = { faster: '改善', slower: '悪化', noise: 'ばらつきの範囲内', few: `回数が少なく判定できません(各 ${MIN_RUNS} 回以上。古い基準なら /perf base で取り直してください)`, unknown: '比較できません' }
73
74/** The comparison as lines: one for time, one for memory, and a warning per unsteady side. */
75export function reportLines(before: PerfSample | undefined, after: PerfSample | undefined): string[] {
76  const lines: string[] = []
77  const side = (label: string, s: Stats | undefined, fmt: (v: number) => string) =>
78    s === undefined ? `${label} —` : `${label} 中央値 ${fmt(s.median)} (±${fmt(s.stdev)}, CV ${s.cv.toFixed(1)}%, ${fmt(s.min)}〜${fmt(s.max)}, n=${s.n})`
79  for (const [name, pick, fmt] of [
80    ['時間', (x: PerfSample) => x.timesMs, ms],
81    ['メモリ', (x: PerfSample) => x.rssBytes, mb],
82  ] as const) {
83    const b = before === undefined ? undefined : statsOf(pick(before))
84    const a = after === undefined ? undefined : statsOf(pick(after))
85    if (b === undefined && a === undefined) continue
86    const { verdict, deltaPct } = verdictOf(b, a)
87    lines.push(`${name}: ${deltaPct === undefined ? '' : `${pct(deltaPct)} `}${WORD[verdict]}`)
88    if (before !== undefined) lines.push(`  ${side(before.label, b, fmt)}`)
89    if (after !== undefined) lines.push(`  ${side(after.label, a, fmt)}`)
90    for (const [label, s] of [[before?.label, b], [after?.label, a]] as const) {
91      if (s !== undefined && s.cv > 10) lines.push(`  ⚠ ${label} のばらつきが大きい(CV ${s.cv.toFixed(0)}%): 回数を増やすか、他の負荷を止めて測り直してください`)
92    }
93  }
94  return lines
95}
96
97/** `/perf` arguments: `base <cmd>`, `ref <git-ref> <cmd>`, `clear`, `show`, or a command. */
98export function parseArgs(args: string): { mode: 'run' | 'base' | 'ref' | 'show' | 'clear'; ref?: string; command: string } {
99  const text = args.trim()
100  const [first = '', ...rest] = text.split(/\s+/)
101  if (first === 'show' || first === '') return { mode: 'show', command: '' }
102  if (first === 'clear') return { mode: 'clear', command: rest.join(' ') }
103  if (first === 'base') return { mode: 'base', command: text.slice(4).trim() }
104  if (first === 'ref' && rest.length >= 2) return { mode: 'ref', ref: rest[0], command: text.slice(4).trim().slice((rest[0] as string).length).trim() }
105  // `ref` with no command, or nothing at all, asks for what is missing: it is no command to run.
106  if (first === 'ref') return rest[0] === undefined ? { mode: 'ref', command: '' } : { mode: 'ref', ref: rest[0], command: '' }
107  return { mode: 'run', command: text }
108}
109
110/** A baseline is the command's in the folder it ran in (below the top, as git names it): at the top the key it always was. */
111export const baselineKey = (root: string, command: string, below = ''): string =>
112  `${root}\u0000${below === '' ? '' : `${below}\u0000`}${command.trim().replace(/\s+/g, ' ')}`
113
114/** A git ref safe to hand to git: no option, no whitespace, no shell or revision-range tricks. */
115export const isSafeRef = (ref: string): boolean => /^[\w][\w./~^@{}-]*$/.test(ref) && !ref.includes('..')
116
types/index.d.ts 30 lines
1/** One side of a comparison: the measured runs of a command in one tree. */
2export type PerfSample = {
3  /** Where it ran: `HEAD~1` (a worktree), `基準` (a saved baseline) or `現在`. */
4  label: string
5  command: string
6  at: number
7  /** Wall time of each measured run, in milliseconds. */
8  timesMs: number[]
9  /** Peak resident memory of each run, in bytes, where /usr/bin/time reported it. */
10  rssBytes: number[]
11}
12
13/** A /perf comparison, as the pane draws it. */
14export type PerfReport = {
15  status: 'running' | 'done' | 'failed'
16  command: string
17  before?: PerfSample
18  after?: PerfSample
19  /** What is running now, or why it failed. */
20  note?: string
21}
22
23declare module 'claude-code' {
24  interface PluginState {
25    'perf-delta': {
26      report: PerfReport | null
27    }
28  }
29}
30