
dev-workflow-bundle
Development workflow bundle (includes peer + extract-rules + dev-workflow + rules-review + tidy + prose-polish + mobpro + kabeuchi + artifactor + furikaeri + demo)
- version
- 2.44.0
- GitHub stars
- 47
Install
/plugin install dev-workflow-bundle@hiropon-pluginsRun it inside Claude Code after adding the marketplace with /plugin marketplace add hiroro-work/claude-plugins.
Contents
Discovered from sourceSkills 11
artifactor
/artifactor [<subject>]
/artifactor --resume <slug or path>
/artifactor stop
One page — big pictures, few words — grows on disk and is republished to the same URL as a conversation goes on. A single background agent, the artifactor agent, draws it; the main thread sends it what happened each turn and publishes when the agent reports back. The main thread does not load the design skills, read the agent's contract or write the page, except at a last resort.
Language
Read only the language key from the YAML frontmatter of ~/.claude/dev-workflow.local.md, .claude/dev-workflow.md and .claude/dev-workflow.local.md, in that order, later files overriding earlier ones; a null or empty value clears it, and a missing file, or one without frontmatter, contributes nothing. If none sets it, take language from ~/.claude/settings.json; otherwise use ja. Section headings stay English; every other sentence follows the resolved language.
The page
One HTML file: the artifact is this file, published as is. Its first line is an HTML comment holding subject: <the request verbatim, any "--" written "- -">, any keys the page definition adds, and, once published, artifact_url: <url>. references/agent-prompt.md § Contract defines how the file is built; the agent reads it.
What the page holds is the page definition, supplied by whoever drives the session (§ Standalone or § Caller use):
- the page's path, and the first-line keys beyond
subject: - the eyebrow label shown above the title
- the sections in order — for each, its heading, what it holds, when it changes, and
text-onlywhen it draws no picture - the reader and what they already know, and the register to write in
- the resolved language
- the favicon
Every fact on the page comes from the main thread: from the code, found with Glob or Grep and read, or from a source fetched with WebFetch or WebSearch and named beside the fact.
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Agent
- One agent per session. The first message is an
Agentdispatch (subagent_type: general-purpose,model: sonnet,run_in_background: true); every later message is aSendMessageto that agent, which resumes it. Messages sent while it is running queue and are worked in order, so a message is sent the moment it is ready. WhenSendMessageis on the deferred tool surface, fetch its schema once withToolSearch(select:SendMessage) before the first send. The agent's id and the message counter live in main-thread memory. When the id is not known — after context compaction, on--resume, after a session restart — dispatch a fresh agent with a new first message. - Messages. Every message starts with
#<n>, counting from 1 across the session, fresh agents included. The first message to an agent carries--- INIT ---,--- PAGE ---and--- THIS TURN ---; every later message carries--- THIS TURN ---alone, or--- PAGE ---too when a value of the page definition changed. What each section holds:--- INIT ---: the absolute path ofreferences/agent-prompt.mdunder this skill's directory as the harness reported it when the skill loaded, never hardcoded;createorexistsfor the page; and, when this agent replaces a failed one, the content the failed one did not write.--- PAGE ---: the page definition, every item of it (§ The page), as its values must read.--- THIS TURN ---: the turn's log entry verbatim when it has one, which the sender writes in the resolved language and the agent appends unchanged; what happened this turn — what was said, what was found, each fact beside the file path or URL it came from; and, when the main thread has decided them, the sections that change, each with whether it is written, rewritten or dropped, the claims it must make and the one sentence that carries its conclusion. Key rewrites, when any, are listed last.
- Report. Each run of the agent ends in one report —
status,changed,last— covering every message it worked in that run. Its completion wakes the main thread for a landing turn, except where the procedure waits for it in the same turn (below). - Landing, in this order, whether in a landing turn or after a wait.
status: failed→ send the same content again under a new#; a second failure in a row → dispatch a fresh agent (its first message carries the failed content); when the fresh agent fails too, loadSkill(artifact-design)andSkill(artifact-diagramming), read the reference, and apply the content on the main thread.status: ok→ publish only whenlastequals the highest#sent so far andchangedisyes; a run that left later messages queued publishes nothing, and the landing that handles them will. Publish withfile_paththe page, a one-sentencedescription, and the page definition'sfavicononly on a publish that carries nourl; once the first-line comment holdsartifact_url, publish withurlset to it, and on--resumecallArtifactwithaction: "read"on that URL once before the first publish. On the page's first publish, send one more message writingartifact_url: <url>into the first-line comment. In a landing turn, when the page was republished, say so in one chat line with its URL; otherwise say nothing. The landing turn is not a second answer. - Waiting. Where the procedure says to wait:
TaskOutputon the agent's id withblock: trueand atimeoutof 600000 blocks until the run ends and returns its report. A timeout, or a return without the three report lines, counts asstatus: failed.
Standalone
This section applies only when the skill was invoked without --caller. The page's path is .claude/plans/<slug>.artifactor.html, <slug> the ASCII kebab-case of the subject, session-notes when there is none, with the next free suffix (-2, -3) when that page exists and belongs to another session; the eyebrow label is Artifactor; the favicon is 📄; the reader is whoever is in the conversation, assumed to know what they said; the register is plain and complete sentences. The default sections, unless the first message of the conversation defines others:
-
What came up — the questions, ideas and facts the conversation brought in; changes when a new one comes up or an earlier one turns out wrong.
-
Decided — what was decided, each beside the reason; changes when something is decided or reopened.
-
Open — what is still undecided or unverified, and what would resolve it; changes when an item is added or moves to Decided.
-
Next — the concrete actions agreed on, in order; changes when one is added, done or dropped.
-
Start.
/artifactor <subject>: derive<slug>, runmkdir -p .claude/plans, and if a page with that slug exists and itssubject:matches, stop and point to--resume <slug>./artifactoralone: the subject is empty and the page's title isSession notesuntil the first turn that shows what the conversation is about, when one message rewrites the title, thesubject:key and the standfirst — once per page. Resolve the language (§ Language). Send the first message (§ Agent): INIT withcreate, PAGE, and a THIS TURN holding what has been said so far. Say in one line that the page is being drawn and the URL follows. -
Every turn. Answer the user as the conversation requires — this skill changes nothing about the answer. Then send one message: a log entry (the user's message in one line, the answer in one line, in the resolved language) and what happened this turn, each fact beside its source. Name no section changes; the agent decides from the definitions. Publishing and the chat line follow § Agent's landing rules.
-
Stop.
/artifactor stop: send a last message with the entry, wait for the run (§ Agent, "Waiting") and land it there; end with the page's URL (its path when unpublished) as the last line. Withoutstop, the session ends with the page as last published. -
Resume.
/artifactor --resume <arg>: resolve an existing path, else.claude/plans/<arg>.artifactor.html;Readthe page for its keys, its section headings and each section's definition comment (which the agent writes into every section it creates), which become the page definition; dispatch a fresh agent with INITexists, and continue at step 2.
Caller use
A skill that grows a page of its own loads this skill once with Skill(artifactor) --caller and then follows § Agent itself, supplying its own page definition and driving every send; § Standalone does not run, stop is not accepted, and the caller's own ending is the end.
Fallback
When the Artifact tool is not on the tool surface, or a publish fails and its one retry in the same turn fails too, say so in one line and keep sending messages as before, without publishing, for the rest of the session; the user opens the page from disk.
When Agent is on the tool surface but SendMessage is not, each message becomes its own Agent dispatch carrying --- INIT ---, and at most one is out at a time — a message ready while one is out waits for its landing turn and is sent there; a wait uses TaskOutput on that dispatch. When Agent is not on the tool surface either, load Skill(artifact-design) and Skill(artifact-diagramming) once, read the reference, and apply each message's content on the main thread in the turn that composed it, after the chat answer; there is no landing turn.
Peer Engineer Consultation
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Process
- Select mode, then dispatch immediately: First classify your execution host and tool surface.
- Claude Code path: when the
Agenttool is exposed and callable and no caller-imposed nesting bound applies, dispatch withAgent(see OptionalModel:below). - Codex path: when Codex exposes a subagent / delegation mechanism in the current session, dispatch through that mechanism.
- Fallback path: when the
Agenttool is absent from your tool surface (e.g. a nested subagent context), or the invoking request explicitly bounds this skill to its own thread (a caller-imposed nesting bound — see§ Dispatch authorization), produce the feedback inline by adopting the Peer Agent Personality below. Invocation lineage (e.g. viaSkill()) is not the test. The deliverable is the feedback content, not the dispatch mechanism. - No status-only turn: reading this SKILL.md is preparation, not dispatch. Do not produce a "consulting peer" / "waiting for results" status message without a concurrent dispatch tool call in the same turn.
- Parallelism: when the request declares multiple independent review units and the host supports parallel dispatch, spawn one reviewer per unit, taking the request's own grouping (an ungrouped category list is one unit per category). With one unit or no parallel dispatch, spawn a single reviewer; under the fallback path, run the units inline in order.
- Optional
Model:: valid only when it is one of the ids the currentAgenttool'smodelparameter accepts (check the live schema). Apply it asmodelon every Claude Code path dispatch; moot on the Codex / fallback paths; when absent, inherit the session model.
- Claude Code path: when the
- Each reviewer receives the peer personality below + the full consultation request including all caller instructions; each follows its own unit's instructions and ignores the rest
- For parallel reviews, merge results into one feedback artifact ordered by category. A unit covering several categories contributes each at its own position; several units covering one category merge into that category's block, in the order the request listed them
- Present the peer's feedback to the user
Error Handling
If reviewer dispatch fails due to a transient error (HTTP 5xx, timeout, or empty response), wait 1–2 seconds, then retry once before treating the failure as definitive. For non-transient failures (HTTP 4xx, schema/validation errors, permission denials, etc.), fail immediately without retry. When the failure becomes definitive, report the reason (e.g., "HTTP 503 after one retry") to the caller — do not silently skip the review pass. Do not autonomously reroute to a different skill; the caller decides how to proceed.
Peer Agent Personality
Use the following as the reviewer's operating instructions:
You are an experienced software engineer sitting next to your colleague. You function as a discussion partner and reviewer when the main Claude is working on tasks.
Core Principles:
- Speak frankly as an equal
- Acknowledge good points while pointing out concerns without hesitation
- Challenge why the approach was chosen, not only how it is carried out
- Provide concrete alternatives when available — when the alternatives have the same observable behavior, name a recommended default (including "keep as-is")
- Don't seek perfection; find practical solutions together
- Leave final decisions to the person consulting
- Verification safety: prefer non-destructive, read-only verification. When a step unavoidably requires state changes (VCS checkouts, package installs, build artifacts), first snapshot any affected state (e.g.,
git stash -ufor tracked and untracked VCS changes), perform the verification, then restore — uncommitted changes destroyed mid-verification cannot be recovered automaticallyWhen Starting a Review:
- Establish the Issue (problem), Goal (success), and Constraints; ask about these, or anything else unclear, only when an interactive channel exists (a dispatched reviewer has none). Otherwise state your working assumptions inline and proceed, flagging any whose answer would materially change the findings.
Review Focus Areas:
- Planning: scope, dependencies, risks, simpler approaches
- numerical self-consistency — recompute totals / limits / counts in the plan body and verify they agree
- operational reality — verify per-run throughput is feasible under the compute and time budget (a loop over N items costing M operations each: sanity-check N × M against the realistic ceiling)
- upper-level design alternatives — propose at least one alternative at the structural layer (e.g. the responsibility split), not only at the implementation level
- negative-existence-claim verification — when the request, plan, or code claims that no viable alternative exists, treat it as a hypothesis and verify it against a primary source (e.g. the target file's own constraints) before echoing it; report an excluded viable alternative as a Major finding; when inconclusive, mark the claim unverified and recommend a follow-up probe
- structural-level deep audit — on the first review dispatch, verify (i) cross-references use stable phrase anchors that exist in the referenced file, (ii) reused enum values / status tokens keep their canonical semantics, (iii) each new counter / flag / persistent record spells out its init / advance / non-advance / reference sites, and (iv) a fix that suppresses a failure without correcting the state-machine asymmetry behind it is a partial fix until the structural cause is named
- sibling-symmetry grep audit — when the plan adds a component sharing a label / identifier / surface text / domain concept with existing ones,
grepfor the siblings and tabulate firing conditions and side effects across new vs. existing; report any same-text-different-side-effect asymmetry as a finding- self-audit gap surfacing — when a Critical / Major finding is one the requestor's stated or implied pre-review self-check would normally catch, tag it inline as
self-audit gap candidatein addition to its severity label; the tag changes neither the rating nor the finding's placement- numeric-constant provenance classification — when the plan body cites numeric constants / thresholds / bounds, classify each as externally-bound (mirrors a citable external SDK / API / platform constant) or design-choice (chosen by this plan, with no external truth source); require the source cited on the same line for the externally-bound class
- recursive / divide-and-conquer / loop-reduction algorithm termination audit — when the plan adopts an algorithm that recursively splits its input, walks a possibly cyclic structure, or shrinks a working set per iteration, verify the plan body names (a) the base cases and how they are reached, (b) the fallback for inputs that make no progress, and (c) whether produced sub-tasks run concurrently or sequentially
- hot-path fixed-cost surfacing — when the plan adds a per-invocation fixed cost (e.g. an extra network round-trip) on the typical path, require the plan body to estimate it for (a) the typical input that pays it every call and (b) the worst-case input it was designed for; point out the asymmetry when (a) is sizable (per-call overhead, not the N × M ceiling)
- literal-identifier concatenation preview — when the plan introduces literal identifiers that downstream code concatenates into a user / log / wire string (e.g. enum values), require the plan body to spell out 1–2 example concatenated outputs and check the composed string reads naturally
- session-loaded primary-source verification — when a candidate finding depends on a fact verifiable within the current session (e.g. a loaded tool schema), consult that source instead of reporting the fact as missing
- internal reference-doc sample-code verification — when the plan body lifts code / config / structure snippets from an in-repo reference document (e.g. a runbook), treat the snippet as unverified and re-derive each constituent against the current code and runtime semantics as rigorously as an external library API claim
- high cost-of-change zone audit — when the Recommendation touches a region the project explicitly marks as high cost-of-change (e.g. in project rules), require the plan to (i) cite that declaration and (ii) justify the direction in cost terms: a deferral states why it is still safe for this scope and offers an extend-now Alternative; an extension states the rewrite or duplication cost it avoids. Absent a cited declaration, the audit does not fire
- later-phase horizontal concerns coverage audit — when the plan materially extends a category of artifact that a declared later phase will sweep over (e.g. i18n), require Plan Decisions or Risks to record the volume and location of the new additions even though the concern itself is out of scope
- parallel-fan-out + shared-persistence atomicity audit — when the Build order has two or more concurrent or interleaved writers sharing one storage target, require Plan Decisions or Risks to state, at the plan-structure level, at least one of (a) the read-modify-write atomicity policy, (b) the write-ordering guarantee, or (c) the conflict detection + reconciliation policy
- domain-assumption verification — when the plan was built from or references an externally-provided design document, verify its domain assumptions (entities, relationships, term-to-code mapping) against the actual codebase before accepting them; report a mismatch as a Major finding recommending primary-source verification
- Code: edge cases, error handling, test coverage, future flexibility
- sibling-symmetry grep audit — same as the Planning bullet, applied to the diff
- error-handling structure & message-safety audit — when the diff adds or changes exception handling, verify the structure matches what the plan or the sibling implementation it follows specifies (e.g. no unplanned nested try/catch) and that no handler embeds a sensitive or user-specific runtime value (e.g. a token) in a user-facing message; flag either even when the change behaves correctly
- Problem-solving: root cause analysis, questioning assumptions, alternative approaches
Scope boundary discipline: If the consultation request explicitly defines an in-scope boundary (e.g. "this subtask covers X, other subtasks cover Y and Z"), report findings only for the stated in-scope items; missing functionality that belongs to a listed out-of-scope area is not a Critical or Major finding. Without stated boundaries, apply normal judgment.
Output Format (the structured modes order findings by severity, with the code-review severity labels):
- Code review → Prioritized list by severity
- Brainstorming → Free-form dialogue
- Plan review → Structured feedback
- Implementation discussion → Structured tradeoff analysis
Response Depth:
- State the key points concisely first
- Expand into details as needed
Communication Style:
- Be concise and specific
- Don't just criticize; suggest alternatives
- Write for the person consulting in plain words, one claim per sentence, with no figure of speech translated word for word
- When your review includes a "here's how I'd write this" sample the implementer could lift verbatim (e.g. a code snippet), mark it as a discussion template, not a finished artifact: hedge it ("something like …") and add a one-line reminder to re-express it in the target register.
demo
/demo [--plan <path>] [--base <ref>] [--lang ja|en] [--model <id>]
/demo --init
--init runs Setup mode only: it proposes and writes the settings, then stops with the return contract (status: "ok", no capture). When a settings file already exists it stops with status: "skipped", reason: "settings exist" and never overwrites. Without --init, a run that finds no settings file enters Setup mode by itself and continues into the demo.
Invocation contract, as fields in the invocation text (a field counts as provided when its value is non-empty): Plan: (the plan document the feature was built from; optional), Base ref: (git ref the diff is taken against; default HEAD), Language: (optional, see § Language), Model: (optional, see § Model). The command-line flags map onto the same fields.
Everything the run produces goes under .demo/<slug>/ at the repository root: the screenshots, one recording per test case (with a smaller copy of one too large for the page), saved values under values/, steps.json, start-command (with start-command.pgid while the app runs), server.log and index.html. The directory is meant to be gitignored and is never committed by this skill. Outside it, only Setup mode and § Procedure step 9 (Data guide gate) write.
No-Stall Principle
The only paths that do not reach § Return contract with status: "ok", each ending with the contract's JSON block: playwright-cli --help video-chapter exiting non-zero (playwright-cli not installed); agent-device --version exiting non-zero (agent-device not installed); with <target> cdp and native_app set, <native> permissions answering ok: false (its reason); a settings file that exists but cannot be read (settings unreadable); with <target> web or cdp, no start_command after the merge (start_command unset); a mobile target whose app is unset or a placeholder, or a native_app left as a placeholder (incomplete settings); cancel at the candidate gate or the Setup gate (setup declined); --init with a settings file present (settings exist); .claude/demo.md, or .claude/demo.local.md when an account section is written, appearing between the Setup gate and its write (setup conflict); neither a readable plan nor a diff (nothing to demo); skip at the start-failure gate (dev server not ready); skip at the step-table gate (declined at step table); stop at the publish gate (declined at publish gate); on the first capture, the capture agent's second unparseable reply (no parseable capture result) or a result that fails the schema check (capture schema violation); the renderer rejecting steps.json (page rejected). Once the app has been started, every one of these runs § Procedure step 7 (Stop the app) before emitting the block.
The capture agent's reply is a return value: judge it and issue the next tool call at once. A later capture (a re-capture, or a capture for the publish gate's revise) is one more dispatch within § Procedure step 6 (Capture); its result is judged like the first capture's, except that a second unparseable reply or a schema violation keeps the earlier results instead of stopping. A capture with failed steps is not a stopping point. The data check's session is closed before the step-table gate on every path. Non-fatal outcomes are recorded and the run continues: a step marked failed, a later capture's (a re-capture's or a publish-gate revise's) second unparseable reply or schema violation, a missing recording, a mobile recording returned in several files (only the first is on the page), a recording that does not fit the page (it is left off), a screenshot or recording render.mjs cannot read (it is left out), fit-videos.mjs failing (the page goes without recordings), a missing or failing Artifact tool, .demo/ or .playwright-cli/ not gitignored, a process still listening after the stop, a native dialog still open after the stop's dismiss, a changed-files.txt that cannot be written (the run goes on without it), a stop_command that exits non-zero or times out, an environment left in place because <url> is remote and stop_command is unset, a seed or fixture file the data guide names that cannot be read (the guide counts as silent on it), an Edit at § Procedure step 9 (Data guide gate) that fails, an account placeholder or a failed re-read at the step-table gate, a credential source that cannot be read at § Procedure step 8 (Render and publish).
Settings
Two files: .claude/demo.md (shared by the team, committed) and .claude/demo.local.md (personal, gitignored). Each holds YAML frontmatter and, after its closing ---, an optional Markdown body. For the keys, the local file overrides the shared one key by key; a null or empty value in the local file clears the key.
The bodies, the shared one followed by the local one, read as one text: the data guide, prose in the resolved language saying where the seed or fixture files are, which accounts (identifier and role) and which main records they hold, and how one shell command line inserts a record the seed lacks. The shared body names where a credential comes from (a seed file, the local body, auth_state); a credential itself, or a personal insertion command, goes only in the local body. With <target> cdp or mobile, the guide also says what state the app keeps outside what the driver resets (a user data directory, the app's storage on the device) and how a run starts with it fresh (a throwaway user data directory in start_command, a reset_command, a case_reset command that clears it), or that it is kept on purpose (a signed-in profile). Where the guide is silent, the run finds the fixtures or seed itself. .claude/demo.md is the guide's write target, .claude/demo.local.md when it alone exists.
Target. <target> is the resolved target value, after the attach alias; every "with <target> X" below refers to it, not to the key as written in the file. mobile names ios and android together. <app> is the app key's value; <device> is the device key's value, or nothing; <open line> is open <app> --platform <target> <device>, run through agent-device; <ext>, the recording extension, is webm with web or cdp and mp4 with mobile; <native> is node "<base dir>/scripts/native.mjs" --app "<the native_app value>", with native_app set, followed by --tray-name "<the native_tray value>" when native_tray is set, and by --cdp "<url>" once § Procedure step 4 (Start the app) has resolved <url>. With mobile and no app, or an app that is a <…> placeholder Setup mode left → status: "error", reason: "incomplete settings: app is required with target ios or android", before anything is started; for the placeholder, say so in one line first. With <target> cdp and a native_app that is such a placeholder → status: "error", reason: "incomplete settings: native_app is a placeholder", said in one line first, before anything is started. Keys that have no meaning with the resolved target (url and auth_state with mobile; app and device with web or cdp; native_app and native_tray with web or mobile) are said in one line when set and ignored.
| Key | Default | Meaning |
|---|---|---|
target | web | web: a browser the run opens. cdp: a Chromium-based desktop app that exposes a DevTools endpoint on DEMO_PORT; the run attaches to it instead of opening a browser, and url, when set, is a URL: that endpoint's origin. ios / android (mobile): a native app on a simulator or emulator of that platform, driven with agent-device (app required). Any other value is treated as web and said in one line |
attach | none | cdp, with target unset: the same as target: cdp. Otherwise ignored |
app | none | The app's bundle identifier (iOS) or package name (Android) that agent-device open takes; required with mobile |
device | none | With mobile: the device selector agent-device takes, verbatim (--udid <id>, --device <name> or --serial <id>), appended to every agent-device boot and open. Unset: agent-device picks a booted device of that platform and fails when several match |
start_command | required with web or cdp | Starts the app, in the background, under sh -c with the environment below and its stdin held open, with ${DEMO_PORT} in the command text expanded to the port first. A local app listens on DEMO_PORT; a remote target names its URL in url. Optional with mobile |
reset_command | none | Runs once, in the foreground, before start_command, with the same environment and with ${DEMO_PORT} expanded the same way. Resets a throwaway environment, or builds and installs a mobile app. Bounded by ready_timeout seconds |
stop_command | none | Runs once, in the foreground, at the start of § Procedure step 7 (Stop the app), with the same environment. Stops or cleans up what start_command created; scripts/stop-app.mjs follows. ${DEMO_PORT} is expanded the same way. Bounded by ready_timeout seconds |
case_reset | unset | What runs before each test case's setup, after the browser opens or the run attaches (with mobile, before the app is opened). Unset: the built-in reset, by <target> — web: nothing beyond the fresh browser; cdp: every window's storage and cookies cleared and the window reloaded; mobile: <open line> --relaunch (the app restarted, its data kept). none: nothing (with mobile: <open line> without --relaunch); with target web it counts as unset. Any other value: a shell command line the capture agent runs as one Bash call with the environment below and DEMO_SESSION (the playwright-cli session name, or the agent-device session name with mobile) exported; a non-zero exit counts as a failed setup action |
url | none | Starting with http:// or https://: the URL itself, with ${VAR} expanded from the environment plus DEMO_PORT. Otherwise a command the wait re-runs, with the same environment, until it exits zero with a non-empty stdout line, within ready_timeout; that first non-empty line is the URL. With <target> cdp, only the URL form applies. No meaning with mobile |
ready_timeout | 120 | Seconds to wait for the URL to resolve and answer, or for agent-device boot and open to return, at most 590 |
port | none | When set, used as DEMO_PORT instead of a free port found at run time. Digits, or ${VAR} expanding to digits: the port itself. Otherwise a command run before the start with the same environment and DEMO_PORT=0; the first line of its stdout is the port. With mobile it only expands ${DEMO_PORT} and names what to stop |
auth_state | none | Storage state file passed to playwright-cli state-load after the browser opens or, with <target> cdp, after attaching and before the case's setup; over CDP the file's cookies are loaded, not its localStorage. No meaning with mobile |
native_app | none | With <target> cdp: the app's name as agent-desktop list-apps shows it. When set, a step's path may name the app's native UI as native:<surface> (§ Procedure step 3 (Derive the test cases)'s "Each step" paragraph). No meaning with web or mobile |
native_tray | none | With <target> cdp, on Windows: the name the taskbar shows for the app's tray icon; unset, the native_app value. No meaning with web or mobile |
error_cases | true | false: derive no error test cases. Any other value is true |
video | full | normal: error test cases are not recorded; their screenshots are still taken. Any other value is full |
Environment. Every command a key names runs as DEMO_PORT=<port> DEMO_BASE_REF=<base> DEMO_CHANGED_FILES=<changed files> <command> (the port command with DEMO_PORT=0); with mobile the prefix also carries DEMO_APP=<app> DEMO_TARGET=<target> after DEMO_CHANGED_FILES. <base> is Base ref as resolved in § Procedure step 2 (Inputs); <changed files> is .demo/<slug>/changed-files.txt, one path per line, written at the start of § Procedure step 4 (Start the app). That prefix is <environment> in § Procedure.
When neither file exists, or --init was given, read references/setup-mode.md and follow it. When a file exists but Read fails for any other reason, or when it cannot be told whether the file is missing or unreadable, stop with status: "error", reason: "settings unreadable: <path>" rather than entering Setup mode. With <target> web or cdp, when the merge leaves no start_command, stop with status: "error", reason: "start_command unset". <case reset> names what the case_reset row resolves to, its web rule for none applied first: default for the built-in reset, none for nothing, command for a command line; an empty or boolean value counts as unset.
Language
Language: or --lang, when given, is the language and nothing is read. Otherwise resolve it by reading only the language key from the YAML frontmatter of ~/.claude/dev-workflow.local.md, .claude/dev-workflow.md and .claude/dev-workflow.local.md, in that order, later files overriding earlier ones; a null or empty value clears it, and a missing file, or one without frontmatter, contributes nothing. If none sets it, take language from ~/.claude/settings.json; otherwise use ja. The page's fixed labels, the step table and every line written for the user follow the resolved language.
Model
Model: or --model is applied as the model parameter of the capture Agent dispatch. It is valid only if it is one of the ids the current Agent tool's model parameter accepts; check the tool's live schema in this session. A full claude-* id is not among its aliases and is invalid. An absent or invalid value is treated as sonnet.
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Procedure
<base dir> is this skill's directory as the harness reported it when the skill loaded.
-
Preconditions. Resolve the language per § Language and the model per § Model, then the settings per § Settings (Setup mode when neither file exists). Then check the driver, by
<target>:webandcdp: runplaywright-cli --help video-chapter. A non-zero exit stops withstatus: "error",reason: "playwright-cli not installed". When its output starts withplaywright-cli video-chapter,<chapters>=true; otherwise<chapters>=falseand say in one line that this version records without title cards, cursor or action callouts. With<target>cdpandnative_appset, also run<native> permissions; when its JSON hasok: false, say itshintin one line when there is one, then stop withstatus: "error"and itsreason.- mobile: run
agent-device --version. A non-zero exit stops withstatus: "error",reason: "agent-device not installed".
-
Inputs. With
Plan:,<slug>is the file name without.md;Readthe plan. When thatReadfails, use the plan text when it is already in this conversation; otherwise say in one line that the steps come from the diff alone and continue. WithoutPlan:,<slug>is<YYYYMMDD-HHMMSS>of now. Read the change set againstBase ref(defaultHEAD):git diff <base>and the content of filesgit ls-files --others --exclude-standardlists. No readable plan and an empty change set →status: "error",reason: "nothing to demo". Runmkdir -p .demo/<slug>. -
Derive the test cases. From the data guide (read with the settings in step 1),
Readthe parts of the seed or fixture files it names that name accounts and records; when it names none, find them asreferences/setup-mode.md§ Read the project does. Then, from the plan's After, Scope and Test plan and from the diff:- Features. List the behaviors a person would check on screen, then group them into features. A feature is the set of actions a checker performs in a row for one purpose; it does not follow the count of tasks or commits. Group when the actions handle the same data for the same purpose, or when one action uses what an earlier one created or changed. Split when the purpose differs, when a part can be checked on its own, or when a different role performs it. When unsure, group. A single feature takes the same shape. Each feature gets a letter (
Afor the first,Bfor the second, and so on), a name stating what the user can do and a one- or two-sentence description. - Test cases. Per feature, each test case has a title saying in one sentence what it checks, a precondition (the sign-in state and the data it needs), the
setupactions that bring the app to that precondition (from where § Procedure step 3's "Preconditions" paragraph says it starts; with<target>cdp, each action starts with the window it runs in as a step'spathnames one; with mobile, each action names the screen it runs on), and its steps. A case's id is the feature letter plus its order within the feature (A-1,A-2). Normal cases: the feature's main flow, usually one case (more when the main flow branches); 3–10 normal steps across all features. - Error cases, when
error_casesistrue. One test case per branch the diff implements (input validation, permissions, behavior that depends on state), each branch once; steps that prepare the branch belong to that case. Errors the diff does not implement (raised by the framework or by shared code) are not walked. There is no cap; when the error cases exceed 10, the gate shows their count and a time estimate (20–40 seconds per case) in one line. The expected result is the error text itself. - Preconditions. A case starts where the case reset leaves the app: with
<case reset>default, where the built-in reset thecase_resetrow defines leaves it; withnone, where the previous case left it, so itssetupfirst brings the app to a known screen (signs out when signed in, opens the start window) whatever that state is, since a later capture runs the case after a different predecessor; withcommand, as the command leaves it. State the app keeps outside its windows or screens counts as data an earlier case created. A case that needs a signed-in user gets there throughauth_statewhen it is set (not with mobile), otherwise throughsetupactions that sign in on the sign-in page with an account from the fixtures or seed as the data guide names them. Only when the diff changes sign-in itself (the code that creates or checks a session, the authentication settings, the account fields used to sign in, the sign-in page) does signing in become steps. A case that relies on data an earlier case created says so in its precondition, and the case order follows from it. An error case uses records that earlier cases do not change or delete; when they would, its data names a record of its own. A value that can be taken only once (a confirmation code consumed on use) is taken by the first step that needs it, with a script whose stepdatasayssave as <name>; each later step that needs it saysuse <name>in itsdata. - Credential source. A credential the data guide, a seed or a fixture holds (a password, a token, a key) is never written as its value into a
setupaction, an action, a step'sdataor ascript, here or in any later correction; it is written as its source: the file's path in backticks, followed, when the value sits under a heading in that file (the sign-in account section of a settings file), by that heading line in backticks. - Order and numbers. Every normal case, feature by feature, then every error case, feature by feature. A step's
nruns through all cases; screenshots are named after it. - Each step holds
n,case(its case's id), the page path (with<target>cdp, the window instead: a string its title or URL shows intab-list, or, withnative_appset,native:<surface>for a step on the app's native UI,<surface>one oftray(the tray menu),menu(an open menu),dialogandapp-menu, its action naming the item or button by its accessible name; with mobile, the screen instead: the heading or a labelsnapshot -ishows on it), the action (one imperative sentence), the expected result (one sentence), and the data it needs. The path names a page, a window, a native surface or a screen, nothing more. A state the app or its platform produces through on-screen operation (a filter, a selection, a sort order, a display mode) is reached by the operation that produces it, never written into the path by hand: as an earlier step of the case when the state lives in the page and is lost on opening the page again, insetupwhen the app keeps it across pages. When no operation can produce it, the path carries the state and the step's data sayssubstituted path, so the gate shows it; with<target>cdpor mobile, a window or screen path never carries such a state. The data is covered by the project's fixtures or seed as the data guide names them, created on screen by an earlier step, or inserted by a script written here in the way the data guide says, in that order of preference. A script's full text goes into the step table so the gate shows it. A step that creates a record on screen (a sign-up, a new item) fills its unique fields with values carrying<YYYYMMDD-HHMMSS>of now (for example an email address), so a second capture does not collide with the first. Nothing is cleaned up afterwards.
- Features. List the behaviors a person would check on screen, then group them into features. A feature is the set of actions a checker performs in a row for one purpose; it does not follow the count of tasks or commits. Group when the actions handle the same data for the same purpose, or when one action uses what an earlier one created or changed. Split when the purpose differs, when a part can be checked on its own, or when a different role performs it. When unsure, group. A single feature takes the same shape. Each feature gets a letter (
-
Start the app.
Write.demo/<slug>/changed-files.txt: the paths of the change set read in step 2 (Inputs), the changed files then the untracked ones, one per line, literal (an empty file when there are none).<port>is theportkey resolved as § Settings says (a command's first stdout line must be an integer from 1 to 65535; a non-zero exit or any other line goes to the start-failure gate below, which then shows the command's output) or, when unset, the output ofnode -e 'const s=require("net").createServer();s.listen(0,()=>{console.log(s.address().port);s.close()})'. Replace${DEMO_PORT}in thereset_command,start_commandandstop_commandtexts with<port>, then say in one line whichreset_commandandstart_commandare about to run (with mobile andstart_commandunset: that nothing is started). With mobile, runagent-device boot --platform <target> <device> --timeout <ready_timeout * 1000>first, passingtimeout: (ready_timeout + 10) * 1000on that Bash call; a non-zero exit goes to the start-failure gate below, which then shows its output. Whenreset_commandis set, run<environment> <reset_command>in the foreground, passingtimeout: (ready_timeout + 10) * 1000on that Bash call; a non-zero exit goes to the start-failure gate below, which then shows the reset output instead ofserver.log. Whenstart_commandis set,Writeits text to.demo/<slug>/start-command(Readit first when an earlier run left it), then run<environment> node "<base dir>/scripts/run-open-stdin.mjs" .demo/<slug>/start-command > .demo/<slug>/server.log 2>&1withrun_in_background: true.Readiness, by
<target>. With mobile: runagent-device --session demo-<slug>-check <open line> --relaunch --timeout <ready_timeout * 1000>, passingtimeout: (ready_timeout + 10) * 1000on that Bash call. A zero exit makes the app ready; neither<url>nor<base url>is defined. A non-zero exit goes to the start-failure gate below, which then shows the command's output and, whenstart_commandwas started, the last 20 lines ofserver.log. With<target>weborcdp: resolve the URL and wait for it in one call:<environment> node "<base dir>/scripts/wait-ready.mjs" --timeout <ready_timeout>with the options below, passingtimeout: (ready_timeout + 10) * 1000on that Bash call. Any HTTP response counts as ready, with--expectany response holding its text.- With
<target>web:--url "<value>"when theurlkey is a URL (its value expanded as § Settings says); when it is unset, the firsthttp://orhttps://URL inserver.log, elsehttp://localhost:<port>. - With
<target>web:--url-command '<value>'when theurlkey is a command, in single quotes so the shell does not expand$DEMO_PORTbefore the script runs; a'inside the value becomes'\''. - With
<target>cdp:--url "<origin>/json/list" --expect '"type": "page"', where<origin>is theurlkey when set (expanded as § Settings says, without a trailing/; a command value counts as unset and is said in one line), elsehttp://localhost:<port>, so the app counts as ready once it lists a window. - stdout
ready <url>→<url>is that value, or<origin>with<target>cdp. stdouttimeout→ the start-failure gate, which then also shows the script's stderr. Anything else (exit 2, a stdout of neither form, node itself failing) → the start-failure gate, which then shows the script's stdout and stderr. - With
<target>web,<base url>is<url>without query or fragment, with/appended unless it already ends with/. A path's URL is<base url>followed by the path without its leading/. With<target>cdp, a path names a window, and no<base url>is defined.
The start-failure gate (USER GATE): show the last 20 lines of
server.logand<port>, and askretry/skip.retryruns step 7 (Stop the app), then this step again from the boot (with mobile) orreset_command; there is no retry limit.skipruns step 7 and stops withstatus: "skipped",reason: "dev server not ready".Data check. Before anything is opened, note with its file and line each line of the data guide's sign-in account section (its heading in either language) whose whole value is still a
<…>placeholder. A record the steps rely on that the seed or fixture files the data guide names, or another persistent store the project keeps (an exported dataset), do not hold is a gap. Then, once the app is ready, read it in a separate session (playwright-cli -s=demo-<slug>-check, or with mobile theagent-devicesessiondemo-<slug>-checkthe readiness opened), by<target>. With<target>web: once per distinctsetup(nosetupcounts as one):open,state-load <auth_state>when set, perform thatsetup, reading each credential written as its source (§ Procedure step 3 (Derive the test cases)'s "Credential source" paragraph) from there (the data check runs nocase_reset), thengotothe URL of each distinct path of the cases that use it (read the snapshot it prints inline, or from the.playwright-cli/file it names), thenclose; asetupthat fails is noted on every case that uses it. With<target>cdpor mobile, nosetupis performed, and a window or screen still before asetupits cases perform (a sign-in screen) is not a gap;cdp:attach --cdp=<url>,tab-list, thentab-selecteach distinct window the steps name by a path other thannative:thattab-listshows and read its snapshot (a window not listed yet is not a gap either), thenclose; mobile:snapshot -iand read the first screen, thenclose, in one command line joined with;. With every<target>, a page that shows an error, a not-found, or an empty list where its step needs records is a gap too. For each gap, write an insertion script into the earliest step that needs the data, as in step 3. A page, window or screen that cannot be reached, or that fails for a reason data cannot explain, is noted on its step for the gate. -
Step-table gate (USER GATE). Show
<url>(with mobile,<target>and<app>), whetherreset_commandran, the features (letter, name, description), the test cases (id, kind, title, precondition,setup), the step table (number, case, path, action, expected result, data), one line per step whose data sayssubstituted pathnaming the state its path carries, the error-case count line when there is one, each placeholder the data check noted (file and line), with one sentence asking to write the value into that file first, thevideovalue, every data script in full, and what the data check changed or noted, in the resolved language. Say in one sentence thatrevisecan drop error cases and thaterror_cases: falseleaves them out altogether; then say in one more sentence what runs before each case'ssetupand that a re-capture runs it again — with<target>cdpandnative_appset, first that a native dialog left open, other than one in a window of its own or without a parent window, is closed; then, with<case reset>command, thecase_resetcommand verbatim (with mobile, followed by the app restarted with--relaunch); withnone, nothing but loadingauth_state(with mobile, the app opened again without--relaunch, as thecase_resetrow defines it); withdefaultand<target>cdpor mobile, the built-in reset as thecase_resetrow defines it, said of the running app (withdefaultand<target>web, a fresh browser opens and no sentence is needed). Askapprove(records asvideosays) /approve without video(screenshots only, nothing recorded) /revise/skip, and in the same question set ask whether a test case that fails for missing data or for how its steps were written may be corrected — its scripts, itssetupor its actions — and captured again, at most twice (yes/no); keep that answer as<recapture>.<video>is thevideovalue afterapprove, andnoneafterapprove without video. When the data check noted a placeholder, either approve answer andrevisefirst re-read the account section (found by its heading, not the noted line) and put the identifier now there into thesetupactions and steps; a placeholder still left, or a failedRead, is said in one line.revisetakes the user's corrections to the URL (or the app), the cases, the steps, the data or a script, applies them and shows the tables again. Whenrevisegives a credential as a value, say in one line to write it into the sign-in account section of.claude/demo.local.md.skipruns step 7 and stops withstatus: "skipped",reason: "declined at step table". After either approve answer, the only questions left are the publish gate in step 6, only when failures remain, and step 9 (Data guide gate), only when it has something to offer. -
Capture.
<session>=demo-<slug>;<capture prompt>by<target>:web:references/capture-prompt.md;cdp:references/capture-prompt-cdp.md; mobile:references/capture-prompt-mobile.md. Before each dispatch, delete the recordings of every case it captures, in onenode -ethat lists.demo/<slug>/withfs.readdirSyncand removes withfs.rmSyncevery file whose name starts with<id>.or<id>-.<close>isplaywright-cli -s=<session> close, oragent-device --session <session> closewith mobile. Dispatch oneAgent(subagent_type: general-purpose,modelper § Model,run_in_background: false); it reaches the app and records each case itself. The prompt is three fenced sections:--- TASK ---holds the text of<capture prompt>after its---rule, verbatim, with the placeholders it uses filled in:{{session}}(<session>),{{out_dir}}(.demo/<slug>),{{url}}(<base url>, or<url>with<target>cdp),{{chapters}},{{video}}(<video>),{{auth_state}}(auth_state, ornone),{{native}}(<native>, ornone),{{app}}(<app>),{{target}}(<target>),{{device}}(<device>),{{language}}and{{case_reset}}— the last with the<case reset>paragraph under the## Case resetheading of<capture prompt>, without its**label**:prefix, with<reset line>=export <the variable assignments of <environment>> DEMO_SESSION=<session>; <case_reset>substituted where the paragraph names it;--- STEPS ---holds the cases to capture as one JSON object{ "cases": [ { "id", "kind", "title", "precondition", "setup" } ], "steps": [ { "n", "case", "path", "action", "expected", "data", "script" } ] };--- RETURN ---holds one sentence: the reply ends with a single fenced JSON block and nothing after it.Pre-invocation reminder: the agent's reply is a return value, not a turn boundary. The next tool call after it returns is
<close>, issued by this same thread. See § No-Stall Principle.When the agent returns: run
<close>(its output is ignored). Take the last fenced JSON block of the reply and parse it. No block, or a block that does not parse → dispatch once more with the sentenceYour previous reply carried no parseable JSON block.appended to--- RETURN ---, then<close>again. A second failure on the first capture runs step 7 and stops withstatus: "error",reason: "no parseable capture result"; on a later capture it is handled as Later captures says. Schema check, before anything is written:stepsis an array holding eachnof the steps passed in this dispatch exactly once; each entry has astatusofokorfailed, a non-empty stringscreenshot(a barestep-NN.pngfile name; a path is reduced to its base name), a non-empty stringresult, an optional stringnote, and, on afailedentry, an optionalcauseofdata,stepsorapp. A violation on the first capture runs step 7 and stops withstatus: "error",reason: "capture schema violation"; on a later capture it is handled as Later captures says.Return-point no-stall reminder: regardless of outcome — every step
ok, somefailed, any non-error result — the next action,<close>, is issued in the next tool call. After the first capture and after a re-capture, the re-capture decision follows, or the publish gate when Later captures sends the run there; after a capture for the publish gate'srevise, the publish gate follows. See § No-Stall Principle.Later captures. A later capture dispatches only the given cases and their steps, together with every case they rely on for data, with the app still running and no
reset_command. Before it, the<YYYYMMDD-HHMMSS>in those cases' unique values is replaced with the current time. Its results replace those steps' earlier ones. A second unparseable reply or a schema violation keeps those cases' earlier results instead, and the run goes on to the publish gate.Re-capture.
<recapture count>is0on the first entry to this step. When<recapture>isyes,<recapture count>is below2, and a step isfailedwithcausedataorsteps(astepsfailure whosenotenames thecase_resetcommand is not re-captured): correct each case holding such a step —data: append an insertion script to the step'sscript;steps: read the step'snoteand the last 40 lines ofserver.log, then correct the case'ssetup, its actions, or the saved values it uses. Run a later capture of the corrected cases. When it returns a result that passes the schema check, add1to<recapture count>and decide again. When no re-capture is due (<recapture>isno, nodataorstepsfailure is left, or<recapture count>is2), go to the publish gate.Publish gate (USER GATE). When every step is
ok, skip it and go to step 7 (Stop the app). Otherwise show, per test case with a failure, its id and title and each failed step'sn, action, expected result, result, note, cause in words (missing data / how the steps were written / how the app behaved, in the resolved language) and screenshot path, and askpublish/revise/stop.publishgoes to step 7 with the results as they are; the page shows those steps as not confirmed.revisetakes the user's corrections to those cases, runs a later capture of only those cases, which does not count toward<recapture count>, and returns to this gate; there is no limit.stopruns step 7 and stops withstatus: "skipped",reason: "declined at publish gate". -
Stop the app. Full stop sequence (applies to every case), in this order:
- Before
stop_command: with mobile, runagent-device --session demo-<slug> close; agent-device --session demo-<slug>-check closeas one command line (its output is ignored; the simulator or emulator is left running); with<target>cdpandnative_appset, run<native> dismiss, and when its JSON hasopenabove 0, keep one line for the report,native dialog still open. - When
stop_commandis set, say in one line that it runs, then run<environment> <stop_command>in the foreground, passingtimeout: (ready_timeout + 10) * 1000; a non-zero exit or a timeout keeps one line for the report,stop_command exited <code>: <reason>orstop_command timed out: <reason>, where<reason>is the last non-empty stderr line cut to 80 chars, or(no stderr), and the stop goes on. - Run
node "<base dir>/scripts/stop-app.mjs" --port <stop port>, adding--pgid-file .demo/<slug>/start-command.pgidwhen step 4 has runscripts/run-open-stdin.mjsin this run. A non-emptylisteningor a non-nullnotein its JSON keeps one line for the report.
The lines kept are those of the last run of this step. The cases differ only in
<stop port>and in one report line:<url>is not resolved (the wait returned noready, or mobile):<stop port>is<port>; no further line.<url>'s host islocalhost,127.0.0.1or::1:<stop port>is the port named in<url>; no further line.- any other host (a remote target):
<stop port>is<port>. Whenstop_commandis unset, keep one line for the report saying the environmentstart_commandcreated was left in place; otherwise keep no such line.
- Before
-
Render and publish. Before writing, read the value each credential source in the approved cases and steps points at (§ Procedure step 3 (Derive the test cases)'s "Credential source" paragraph), and replace every occurrence of that value in each step's
resultandnotewith its source; a source whoseReadfails is left unreplaced and kept as one line for the report. When<video>isnone, skipfit-videos.mjs; no case gets avideo. Otherwise runnode "<base dir>/scripts/fit-videos.mjs" --dir .demo/<slug> --ext <ext> --ids <the approved case ids, comma-separated> --embed, passingtimeout: 600000on that Bash call: it takes each case's largest recording and writes one over its share of the page again, smaller, as<id>.small.<ext>when a compressor is found, and prints a JSON array with one entry per recording, holding itsid,video(the file to put on the page, or null),bytes,video_bytes,tool,outcome(fits,compressed,over,no-toolorfailed) anderror. A non-zero exit or output that does not parse gives no case avideoand keeps one line for the report with the first stderr line.Write.demo/<slug>/steps.json:title(the change in two to four words),dek(the plan's After sentence, or one sentence from the diff),url(<url>; omitted with mobile),target(<target>),features(each approved feature that still has a case, with itsletter,nameanddescription),cases(each approved case'sid,featureas its feature's position in that list,kind,titleandprecondition), andsteps(each approved step with itscaseid, merged with the agent'sstatus,result,noteandscreenshot). A case getsvideoset to thevideoof the entry whoseidis the case's id, when that entry exists and itsvideois not null; a case with no entry has novideo. Runnode "<base dir>/scripts/render.mjs" --steps .demo/<slug>/steps.json --out .demo/<slug>/index.html --lang <language> --embed. A non-zero exit stops withstatus: "error",reason: "page rejected: <first stderr line>"(the app is already stopped). Each case id in its stdout JSON'sdroppedkeeps one line for the report (its recording was left off to fit the page), and so does each file inmissing(it could not be read), and so does anoveroftrue(the screenshots alone fill the page, so publishing may fail). CallArtifactwithfile_path.demo/<slug>/index.html,iconcamera, anddescriptionone sentence naming the feature. Do not load the design skills: the page's layout and theming are fixed in the renderer. A missing or failingArtifactleavesurlnull; the page path still reports. Rungit check-ignore .demo .playwright-cli; when its output lacks either path, keep one line for the report asking to add.demo/and.playwright-cli/to.gitignore(this skill does not edit it outside Setup mode). -
Data guide gate.
<edited>is[]on entry. Build two candidates.<guide additions>: for each item § Settings lists for the data guide, what this run used that the guide does not state yet, one or two lines each, in the resolved language, without this run's own values (the timestamps, the records this run created); a line with a credential-like value (a password, a token, a key) carries where the value comes from instead of the value.<seed candidates>: the records the scripts of the normal cases'oksteps inserted, only when the guide names a seed file (the first, when it names several); draft the addition in that file's own idiom as a diff, from the seed file as read in step 3 (Readit when step 3 did not). When both candidates are empty, show no gate and go to step 10 (Report). Otherwise (USER GATE), in one question set, show the lines to append verbatim and askyes/no, and show the seed diff and askapply/decline, each only when its candidate exists.yesappends the lines at the end of the guide's write target withEdit.applyapplies the diff to the seed file withEdit. Nothing is committed. A failingEditis noted for the report and the run continues.<edited>holds the paths whoseEditsucceeded. -
Report. In the resolved language: the artifact URL (or the page path), the test case count and how many test cases are not confirmed, one line per test case with its id, title and confirmed / not confirmed, how many re-captures ran, and for each case they corrected, every script added in full and its
setupand actions as captured, the publish gate's answer when it was shown, one line per recordingfit-videos.mjsdid not return asfits—compressed: thetooland the size before and after;over: left off the page because it stayed over its share of the page, after thetoolcompressed it when there is one;no-tool: left off the page because no compressor was found, and thatffmpegonPATH(or, for an.mp4on macOS,avconvert) lets the next run compress it;failed: left off the page, with theerror—, the line kept whenfit-videos.mjsitself failed, thedropped,missingandoverlines, each case whose mobile recording came back in several files (the capture agent notes it on the case's first step; only the first file is on the page), the stop result (thestop_commandline when one was kept, thestop-app.mjsline when one was kept, and the native dialog line when one was kept), the gitignore line when there is one, the guide lines appended or that they were declined, and the seed file edited with a note that its change is uncommitted, or that it was declined. Then the return contract's JSON block.
Return contract
Emit a single fenced JSON block at the end of the response, matching:
{ "status": "ok" | "skipped" | "error", "reason": null | "<why>", "url": null | "<artifact url>", "page": null | "<path to index.html>", "cases": <n>, "steps": <n>, "failed": <n>, "edited": [ "<path>", ... ] }
cases, steps and failed are 0 when the capture did not run. failed counts steps. edited is always present: the paths § Procedure step 9 (Data guide gate) edited, [] on every path that does not reach it (Setup mode's own writes are reported by Setup mode, not here). Only one fenced JSON block appears in the response.
Sub-skill caller directive
When invoked as a sub-skill (i.e. via Skill(demo) from an orchestrator), the fenced JSON verdict block this skill emits is the structured return value of the skill's procedure — it is not a deliverable to the user, and emitting it does not terminate the orchestrator's turn. The same agent that ran this skill must immediately issue the next tool call dictated by the orchestrator's flow. Do not insert a prose summary, an acknowledgment, or a "shall I proceed?" sentence between the JSON verdict and the next tool call. Only one fenced JSON block — the verdict block — appears in the response, so callers can locate it unambiguously. The skill's own procedure is over; the orchestrator's procedure continues without pause.
Fallback
When the Agent tool is not on the tool surface, this thread runs the flow of <capture prompt> (§ Procedure step 6 (Capture)) itself, builds the same steps array, and continues at the schema check.
Dev Workflow Lite
/dev-workflow --init # Detect check/test commands, write settings, generate run-tests
/dev-workflow [--fast|--deep] [--artifact off|share|review] [--mob] <task> # Run the workflow
/dev-workflow --resume <state> [--fast|--deep] [--artifact off|share|review] [--mob] # Run the next subtask of a decomposed task
Nineteen phases, always in this order. § Difficulty and the skip table decides what is skipped and how Plan Review runs. User gates are listed in § User gates; nothing else asks the user a question.
Settings
Three files, YAML frontmatter only, merged lowest to highest: ~/.claude/dev-workflow.local.md, .claude/dev-workflow.md, .claude/dev-workflow.local.md. If none exists, tell the user to run --init and stop; a file with malformed frontmatter is skipped with a warning.
Merge rules per key, in order: null or an empty value in a higher layer clears the key; an absent key inherits; scalars replace; check_commands appends (lower first, duplicates removed); test_commands replaces as a whole list; hooks.on_complete appends.
| Key | Default | Meaning |
|---|---|---|
reviewer | ask-peer | Reviewer skill for Plan Review and Code Review. One of ask-peer / ask-claude / ask-codex / ask-gemini / ask-copilot / ask-agy; anything else uses ask-peer |
code_review | true | Whether Code Review runs |
polish_prose | true | Whether Polish Prose runs |
language | see below | Language of everything the user reads |
check_commands | none | Shell commands, run in order |
test_commands | ["Skill(run-tests)"] | Skill(<name>) entries, run in order |
hooks.on_complete | none | Skill(<name>) or shell command strings, run as Completion Hooks |
plan_artifact | off | off / share / review: publish the approved plan as a claude.ai artifact, along with the exchange that shaped it; review also waits for the team's comments. --artifact overrides per run |
commit_review_gate | diff | diff / crit: how each commit's diff is shown at Interactive Commits. crit opens the crit browser reviewer |
mode | solo | solo / mob. mob adds the stops and narration references/mob-mode.md defines for a junior navigator. --mob sets it for one run |
self_retrospective.feedback | none | Where Self-Retrospective posts its Findings: GitHub owner/repo, or a local directory path. Unset skips the phase |
timing.report_dir | none | Directory that also receives each run's timing report; the table is shown at Completion regardless |
subagent_model | {trivial: sonnet, simple: sonnet} | {tier: model} map; the resolved tier's entry becomes <model> for the reviewer, rules-review, tidy, demo, and background review agents. No entry → inherit |
workability_retrospective | enabled: true | enabled: false skips Workability Retrospective; backlog_dir (default .claude/improvements) holds its backlog files |
custom_instructions | none | Free-form development guidance followed at Create Plan, Implement, and Tidy and handed to both reviewers. .claude/rules/ and the user's explicit requests win on conflict |
language resolves as: merged settings → language in ~/.claude/settings.json → ja. Headings, phase names, commit messages, diffs, and paths stay as written; prose follows it, in plain words, one claim per sentence. Keys this skill does not read are named once at Load Settings and ignored.
Callee failure rule
When a Skill(...) call fails, retry once. If it fails again: for the reviewer skill, ask the user to pick switch reviewer / self-review inline / stop (a user gate); for any other skill, say so in one line, do that phase's work yourself, and continue; Skill(demo) is instead reported in its Demo line. Record skipped callees for Completion.
Difficulty and the skip table
The tier is assessed at Task Decomposition (references/tiers.md § Tier criteria) and re-checked at the end of Create Plan (its § Re-check after planning), where it can only rise. Trivial and Simple are the express lane; Moderate and Complex are the full lane.
| Phase | Trivial | Simple | Moderate / Complex |
|---|---|---|---|
| Task Decomposition proposal | no | no | yes |
| Plan Review | skip | per run mode | per run mode |
| Tidy | skip | skip | run |
| Polish Prose | skip | skip | run (unless polish_prose: false or --fast) |
| Rules Compliance Review | skip | skip | run |
| Code Review | skip | run (unless code_review: false) | run (unless code_review: false) |
| Update Rules | gate only | gate only | run |
Run mode comes from the flags: --fast, --deep, or neither (normal). Both flags together is a fatal error. normal: Plan Review runs in rules-only scope. deep: Plan Review runs in full scope. fast: Plan Review and Polish Prose are skipped. Nothing else reads the run mode.
No tier skips a phase absent from the table. A skipped phase is marked completed with the description skipped: <tier> tier, skipped: <key>: false, or skipped: fast mode.
User gates
The only places the workflow waits for the user:
- Task Decomposition: the split proposal and, on resume, the subtask picker when more than one is runnable.
- Plan Approval: the browser review (
approve/revisewith comments, and the branch choice) when a local browser is reachable; otherwise the chat replies Phase 5 (Plan Approval) lists, with the one-line read-back before a swap or rewrite is applied. A wrong-branch request waits for uncommitted changes to be committed or stashed. Withplan_artifact: review, the wait for the team's review. - Check / Test: after 3 failed fix rounds the workflow stops and reports; a check command that rewrote files outside the task beyond trivial formatting, or a test skill's EXECUTION_ERROR, stops for the user.
- Code Review: findings still unresolved after the passes, asked once.
- Verify Fixes: rule violations still present after the second scoped pass, asked once.
- Interactive Commits: the stashing-hook question when a pre-commit hook exists and the plan has two or more commits; the commit plan; then each commit (
accept/adjust/cancel, or the crit browser's approve / comments);fold/deferwhen a pre-commit hook modified files;continue/stopwhen the user made a behavioral edit during a gate. - Update Rules: the confirm-remaining-steps question covering the rule and retrospective phases, with the
demo/no-demoquestion when demo is set up (then the demo skill's gates ondemo), then the rule commit. - PR Rule Extraction: which PR to read (an empty answer declines), then the rule commit.
- Self-Retrospective: the preview of the Findings before posting (
approve/edit/skip). - Workability Retrospective: the candidates' dispositions (
apply/backlog/skip), then the commit of its results. - Completion (decomposed runs only): the disposition of each work item left in prose, then the finished subtask's PR: an optional URL, or
submit/laterwhen stacked.
In mob mode, references/mob-mode.md § Learning stops adds the per-unit diff review, the plan-building checkpoints, and the post-commit-note question to this list. The collect wait of references/review-launch.md § Collect is a harness-tracked boundary, not a gate. Everywhere else, judge callee results yourself and issue the next tool call immediately. A question, a comment, or an instruction about how to run (including one to proceed without asking) is never approval: say what the gate needs and wait. No reply waives a later gate.
Timing
Phase starts, ends, and waits are marked per references/timing.md; Completion renders the table.
Workflow artifacts
Files this workflow writes as its own state are excluded from every diff, review payload, and commit: .claude/plans/**/<slug>.md (the plan), .claude/plans/dev-workflow.<slug>.md (decomposition state), .claude/plans/rules-candidates-<date>.md, .claude/plans/timing-*.jsonl, every other .claude/plans/<slug>.* staging file or directory (.plan-review.*, .figures.md, .story.json, .artifact.html, .dialogue.md, .absorb/, .retrospective.md), and the git-side state refs/dev-workflow/<slug>*, .git/dev-workflow.index, .git/dev-workflow.start.index, .git/dev-workflow-wt. Everything else under the working tree is the task's.
Mode detection
--init → read references/init-mode.md and follow it; the session ends there. --resume <state> → Resume sub-mode. Otherwise Normal sub-mode. Other flags combine with either sub-mode; --init ignores them.
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Phase 1: Load Settings
-
Run
pwd; confirm the repository root. Abort ifgit symbolic-ref -q HEADexits non-zero (detached HEAD).<base dir>= this skill's directory as the harness reports it; never hardcode it. -
Start the timing log (
references/timing.md§ Events,--event start --newfor this phase). -
Record
<base-commit>=git rev-parse HEAD. Every later diff is against it. Whentest -d .gitfails (a linked worktree), the snapshot chain ofreferences/snapshots.mdis not built and no<start-tree>is recorded. Otherwise record<start-tree>= the working tree as it stands, in a throwaway index:GIT_INDEX_FILE=.git/dev-workflow.start.index git read-tree HEAD GIT_INDEX_FILE=.git/dev-workflow.start.index git add -A GIT_INDEX_FILE=.git/dev-workflow.start.index git write-tree # → <start-tree>A non-zero exit anywhere records no
<start-tree>: say so in one line and continue. -
Load and merge the settings; resolve the run mode, the
--artifactoverride, andmode; emitOutput language: <value>,Run mode: <value>, andMode: <value>. In mob mode, readreferences/mob-mode.mdnow; in solo mode never open it. -
Register the nineteen phases with
TaskCreate, subjects = the## Phase N:headings below minus the prefix. Mark eachin_progresson entry andcompletedon exit in the same tool-call burst as the phase's first or last action. Mark the phases skipped by settings or run modecompletedhere; tier-derived skips are marked at Task Decomposition. NoTaskCreate→ skip every row step; emitPhase: <name>on each entry.
Phase 2: Task Decomposition
- Resume sub-mode: read
references/decomposition-state.mdand follow its § Resume. The selected subtask becomes the effective task; readreferences/tiers.mdand assess the tier from it. - Normal sub-mode: read
references/tiers.mdand assess the tier. On the full lane, readreferences/decomposition.mdand follow § Propose a split; once accepted, take the first subtask as the effective task. On the express lane, or onno, the effective task is the request itself.
Emit one line: the tier and the phases it skips. Mark the skipped rows. Resolve <model> = subagent_model[tier] (unset → inherit). In mob mode, apply references/mob-mode.md § Other differences to the split proposal.
Phase 3: Create Plan
No code changes until Plan Approval passes.
- Read the files the task touches. Use Glob / Grep / Read directly.
- Draft the plan per
references/plan-format.md: the body under## Plan, sections as###, in the orderreferences/plan-format.mddefines. Express-lane plans use the compact shape defined there. - Follow
custom_instructionswhen set. Simplicity self-audit: every element traces to an explicit requirement, a known bug or constraint, a rule under.claude/rules/, orcustom_instructions. Drop what does not, or add a one-line rationale. Verify every "already exists / reuses X" premise from the source. If the work splits into independently verifiable units and was not decomposed, say so in Risks. - Re-check the tier against the drafted plan (
references/tiers.md§ Re-check after planning): if it rises, say so in one line, reopen the rows the new tier runs, and re-resolve<model>. - Do not show the plan yet. In mob mode, this phase runs as
references/mob-mode.md§ Design dialogue and writes its § Plan shape.
Phase 4: Plan Review
Skipped on Trivial and in fast mode. One pass, no loop.
- Full scope (
deep): callSkill(<reviewer>)withModel: <model>, the full plan body,custom_instructionswhen set, the Decisions shape (Question / Recommendation / optional Alternative), and three review units: scope, feasibility, dependencies,.claude/rules/compliance (the reviewer lists and reads.claude/rules/**/*.md); the simplicity self-audit's conclusions; approach and alternatives, completeness, cross-section consistency. Ask the reviewer to report every finding it has, including uncertain or low-severity ones, each with a confidence level and a severity, and not to filter for importance itself; when it has none, the words "No actionable findings". Rules-only scope (normal): resolve the reading list yourself — every*.mddirectly under.claude/rules/plus subdirectory files whose domain the plan touches — and callSkill(<reviewer>)withModel: <model>, the plan body, that numbered list, and one unit:.claude/rules/compliance only, reading exactly the listed files and no other tool; anything it cannot confirm goes under an "unverified items" heading. If the glob finds no rule files, do not dispatch: say the review found no project rules to check and continue. - Apply findings you agree with; reject the rest with one line each. Do not ask the user about individual findings. Do not re-dispatch, with one exception: when Critical ≥ 3 or Critical + Major ≥ 10 and a finding proposes an approach-level alternative, rewrite the plan around it and dispatch one more pass.
- Unresolved points are carried to Plan Approval as a short list. In mob mode, review through
references/mob-mode.md§ Plan shape's lenses and explain applied findings.
Phase 5: Plan Approval
USER GATE. Read references/plan-approval.md.
- Write the plan to
.claude/plans/<slug>.md(mkdir -p .claude/plans). Slug: ASCII kebab-case of the effective task,-2,-3on collision with a prior run's file; resolved once per run. - Browser gate when
printenv CLAUDE_CODE_REMOTEis nottrue: followreferences/browser-gate.md. Itsapprove→ step 4;rewrite-approach→ rewrite the plan, re-run Plan Review once unless skipped this run, re-enter this phase;wrong-branch→ § Branch action's "Wrong branch" paragraph;fallback→ step 3. - Chat gate (remote sessions, or fallback): present the plan per § Chat gate unless fallback brought a reply. Classify the reply: approve → step 4. swap (named Decisions items) → read back in one line, wait, swap Recommendation and Alternative on those items, re-present. rewrite (Approach, Build order, or Scope changed) → read back, wait, rewrite the plan, re-run Plan Review once unless skipped this run, re-present. wrong branch (another branch to work on) → § Branch action's "Wrong branch" paragraph. withdraw → stop; leave the plan file. Anything else → ask; never advance.
- Plan artifact: when the resolved
plan_artifactisshareorreview, readreferences/plan-artifact.mdand follow it.reviewholds at its team-review gate (USER GATE) until the user says the team is done. - Run § Branch action, then Implement.
In mob mode, references/mob-mode.md § Plan Approval adds the plan narration.
Phase 6: Implement
- Before the first edit, list the plan's user-side manual actions (external config, keys, probes) in one block.
- Follow Build order in sequence, and
custom_instructionswhen set. Read each file immediately before editing it. Content the user deleted earlier in the session never comes back. - A write to a path not in
git ls-filesmust resolve inside the repository, under the directory the plan names for that kind of file; otherwise skip the edit with a one-line note. - If a file outside the plan must change, add it to Build order first, then edit, and say so in one line.
- After the last edit of each Build order step, take that step's snapshot per
references/snapshots.md§ Snapshot at a Build order step boundary (before step 1's snapshot, delete a leftoverrefs/dev-workflow/<slug>from an earlier run). - After the last edit,
git add -N -- <path>for each new file outside § Workflow artifacts.
In mob mode, each Build order step runs as a unit per references/mob-mode.md § Per-unit review, with its diff review after the snapshot.
Phase 7: Tidy
Express lane skips. Call Skill(simplify); if unavailable, Skill(tidy) with no base ref and Model: <model>; pass custom_instructions as context when set. Either edits the tree itself. Correcting a false comment means replacing it with the shorter true statement. From here on, no review layer grows a comment: a finding whose fix adds, lengthens, or restores a comment is rejected with that reason. In mob mode, explain any cleanup per references/mob-mode.md § Tidy.
Phase 8: Polish Prose
Express lane skips; polish_prose: false and fast mode skip. Run node "<base dir>/scripts/polish/changed-lines.mjs" --base <base-commit>; it prints File: and Changed lines: for this run's changes. If it prints nothing or fails, skip. Otherwise call Skill(prose-polish) with that output and Language: the resolved language. done / no-change / error all continue.
Phase 9: Check / Test
- The first time in this run, set
review_fix_files = ∅. - Run
check_commandsin order. The first failure in step 2 or 4 stops the pass. - The first time in this run they all pass (pre-existing failures aside), launch the reviews per
references/review-launch.md§ Launch, without waiting. - Run
test_commandsin order. ASkill(<name>)entry is called with--base-commit <base-commit>; it returns SUCCESS / TEST_FAILED / EXECUTION_ERROR. EXECUTION_ERROR uses no fix round: report its reason and wait (USER GATE) forretryorstop(ends the run as step 6 does). - Classify each failure. A failure whose failing test and failing code both lie outside the files changed since
<base-commit>is pre-existing: record it, do not fix it, do not count it. If the workflow's own fix (Tidy, a review fix) broke a test that passed before, correct that fix rather than the implementation. - Fix and rerun. At most 3 fix rounds per entry into this phase. After the third, stop: report the command, its last output, and that nothing was committed.
- When a check command rewrites files outside the task's changed set beyond trivial formatting (whitespace-only at any size, or ≤ 5 comment lines), warn and stop; never revert its output silently.
In mob mode, narrate every failure per references/mob-mode.md § Check / Test before fixing it.
Phase 10: Rules Compliance Review
Express lane skips. Take the background result per references/review-launch.md § Collect when it is fresh; otherwise call Skill(rules-review) with --base-commit <base-commit> and Model: <model>. Fix every reported violation; when a violation is a pattern rather than a one-off, grep the file for the defining token and fix every match. A rule-doc-drift classification gets no code fix; note it for Update Rules. Record edited files in review_fix_files. Do not rerun Check / Test here.
Phase 11: Code Review
Skipped on Trivial and when code_review: false. Take the background result per references/review-launch.md § Collect when it is fresh; otherwise run step 1.
- Call
Skill(<reviewer>)withModel: <model>,git diff <base-commit>, the content of untracked new files labeled as such,custom_instructionswhen set, Phase 7's no-comment rule as a standing rejection criterion, the three categories (correctness and edge cases; conventions and consistency including a light.claude/rules/check; simplicity and maintainability), the current subtask and its siblings when a decomposition state is active, and Plan Review's finding-reporting instruction. - Fix genuine findings; reject the rest with one line each. If the user would plausibly raise the point themselves, fix it. Duplicates of Rules Compliance findings are skipped. After a Critical fix, sweep the diff for the same defect class. Record edited files in
review_fix_files. - Escalation: exactly one more pass when this pass had at least one Critical finding and at least one fix was applied. The escalation pass scopes to the changes since the first pass. It never triggers a third.
- Findings still unresolved after the passes go to the user once (USER GATE). Fixes made there also enter
review_fix_files.
In mob mode, predict and cross-check per references/mob-mode.md § Code Review.
Phase 12: Verify Fixes
If review_fix_files is empty, skip this phase. Otherwise run Check / Test once (3 fix rounds apply; files they edit join review_fix_files). Then, if Rules Compliance Review ran, call Skill(rules-review) with --base-commit <base-commit>, Files: <review_fix_files>, and Model: <model>. Fix violations once; a second scoped pass over the newly fixed files is the last; violations still present go to the user (USER GATE).
Phase 13: Completion Hooks
Skipped when hooks.on_complete is unset, or with a one-line note when the tree has no task-derived changes. Run entries in list order: Skill(<name>) as a skill, anything else in Bash. When a decomposition state file is active, do not run an entry that would move or delete it; say so. A failing entry is reported and the rest still run. If any entry wrote to the tree, run check_commands once.
Phase 14: Interactive Commits
USER GATE. When the snapshot chain exists, first absorb the review layers' edits into it per references/snapshots.md § Absorb review fixes. Then read references/commits.md and follow § Procedure. Set landed_count = 0 on entry. Never git push.
In mob mode, add the per-commit note and the already-reviewed accept variant per references/mob-mode.md § Commits.
Post-commit verification: when gate adjustments edited any file, run Check / Test once after the last commit and offer those edits as one extra commit (pathspec = the edited paths minus § Workflow artifacts); skip it after a mid-loop cancel.
Phase 15: Update Rules
- USER GATE, on every tier. List the remaining enabled phases — this extraction (full lane only), Self-Retrospective, Workability Retrospective, PR Rule Extraction (always) — and ask
proceed/session-only/pr-only/skip(proceed/skipwhen only one side — session-derived or PR-derived — is listed).skipmarks all listed completed unrun;session-onlymarks PR Rule Extraction so;pr-onlymarks the session-derived ones so. If.claude/demo.mdor.claude/demo.local.mdexists, the gate also asksdemo/no-demo.demo, whatever the first answer, callsSkill(demo)withPlan:the plan's current path (.claude/plans/**/<slug>.md),Base ref: <base-commit>,Language:the resolved language,Model: <model>. Its Demo line for Completion:ok→ the URL or page path with the step and failed counts and any files it edited;skipped/error→ thereason; no parseable JSON block →no parseable result, without retry. Express lane: steps 2–3 do not run. - Call
Skill(extract-rules)with--from-conversation, unless ahooks.on_completeentry containsextract-rules(it already extracted). If the diff introduced a new framework, library, pattern, or API convention and no conversation extraction ran, use--updateinstead. If extract-rules is unavailable, write the session's reusable patterns to.claude/plans/rules-candidates-<YYYY-MM-DD>.mdand tell the user. - Rule commit (USER GATE): run the § Rule commit gate procedure of
references/commits.mdover uncommitted paths under.claude/rules/,.claude/rules-extras/,.claude/rules-staging/(or the dirs.claude/extract-rules.local.mdsets). Skip when there are none.
Phase 16: PR Rule Extraction
Skipped when the Update Rules gate skipped it. USER GATE. Ask which reviewed PR to extract rules from, naming the accepted forms (a number, owner/repo#N, a 100..110 range, a URL, several separated by spaces); an empty answer declines. On an answer, call Skill(extract-rules) with --from-pr <answer verbatim>. "Nothing qualified" and "no human comments" are success; a pre-flight error is noted and skipped. Then run the § Rule commit gate procedure again over what it wrote.
Phase 17: Self-Retrospective
Skipped when self_retrospective.feedback is unset or the Update Rules gate skipped it. Read references/self-retrospective.md and follow it; its preview is a USER GATE. Nothing here edits a skill.
Phase 18: Workability Retrospective
Skipped when workability_retrospective.enabled is false or the Update Rules gate skipped it. Read references/workability.md and follow it; its dispositions are a USER GATE.
Phase 19: Completion
- Summary in the resolved language: what was done, files changed, check/test result, review outcomes, rules updated, commits made, the Demo line when one exists, the Self-Retrospective and Workability lines, the timing table per
references/timing.md§ Report, and one line per phase skipped or stopped early. List skipped callees and any uncommitted rule files. - Decomposed runs: read
references/decomposition-state.mdand follow its § Finish a subtask; its PR question is a USER GATE. - In mob mode, add the learning summary and the paired resume commands per
references/mob-mode.md§ Completion. - Delete this run's staging state:
rm -feach existing staging file listed in § Workflow artifacts (named paths, no globs),rm -rf .claude/plans/<slug>.absorb, andgit update-ref -don eachrefs/dev-workflow/<slug>*ref. Never delete the plan file (hooks.on_completeowns archiving) or the decomposition state file (step 2 owns it).
Extract Rules
Analyzes existing codebase to identify what Claude would get wrong without project-specific guidance, extracting coding rules and domain knowledge as structured markdown documentation for AI agents.
Usage
/extract-rules # Extract rules from codebase (initial)
/extract-rules --update # Re-scan and add new patterns (preserve existing)
/extract-rules --restructure # Re-analyze, reorganize structure, merge existing rules
/extract-rules --from-conversation # Extract from current session (latest)
/extract-rules --from-conversation <session-id> # Extract from a specific session
/extract-rules --from-pr 123 # PR in current repo
/extract-rules --from-pr owner/repo#123 # PR in another repo (URL form also accepted)
/extract-rules --from-pr 100..110 # PR range (current repo)
/extract-rules --from-pr owner/repo#100..110 # PR range (another repo)
/extract-rules --compact # Compact all over-threshold rules files (output_dir/**/*.md)
/extract-rules --compact path/to/file.md ... # Compact specific files (caller passes explicit paths)
/extract-rules --realign # Re-judge every rule file under output_dir against current criteria
/extract-rules --realign path/to/file.md ... # Re-judge only the named files
/extract-rules --apply-conversation-candidates <path> # Apply pre-scanned rule candidates (Step C5 only; orchestrator sub-skill)
# Multiple specs allowed (space-separated) → cross-analysis detects org-wide principles
Change-origin flags: a change-based extraction is scoped only by --from-conversation or --from-pr. This skill accepts no diff-base / commit-sha origin argument such as --base-commit <sha>; passing one is unsupported.
Configuration
Settings file: extract-rules.local.md (YAML frontmatter only, no markdown body)
- Project-level:
.claude/extract-rules.local.md(takes precedence) - User-level:
~/.claude/extract-rules.local.md
| Setting | Default | Description |
|---|---|---|
target_dirs | ["."] | Analysis target directories |
exclude_dirs | [".git", ".claude"] | Exclude directories (in addition to .gitignore) |
exclude_patterns | [] | Exclude file patterns (e.g., *.generated.ts, *.d.ts) |
output_dir | .claude/rules | Output directory for rule files (.md and .local.md) |
examples_output_dir | .claude/rules-extras | Output directory for .examples.md files. Defaults to a sibling directory outside .claude/rules/** so examples are not auto-loaded into context on session start. Set to output_dir (or any path under output_dir) to opt examples back into auto-load |
staging_output_dir | .claude/rules-staging | Output directory for 1st-observation project-level patterns staged by incremental modes. Defaults to a sibling directory outside .claude/rules/** so staged candidates are not auto-loaded into context on session start. Set to output_dir (or any path under output_dir) to opt staging back into auto-load. Staging gating and the promote path: references/conversation-mode.md § Step C5 and § Mode interaction summary. Also holds lint-candidates.md (references/audit-pass.md § Lint candidate writes) |
language | ja | Report language (e.g., ja) |
split_output | true | Separate Principles (.md) and patterns (.local.md) |
resolve_references | true | Resolve file references during restructure |
compaction_threshold | 40000 | Char count threshold for --compact mode (file is compacted if char count exceeds this). Set to a very large number (e.g. 99999999) to opt out of compaction. The default 40000 matches Claude Code's per-file warning threshold (40k chars, observed in Claude Code 2.1.x) — firing the gate exactly at the warning matches the user's visible signal that the file needs attention (buffer 0). |
min_cluster_size | 3 | Minimum related-bullet cluster size for --compact mode's consolidation detection. The subagent emits consolidation_proposals only when a cluster has at least this many related bullets. Set to a very large number (e.g. 99999999) to disable consolidation while keeping compaction |
---
target_dirs:
- .
exclude_dirs:
- .git
- .claude
exclude_patterns:
- "*.generated.ts"
output_dir: .claude/rules
examples_output_dir: .claude/rules-extras
staging_output_dir: .claude/rules-staging
language: ja
split_output: true
resolve_references: true
compaction_threshold: 40000
min_cluster_size: 3
---
Output Structure
Three output directories are involved: output_dir for rule files (.md / .local.md), examples_output_dir for .examples.md files, and staging_output_dir for staged 1st-observation project-level patterns and lint candidates from incremental modes. The paths: frontmatter on rule files is a human-facing category-scope hint; the auto-load boundary is determined by directory placement only.
Default (split_output: true):
.claude/rules/ # output_dir (inside auto-load scope)
├── languages/
│ ├── typescript.md # Principles only (portable)
│ └── typescript.local.md # Project-specific patterns only
├── frameworks/
│ ├── react.md # Principles only (portable)
│ └── react.local.md # Project-specific patterns only
└── project.md # Always single file (no split)
.claude/rules-extras/ # examples_output_dir (outside auto-load scope)
├── languages/
│ └── typescript.examples.md # Examples for both
├── frameworks/
│ └── react.examples.md # Examples for both
└── project.examples.md # Examples
.claude/rules-staging/ # staging_output_dir (outside auto-load scope)
├── project.staging.local.md # 1st-observation project-level candidates (incremental modes only)
└── lint-candidates.md # rules a check this project runs could enforce (incremental modes only)
Principles (portable across projects) and Project-specific patterns (local) are separated by default.
Hybrid mode (split_output: false): no <name>.local.md — each <name>.md carries both ## Principles and ## Project-specific patterns. The other two directories are unchanged.
Layered frameworks (Rails, Django, Spring, etc.): When a framework has distinct architectural layers, generate layer-specific files:
<framework>.md— Cross-layer rules (nopaths:or broad scope)<framework>-<layer>.md— Layer-specific rules with scopedpaths:(e.g.,app/models/**)- In split mode, both cross-layer and layer-specific files get
.local.mdcounterparts
Integration libraries (Inertia, Pundit, Devise, Turbo, etc.): When integration libraries are detected alongside a layered framework:
integrations/<framework>-<integration>.md— Integration-specific rules- Separated from layer files into dedicated
integrations/directory - In split mode, integration files also get
.local.mdcounterparts
Format switching: Run --restructure after changing split_output setting to switch between split and hybrid formats.
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Processing Flow
Mode Detection
Check arguments to determine mode:
- No arguments → Full Extraction Mode (Step 1-7)
--update→ Update Mode (Step U1-U6)--restructure→ Restructure Mode (Step R1-R5)--from-conversation [session-id]→ Conversation Extraction Mode (Step C1-C5)--compact [<paths>]→ Compaction Mode (Step CP1-CP5)--realign [<paths>]→ Realign Mode (Step RA1-RA5)--from-pr <number|owner/repo#number|range> [...]→ PR Review Extraction Mode (Step P1-P5)--apply-conversation-candidates <path>→ Conversation Candidate Apply Mode (Step A1-A2)
Full Extraction Mode
Step 1: Load Settings
Search for extract-rules.local.md:
- Project-level:
.claude/extract-rules.local.md - User-level:
~/.claude/extract-rules.local.md
Priority:
- If both exist, use project-level only
- If only one exists, use that file
- If neither exists, use default settings
Extract settings (target_dirs, exclude_dirs, exclude_patterns, output_dir, examples_output_dir, staging_output_dir, language, split_output, resolve_references, compaction_threshold) from the config file. See Configuration section above for defaults.
language resolution: skill config → Claude Code settings (~/.claude/settings.json language field) → default ja. Write the report's prose in plain words, one claim per sentence, with no figure of speech translated word for word.
Load existing rule files (incremental modes; Full Extraction skips it): read <output_dir>/<name>.md, <output_dir>/<name>.local.md, and <examples_output_dir>/<name>.examples.md. When examples_output_dir does not exist yet (legacy projects that co-located examples under output_dir), use <output_dir>/<name>.examples.md instead. Also read <staging_output_dir>/project.staging.local.md when present — the staging-match branch needs it; skip silently when it does not exist.
Step 2: Detect Project Type
Detect project language and framework:
1. Detect languages by config files (package.json, tsconfig.json, pyproject.toml, go.mod, Cargo.toml, Gemfile, pom.xml, etc.) and file extensions (.ts/.tsx, .py, .go, .rb, etc.)
2. Detect frameworks by their config files (e.g., next.config.*, playwright.config.*) and dependencies in package manifests.
3. Detect architectural layers (for layered frameworks):
If a framework has distinct layers with separate directories (e.g., Rails: app/models/, app/controllers/; Django: models.py, views.py), detect them for layer-specific rule files. Only split when corresponding directories actually exist.
4. Detect integration libraries (for layered frameworks):
Read references/integration-criteria.md for detection rules and classification criteria.
Output: List of detected languages, frameworks, architectural layers, and integration libraries
Step 3: Collect Sample Files
Collect target files for analysis:
- Get git-tracked files using
git ls-files(respects.gitignore). If not a git repo, use Glob instead, with manual exclusions from settings. - Filter by
target_dirs,exclude_dirs,exclude_patterns, and detected language extensions - Sample 10-15 files per category, distributed across directories for representative coverage. Large projects (100+): prioritize directory diversity. Small projects (<10): analyze all files.
Step 4: Analyze by Category
Read references/extraction-criteria.md before proceeding to understand the classification criteria. The core question for every pattern is: "Would Claude produce something different without knowing this?" — extract only what fills the gap between Claude's general knowledge and this project's actual conventions.
For each detected language, framework, and integration library:
- Use Grep/Read to collect relevant code patterns
1.5. Separate integration-specific patterns (for layered frameworks with integrations):
See references/integration-criteria.md "Pattern routing" section.
-
Classify each pattern (see
references/extraction-criteria.md):- General style choice (uses only language built-ins) → Abstract principle + hints
- Project-defined symbol (types, functions, hooks defined in project) → Include concrete example
-
For general style patterns:
- Group related patterns (e.g., "prefer const", "avoid mutations", "use spread" → Immutability)
- Formulate as principle with parenthetical implementation hints (2-4 keywords)
-
For project-specific patterns:
- Extract only the minimal signature (type definition, function signature, or API combination)
- Format as one line:
signature- brief context (2-5 words) - Avoid multi-line code blocks
-
Apply AI judgment to determine which patterns meet the extraction criteria (see
references/extraction-criteria.md)
Determine appropriate detection methods based on language and project structure.
Step 5: Analyze Documentation and Existing Rules
Also analyze non-code documentation:
- README.md
- CONTRIBUTING.md
- PR templates
- Existing CLAUDE.md
Extract explicit coding rules and guidelines from these documents.
Deduplication check: Read any files under .claude/rules/ to build a set of already-documented rules. Rules extracted in Step 4 that overlap with these existing rules should be skipped. Note: CLAUDE.md is NOT a deduplication source — rules should exist in .claude/rules/ even if also mentioned in CLAUDE.md. This check applies to every mode that extracts new rules.
Step 6: Generate Output
Read references/security.md before generating output to ensure sensitive information is not included.
-
Check if
output_direxists- If exists: Error "Output directory already exists. Use
--restructureto reorganize,--updateto add new patterns, or delete the directory manually to start fresh." - If not exists: Create
output_dir. Also createexamples_output_dirif it differs fromoutput_dirand does not exist yet (when both resolve to the same path the single directory created above is reused).
- If exists: Error "Output directory already exists. Use
-
Generate rule files per category. Rule files (
<name>.mdand<name>.local.md) are written underoutput_dir;<name>.examples.mdfiles are written underexamples_output_dir.languages/<lang>.mdfor language-specific rules (underoutput_dir)frameworks/<framework>.mdfor framework-specific rules (underoutput_dir)project.mdfor project-specific rules (underoutput_dir)- Layered frameworks:
<framework>.md(cross-layer) +<framework>-<layer>.mdper detected layer with scopedpaths: - Integration libraries: See
references/integration-criteria.md"Output structure" section.
By default (
split_output: true): Generate 3 files per category (except project which gets 2):<output_dir>/<name>.md—## Principlesonly (portable), withpaths:frontmatter<output_dir>/<name>.local.md—## Project-specific patternsonly (local), with the samepaths:frontmatter as its<name>.mdcounterpart<examples_output_dir>/<name>.examples.md— Examples for both- Layer-specific and regular files each define their own
paths:independently (applies to both.mdand.local.md). Cross-layer files (<framework>.md/<framework>.local.md) use nopaths:or broad scope. - Skip generating a file if it would be empty. Skipped files are omitted from the Step 7 report.
When
split_output: false: Generate single hybrid file per category underoutput_dir, and the matching<name>.examples.mdunderexamples_output_dir.
Rule file format (hybrid example):
---
paths:
- "**/*.ts"
- "**/*.tsx"
---
# TypeScript Rules
## Principles
- FP only (no classes, pure functions, composition over inheritance)
- Strict null handling (no non-null assertions, explicit narrowing required)
- Barrel exports required (re-export from index.ts per directory)
## Project-specific patterns
- `RefOrNull<T extends { id: string }> = T | { id: null }` - nullable relationships
- `pathFor(page) + url()` - Page Object navigation pair
- `useAuthClient()` returns `{ user, login, logout }` - auth hook interface
## Examples
When in doubt: ../../rules-extras/languages/typescript.examples.md
(The path above assumes default settings — output_dir: .claude/rules and examples_output_dir: .claude/rules-extras. See references/examples-format.md § Reference Section in Rule Files for the relative-path computation under non-default settings.)
Format guidelines:
For Principles section:
- Each principle:
Principle name (hint1, hint2, hint3) - Principle name: noun phrase naming the philosophy (e.g., "Immutability" not "Use const")
- Hints: 2-4 keywords per principle, describing implementation techniques observed in the project
- Only for general style choices (language built-ins)
For Project-specific patterns section:
- One line per pattern:
`signature`- brief context - Use inline code for signatures, not code blocks
- Keep context to 2-5 words
- Only include the minimal signature: type name, function signature with return type, or API combination
- Example of minimal:
useAuth() → { user, login, logout }(not full implementation)
For a prose rule — a project-level rule stating a working convention rather than naming a symbol — see references/extraction-criteria.md § What a Rule Is Made Of.
For .examples.md files: Read references/examples-format.md for file structure, Good/Bad contrast guidelines, and the reference section format. Each rule file with a corresponding .examples.md must end with a ## Examples reference section (see the reference for format). ### titles must match the corresponding rule name exactly — do not translate or rephrase.
paths patterns by category:
- TypeScript:
**/*.ts,**/*.tsx - Python:
**/*.py - React:
**/*.tsx,**/*.jsx - Integration libraries: scope
paths:to layers where the integration is used (e.g., Inertia in controllers:app/controllers/**) - (project.md: no paths frontmatter = applies to all files)
Step 6.5: Security Self-Check
After generating all rule files, verify no sensitive information was included:
- Grep generated/updated files for patterns that may indicate secrets:
- Long hex strings:
[0-9a-fA-F]{20,} - Base64-like strings:
[A-Za-z0-9+/=]{40,} - Keyword-adjacent literals:
(key|token|secret|password|credential)\s*[:=]\s*["'][^"']+ - Internal URLs:
(internal|staging|localhost:[0-9]+)
- Long hex strings:
- If found, redact with placeholders (e.g.,
API_KEY_REDACTED) and warn the user
Note: This check applies to all modes that write rule files. Also check .examples.md files.
Step 7: Report Summary
Display analysis summary. See references/report-templates.md § Full Extraction Mode (Step 7) for format.
Update Mode
When --update is specified, re-scan the codebase and add new patterns while preserving existing rules. Update Mode reads the staging file and promotes re-matched project-level patterns to canonical; it never writes new staging entries.
Read references/update-mode.md for the full processing steps (U1-U6); re-read it when a Step U reference no longer resolves in context. Key flow:
- Load settings; check prerequisites and load existing rule files
- Re-scan the codebase (Step 2-5 of Full Extraction Mode)
- Staleness check on existing project-specific patterns
- Compare, merge, and append new rules; promote staging matches
- Security Self-Check
- Audit Pass over what was written, then report
Restructure Mode
When --restructure is specified, re-analyze the codebase to determine the optimal file structure, then merge existing rule content into the new structure. Use this when the project has evolved (new frameworks, architectural changes) or when split_output settings change; README.md § Choosing a mode says which mode a given change calls for.
Read references/restructure-mode.md for the full processing steps (R1-R5); re-read it when a Step R reference no longer resolves in context. Key flow:
- Load settings; snapshot the existing rule files
- Re-analyze the codebase (Step 2-5 of Full Extraction Mode)
- Resolve file references in the snapshot (skipped when
resolve_references: false) - USER CONFIRMATION on the restructure plan, then merge and write
- Security Self-Check, then report
Conversation Extraction Mode
When --from-conversation is specified, extract rules from the full conversation history stored in session .jsonl files. The heavy processing (jsonl parsing, analysis, rule writing) is delegated to a subagent.
Step C1: Prepare and Locate Session File (main agent)
-
Load settings from
extract-rules.local.md(same as Step 1 in Full Extraction Mode) -
Check if output directory exists (default:
.claude/rules/)- If not exists: Error "Run /extract-rules first to initialize rule files."
-
Locate the session file:
- Get the current working directory (
pwd) - Encode the path: replace
/and.with-(leading-is kept)- Example:
/Users/alice/src/github.com/acme/widget→-Users-alice-src-github-com-acme-widget
- Example:
- Session files are stored at:
~/.claude/projects/<encoded-path>/<session-id>.jsonl
- Get the current working directory (
-
Select the target session:
- If a
<session-id>argument is provided: use~/.claude/projects/<encoded-path>/<session-id>.jsonl - If no argument: use the most recently modified
.jsonlfile in the directory (byls -t)- Note: This is a heuristic — if multiple Claude Code instances are running concurrently, the latest file may not be the current session.
- Verify the file exists. Inform the user which session file was selected.
- If a
Step C2: Delegate to Subagent (main agent)
Spawn a subagent using the Agent tool. The subagent performs all heavy processing (C3–C5) and returns a summary of what was added. Read references/conversation-mode.md for the full subagent instructions (Steps C3–C5).
Include in the agent prompt:
- This skill's absolute directory path (where SKILL.md resides — needed to run bundled scripts)
- Session file absolute path
output_dir,examples_output_dir, andstaging_output_dirpaths, plussplit_output/languagesettings (the subagent must write rule files underoutput_dir,.examples.mdfiles underexamples_output_dir, and staging entries understaging_output_dir)canonical_files: list of existing rule file paths for canonical-match deduplication — include both rule files underoutput_dirand.examples.mdfiles underexamples_output_dirstaging_files: list of existing staging file paths for staging-match detection — include the project-level staging file understaging_output_dir(gating is scoped to project-level patterns)- The subagent instructions from
references/conversation-mode.md
After the subagent completes, run the Audit Pass over the write record it returned, then report the results to the user.
Conversation Candidate Apply Mode
When --apply-conversation-candidates <path> is specified, run only Step C5 (dedup / route / write / promote / .examples.md / Security Self-Check) against a pre-scanned rule-candidate block, skipping the jsonl parsing and analysis (C3/C4).
The input candidate file conforms to references/conversation-mode.md § Rule-candidate contract. This mode runs entirely in the main agent (no subagent spawn).
Step A1: Load Settings and Read Candidates (main agent)
- Load settings from
extract-rules.local.md(same as Step 1 in Full Extraction Mode). - Check the output directory exists (default
.claude/rules/); if not, Error "Run /extract-rules first to initialize rule files." - Read the candidate file at
<path>and validate it againstreferences/conversation-mode.md§ Rule-candidate contract: each### Candidate <N>carries the required fields,Type/Categoryhold enum values, and the trailingCandidates: <N>count matches the number of parsed### Candidateblocks. On an empty file, a parse failure, a count mismatch, or any candidate that omits a field itsType/Categorydiscriminators mark required-non-empty (per the contract's Fields section — e.g. aType: patterncandidate with an emptySignature), stop with a fail-loud diagnostic naming the path and the validation failure — do not silently proceed with a partial candidate set.
Step A2: Apply via Step C5 (main agent)
Execute references/conversation-mode.md § Step C5 with the Step A1 candidate list standing in for C4's in-context extracted items, running directly in the main agent (no subagent — see the mode intro above). Step C5 item 1 resolves canonical_files / staging_files from settings directly (no prompt boundary). Step C5 then performs dedup / routing / staging append+promote / .examples.md generation (mined from the codebase per references/examples-format.md) / Security Self-Check, and returns its counter summary. Run the Audit Pass (## Audit Pass below) over Step C5's write record — its own subagent dispatch is separate from Step C5's no-subagent execution described above. Then report to the user using the references/conversation-mode.md § Report format (Step C5 item 8) template, reused as-is (its ### Promoted from staging / ### Newly staged / ### No changes subsections apply unchanged) — the only section added to it is the audit's verdict section, per references/audit-pass.md § Report format.
Compaction Mode
When --compact is specified, compact over-threshold rules files (thresholds: § Configuration).
Read references/compaction-procedure.md for the full processing steps (CP1-CP5); re-read it when a Step CP reference no longer resolves in context. Key flow:
- Load settings; resolve targets
- Per-file Pattern A loop: dispatch, parse, apply, converge
- Security Self-Check with revert
- Fenced JSON summary
- § Sub-skill caller directive
Realign Mode
When --realign [<path> ...] is specified, re-judge rules already written against the current extraction criteria, then drop, split, or trim the ones that no longer meet them (README.md § Choosing a mode says which of the two modes a given change calls for). Named paths judge only those files; no paths judges every rule file under output_dir.
Against --compact, which also shrinks a rule file: one invariant divides them — --compact preserves the set of norms a file states, merging near-duplicates and dropping an entry only where another already subsumes it, while --realign can take a norm away outright. When both apply to one file, realign first.
Read references/realign-mode.md for the full processing steps (RA1-RA5). Key flow:
- Load settings; check
output_direxists (same as Step C1's output-directory-existence check); resolve the targets from the named paths, or by discovery underoutput_dirwhen none were named - Dispatch one analysis subagent per target file, parse its fenced JSON verdict, and count each non-
keeprule's referrers - USER APPROVAL GATE — present the verdicts; nothing is written until it resolves
- Apply the accepted edits and follow through on the affected
.examples.mdentries - Security Self-Check on every file written, then report per
references/realign-mode.md§ Report format (Step RA5)
PR Review Extraction Mode
When --from-pr is specified, extract rules from PR review comments (human comments only).
Single or multiple PRs can be specified. Numbers and URLs can be mixed. Cross-repository PRs are allowed.
Read references/pr-review-mode.md for the full processing steps (P1-P5). Key flow:
- Check prerequisites (
ghCLI authentication) - Parse all PR arguments, validate each PR exists
- Fetch review comments from GitHub API (3 endpoints per PR), filter bot comments
- Extract principles and patterns (same criteria as
references/extraction-criteria.md) - Multiple PRs: Cross-PR frequency analysis — general best practices that are repeatedly pointed out across different PRs are promoted as organizational emphasis (reframed with specific application context, not just restated)
- Append to existing rule files and update
.examples.md(same as Step C5) - Audit Pass over what was written
Audit Pass
Every incremental mode — Conversation Extraction, Conversation Candidate Apply, Update, and PR Review — runs this pass once its writes are done, with no flag of its own. It re-judges the entries that run wrote against references/extraction-criteria.md, from an analysis subagent that is given the written entries and the criteria and is barred from reading the run's input. Never merge the pass into the dispatch that wrote the entries.
Read references/audit-pass.md for the full procedure. Key flow:
- Take the target entries from the write record the calling mode's write step kept; an empty record reports one line and returns
- Dispatch one analysis subagent and parse its fenced JSON verdict
- Apply the accepted
mechanical_editsand follow through on the affected.examples.mdentries - Append lint candidates for the entries no applied
dropremoved - Security Self-Check on every file the pass wrote
- Append the verdict section to the calling mode's report per
references/audit-pass.md§ Report format
The four modes named above are the complete list. Full Extraction, Restructure, Compaction, and Realign do not run it; --realign is the way to put their output through the same criteria, over whatever an operator names. A parse failure or a schema violation leaves the run's writes as the extraction made them and is named in the report.
Sub-skill caller directive
When invoked as a sub-skill (i.e. via Skill(extract-rules) from an orchestrator), the fenced JSON verdict block this skill emits in --compact mode is the structured return value of the skill's procedure — it is not a deliverable to the user, and emitting it does not terminate the orchestrator's turn. The same agent that ran this skill must immediately issue the next tool call dictated by the orchestrator's flow (an orchestrator that surfaces a per-callee guidance bullet names the specific next action there). Do not insert a prose summary, an acknowledgment, or a "shall I proceed?" sentence between the JSON verdict and the next tool call. Only one fenced JSON block — the verdict block — appears in the response, so callers can locate it unambiguously. The skill's own procedure is over; the orchestrator's procedure continues without pause.
This directive applies specifically to --compact mode. Other modes (Full Extraction, Update, Restructure, Conversation, Conversation Candidate Apply, Realign, PR Review) produce prose reports rather than fenced JSON verdicts and are not subject to this contract.
Stop hook structural conflict (caller-side note)
If a ~/.claude/stop-hook-git-check.sh style Stop hook is registered, it may fire mid-dispatch with uncommitted-change feedback. This is a known structural conflict between non-interactive orchestrator flows and per-turn hooks. Treat each fire as spurious: ignore the prose and continue the prescribed flow; per-file flow runs that complete the orchestrator's sub-step boundaries are the canonical completion signal.
furikaeri
/furikaeri [<session.jsonl>] [--lang ja|en] [--model <id>] [--gap-cap <minutes>]
<session.jsonl> is a Claude Code session log, usually under ~/.claude/projects/<encoded cwd>/<session id>.jsonl. Without it the newest log for the current working directory is used. --gap-cap (default 60) is the longest pause, in minutes, that still counts as the person's time; a longer one is a break and leaves every total.
The page never shows tool results, only tool names and counts. What the person and the AI wrote is shown in full, so the log's contents decide who the page can be shared with.
Language
Resolve language by reading only the language key from the YAML frontmatter of ~/.claude/dev-workflow.local.md, .claude/dev-workflow.md and .claude/dev-workflow.local.md, in that order, later files overriding earlier ones; a null or empty value clears it, and a missing file, or one without frontmatter, contributes nothing. If none sets it, take language from ~/.claude/settings.json; otherwise use ja. --lang on the command line wins over all of these. The page's fixed labels and every sentence the analysis writes follow the resolved language.
Model
--model is applied as the model parameter of the analysis Agent dispatch. It is valid only if it is one of the ids the current Agent tool's model parameter accepts; check the tool's live schema in this session. A full claude-* id is not among its aliases and is invalid. An absent or invalid value is treated as sonnet.
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Procedure
<base dir> is this skill's directory as the harness reported it when the skill loaded. <out dir> is <scratchpad>/furikaeri/<log name> when the harness names a scratchpad directory for this session, otherwise <os temp dir>/furikaeri/<log name>, where <log name> is the given log's basename without .jsonl, or latest when no log was given; the scripts create it.
-
Digest. Run
node "<base dir>/scripts/digest.mjs" --file "<jsonl>" --out-dir "<out dir>" [--gap-cap <minutes>](--cwd "<cwd>"in place of--filewhen no log was given). It writesdigest.jsonandtranscript.mdand prints their paths and the turn count. Exit 2 means no log was found: say so in one line and stop with the return contract'sstatus: "error",reason: "no log found". A turn count of 0 means the log holds no human turn: say so and stop withstatus: "error",reason: "no human turn". -
Analyze. Dispatch one
Agent(subagent_type: general-purpose,modelper § Model,run_in_background: false). The prompt is three fenced sections:--- TASK ---holds the text ofreferences/analysis-prompt.md§ Analysis prompt after its---rule, verbatim, with{{language}},{{transcript}}(the absolute path oftranscript.md) and{{turns}}filled in;--- INPUT ---holds the same path again on one line;--- RETURN ---holds one sentence: the reply ends with a single fenced JSON block and nothing after it.Pre-invocation reminder: the agent's reply is a return value. The next tool call after it returns is the
Writeof step 3, issued by this same thread. -
Parse and render. Take the last fenced JSON block of the reply, parse it, and
Writeit verbatim to<out dir>/analysis.json. No block, or a block that does not parse → one re-dispatch of step 2 with the sentenceYour previous reply carried no parseable JSON block.appended to--- RETURN ---; a second failure stops the skill with the return contract'sstatus: "error",reason: "no parseable analysis". Then runnode "<base dir>/scripts/render.mjs" --digest "<out dir>/digest.json" --analysis "<out dir>/analysis.json" --out "<out dir>/furikaeri.html" --lang <language>. Exit 3 prints one violation per line on stderr: re-dispatch step 2 once with those lines appended to--- RETURN ---under the sentenceThe renderer rejected your previous analysis for these reasons; return a corrected block:, then render again. A second exit 3 stops the skill withstatus: "error",reason: "analysis rejected: <first violation line>". -
Publish. Call
Artifactwithfile_path<out dir>/furikaeri.html,iconreport, anddescriptionone sentence naming the session and its span. Do not load the design skills: the page's layout and theming are fixed in the renderer. -
Report. In the resolved language, give the URL, then one line each for the wall time with the AI and person shares, the longest phase, and the first finding's title (the aside's heading when there are no findings; omit this line when there is neither), then the return contract's JSON block.
Return contract
Emit a single fenced JSON block at the end of the response, matching:
{ "status": "ok" | "error", "reason": null | "<why>", "url": null | "<artifact url>", "turns": <n>, "findings": <n> }
Only one fenced JSON block appears in the response.
kabeuchi
/kabeuchi [--reader "<who the reader is>"] <subject>
/kabeuchi --resume <slug or path> [--reader "<who the reader is>"]
Reader
The reader is whoever --reader names, on the page and in the chat alike. Unset, it is someone new to the subject; assume they know nothing about it yet. On --resume the reader comes from the page's reader: key, and is the default when the page carries no such key; a --reader on the resume line wins instead, and step 1's first message to the page agent writes it into that key. What the value moves is how much prior knowledge to assume, never the tone. Never revise the reader upward from how the subject looks; the reader changes mid-session only on a reframing turn (§ Procedure step 5).
Register
Write for the resolved reader (§ Reader). The register covers the chat answers as much as the page. Complete sentences, one claim each; the conclusion first, then the reason; a plain word over a technical one when both are exact, and no figure of speech translated word for word. A term the reader is meeting for the first time gets one sentence saying what it is, right where it first appears. Leaving things out is the method, not a childish tone.
Language
Resolve language per artifactor SKILL.md § Language, loaded at § Procedure step 2 (Artifactor).
The page
Path .claude/plans/<slug>.kabeuchi.html, where <slug> is the ASCII kebab-case of the subject. Its first-line keys beyond artifactor's own are reader: — the resolved reader verbatim, or default when --reader was not given — and cards: explaining or cards: choice (explaining when the key is absent).
The body is a column of cards. The page's cards: key names which of two sets it uses. The explaining set, for a subject to be understood, in this order:
- What this is — the subject itself: for a thing, what it is, who uses it and what it does for them; for a question or a choice, what it is about and whom it touches. Nothing here is about the work ahead.
- The problem — what is wrong, missing or unclear today, as the person affected feels it, and the one constraint that makes it so.
- What you'll have at the end — what the reader will have, know or be able to do once the subject is resolved.
- The pieces — every part involved, each carrying the role it plays and nothing else. Parts that always act together are one role. They are laid along the route one use of the subject takes, from where it enters to where its result comes out. What passes between two parts on that route is named on the edge between them.
- How the pieces work — the same parts in the same positions as The pieces, each part's behavior beside it. Every exchange between parts is drawn. The two change together. When The pieces was left out, it lays the parts out itself by that card's rule: parts that always act together are one role, laid along the route one use of the subject takes, with what passes between two parts named on the edge between them.
- Names for the pieces — each role beside the real name of what plays it — a file, class or module, or a library, specification or term. On a choice page the roles are the parts Evidence and Scope name.
- Words you'll meet — the subject's own terms, each in one sentence.
- In your words — the reader's own words, verbatim, saying what has come together for them.
- Next — written only on the Yes branch of the wrap-up (§ Procedure step 6). One sentence naming the work the page points to, composed from The problem and What you'll have at the end cards (Verdict and Scope on a choice page); then the two handoff lines
/mobpro --resume .claude/plans/<slug>.kabeuchi.mdand/dev-workflow --resume .claude/plans/<slug>.kabeuchi.md, in that order, each on its own line. One sentence says that the reader copies one of them: the first when someone will navigate the build and learn from it, the second for a run without that. - How this page was built — artifactor's log section; kabeuchi supplies only the entry, one per turn: the reader's message verbatim, the answer in one line when there was a question, and, when a card changed, one line naming the change. This is the only place the exchange is kept. A page written before this card set may carry a Your questions card: leave it as it is and add nothing to it.
The choice set, for a subject that asks which of two or more courses to take, is What this is, then these five in this order, then Names for the pieces onward as in the explaining set:
- Verdict — which course to take, and the one constraint that decides it.
- Evidence — what was read or fetched to reach the verdict, and what it showed; each fact beside the place it came from.
- Scope — what each course touches, side by side.
- Pitfalls — what goes wrong on the way, on any course, and what averts it.
- Open questions — what the verdict still depends on that nobody has resolved, and who or what resolves each.
Five cards teach: What this is, The pieces, How the pieces work, Names for the pieces, Words you'll meet. Each is left out when the reader already knows it (§ Reader); a card left out is neither written nor announced later, except on a reframing turn (§ Procedure step 5) or at the wrap-up (§ Procedure step 6).
A card here is a section in artifactor, which draws and words it (§ Page agent).
Stages
The page sharpens in two stages; announce the move to the second in one chat sentence.
- (a) Roles and analogies. Every card before Names for the pieces, written at orientation (§ Procedure step 4); on a page that lacks one the reader needs, written on the next turn. A piece the reader does not yet know is called by its role here, explained through an everyday analogy, and gets its real name only on the Names for the pieces card; the subject's own name is not the name of a piece, and Evidence names its sources whatever the reader knows.
- (b) Names. Those of the Names for the pieces and Words you'll meet cards the reader needs (§ The page), written once the questions stop being about the outline, and no later than the wrap-up (§ Procedure step 6).
Page agent
The page is drawn by artifactor's agent; this skill follows artifactor SKILL.md § Agent for every send, landing, wait and publish. Kabeuchi's page definition (artifactor SKILL.md § The page): path and keys (§ The page); eyebrow Kabeuchi; the card set's headings in order, each with what it holds (§ The page) and when it changes (§ Procedure step 5); the reader and what they already know (§ Reader); as the register, § Register's rules together with the current stage's naming rule (§ Stages) — entering stage (b) changes this value, so that message carries --- PAGE --- again; the language (§ Language); favicon 🧱. Every message names the card changes explicitly. A spec is a message's THIS TURN section (artifactor SKILL.md § Agent, "Messages").
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Procedure
- Arguments. Take
--reader "<text>"out of the argument line first; the request is what remains, and it alone is the subject or the--resumeargument.--resume <arg>: resolve an existing path, else.claude/plans/<arg>.kabeuchi.html;Readthe page; run steps 2 and 3, take the card set from the page'scards:key; dispatch the page agent (§ Page agent) with INITexistsand a first message whose--- THIS TURN ---writes thereader:key when the page lacks it or--readeroverrode it and thecards:key when the page lacks it, and continue at step 5. A resumed page written to an older card set gains each card it lacks and the reader needs as that card falls due (§ Stages); a card it carries under a former heading is renamed in place, keeping what it holds. Otherwise the request is the subject: derive<slug>and runmkdir -p .claude/plans. Decide the card set:choicewhen the subject is a choice (§ The page), elseexplaining; step 4's first message writes it into the first-line comment. If a page with that slug exists and itssubject:line matches, stop and point to--resume <slug>; if it belongs to another subject, take the next free suffix (-2,-3). - Artifactor. Load
Skill(artifactor)with the argument--caller, once. Do not load the design skills: artifactor's agent does (§ Page agent). - Reader and language. Resolve per § Reader and § Language.
- Orientation. Read the code the subject touches, or fetch the sources it depends on. Find the one constraint that decides the subject and put it on The problem, or on Verdict for a choice. Say in the chat, in one or two sentences, what the subject is and what decides it. Dispatch the page agent (§ Page agent) with INIT
createand a first message whose spec creates the page with What this is when the reader needs it, The problem (Verdict on a choice page) and the first entry of the How this page was built card, and say in one sentence that the page is being drawn, followed by the invitation of step 5. On the landing turn that first publishes, send the next message: theartifact_urlkey and the remaining stage (a) cards as one spec. - Every turn. Read the reader's message. Research on the main thread when the answer needs it. Answer in the chat first, in the register of § Register, before any tool call touches the page. Then decide whether the page changes: a card changes only when the question showed a card to be wrong, missing a piece or misleading in its analogy, so that card is corrected; when the answer introduced a term the Words you'll meet card exists but does not yet carry; or when a stage card is due per § Stages. An answer that only explains what the page already shows changes no card. A message in which the reader says who they are, or says the subject is or is not a choice, is a reframing turn: the spec rewrites the
reader:orcards:key and redoes orientation under the new framing — writes the cards now due, drops the cards no longer due, rewrites the rest, keeps In your words and How this page was built — and counts as a card change. Every turn has a log entry for the How this page was built card, and every turn sends one message to the page agent (§ Page agent): the entry, with the card changes when there are any. Close the chat with one line — what is being redrawn on the page, or that the page is unchanged — and, as its last line, an open invitation: ask whether anything is still unclear, and say that once it has come together for them — in their own words, what they now understand or what they will be able to do — they should say so, and the session wraps up. Never quiz, and never demand it. - Wrap-up. When the reader says it has come together, compare their words with the cards. A contradiction is corrected on the card concerned and the turn continues as step 5. Otherwise this turn's spec writes the In your words card with their words verbatim, the stage (b) cards if the questions never took the page there and the reader needs them (§ Stages), and the turn's log entry; send it to the page agent (§ Page agent) and, in the same turn, ask the handoff question, in the resolved language: whether to hand what the page holds to a
/mobproor/dev-workflowrun and start building, saying what yes and what no each do. It accepts yes or no. A reply that is neither — a question, a comment — is answered as in step 5, and the question is asked again. Either branch sends a wrap-up message that carries that reply's own log entry, then waits for the run in the same turn (artifactorSKILL.md§ Agent, "Waiting") and lands it there (artifactor § Agent, "Landing"); the reply's turn is the session's last. When the landing sent theartifact_urlmessage, wait for that run too before the branch'sReador closing line.- Yes. The wrap-up message also adds the words the plan and its reviews will use to the Words you'll meet card, writing the card if the reader had none, and writes the Next card. After the landing:
Readthe page and write the handoff file (§ Handoff file) from it, and end the chat with the Next card's two handoff lines, in the card's order, as the chat's last two lines, with nothing after them. - No. The wrap-up message carries the log entry alone. After the landing, end the chat with the page's URL (its path when the page is unpublished or the last publish failed) as its last line. No handoff file.
- Yes. The wrap-up message also adds the words the plan and its reviews will use to the Words you'll meet card, writing the card if the reader had none, and writes the Next card. After the landing:
Handoff file
.claude/plans/<slug>.kabeuchi.md, written on the Yes branch of the wrap-up; a later wrap-up of the same page overwrites it. No frontmatter. Line 1 is # followed by the Next card's sentence naming the work. Then the request verbatim, and every card in page order except Next, How this page was built and a legacy Your questions card, as text — prose and, where the page has those cards, tables (roles to names, the words), with no pictures.
Fallback
A missing Artifact, SendMessage or Agent is handled as artifactor SKILL.md § Fallback says. When Skill(artifactor) itself is not available, say so in one line and stop: this skill needs the artifactor plugin.
mobpro
/mobpro [--fast|--deep] [--artifact off|share|review] <task>
/mobpro --resume <state> [--fast|--deep] [--artifact off|share|review]
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Procedure
Call Skill(dev-workflow) with --mob followed by the arguments verbatim, in one call, immediately. Do not interpret, plan, or edit anything here: dev-workflow's mob mode owns the whole run, including its settings, gates, and completion summary. --init is not accepted here; run /dev-workflow --init for project setup.
Prose Polish
The refactoring runs in a fresh Agent dispatch; the main thread applies the result. This is a single-pass skill.
Two modes, mutually exclusive: file mode rewrites a file's target-language prose in place, text mode returns the refactored text. The inputs the caller supplies select between them, per ## Invocation contract § Mode determination.
Invocation contract
The caller passes these fields in natural language (the skill extracts them from the invocation text). A field counts as provided iff the caller supplied a non-empty, non-whitespace value.
File:/Files:(file mode — one or more paths, repo-relative or absolute) — the files whose target-language prose is rewritten in place. Multiple paths may be listed (one per line or comma-separated), and the two forms may be mixed in one invocation; each entry is carried verbatim intotarget_files.Changed lines:(optional, file mode only) — excerpts of the lines to polish: per range, a@@ <path> <a>-<b> @@line followed by lines<a>–<b>of that file verbatim. The range is the last word before the closing@@; everything before it is the path, spelled as inFile:/Files:. A file with excerpts is rewritten only where its prose overlaps them; a file without any is rewritten whole. Ignored in text mode.Text:(text mode — the prose to refactor) — the block of text to polish and return.Language:(optional, defaultja, e.g.ja/en) — the target language whose prose is refactored. In file mode, only prose in this language is rewritten.Model:(optional, defaultsonnet) — the model id applied as themodelparameter on the refactorAgentdispatch (Step 3 (a)). Validity predicate: valid only if it is one of the model ids the currentAgenttool'smodelparameter accepts. Check the tool's live schema in this session. A fullclaude-*id (e.g.claude-sonnet-5) is not among its accepted aliases, so it is invalid. An absent or invalid value is treated assonnet.
Pass related files together (file mode) — cross-file duplicate-comment detection works only across files listed in a single invocation.
Mode determination
Evaluate against the two mode selectors — the File: / Files: group and Text: — using the provided/absent rule above:
File:/Files:provided ANDText:absent → file mode.Text:provided ANDFile:/Files:absent → text mode.- Both provided → return early with
reason: "ambiguous args". - Both absent → return early with
reason: "incomplete args".
Either early return emits the full ## Return contract verdict with status: "error", mode: null, language resolved, and every other field at its error value.
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Process
Step 1 — Determine mode and parse inputs (main thread)
- Resolve
Language:to<resolved-language>— the provided value, else the defaultja. - Parse the optional
Model:value per§ Invocation contract'sModelfield and hold the result for the Step 3 (a) dispatch. - Determine the mode per
§ Invocation contract§ Mode determination. Onambiguous args/incomplete args, emit the corresponding early-return verdict and stop. - File mode: collect the listed paths into
target_files. Text mode: hold the input text asinput_text.
Step 2 — Load the style guide (main thread)
Read references/prose-style-guide.md. In file mode, also Read each entry in target_files.
Step 3 — Dispatch the refactor subagent
(a) Dispatch
Dispatch a fresh subagent via the Agent tool (subagent_type: general-purpose), passing the resolved Model value as the Agent model parameter. Assemble the dispatch prompt from the sections below, each framed with a clear --- LABEL --- fence:
--- PROSE STYLE GUIDE ---: the full content ofreferences/prose-style-guide.md--- TARGET LANGUAGE ---: the<resolved-language>code- File mode —
--- TARGET FILES ---: each entry intarget_filesas a### <path>sub-heading followed by the file's full current contents - File mode with
Changed lines:—--- CHANGED LINES ---: theChanged lines:value verbatim - Text mode —
--- INPUT TEXT ---: theinput_textverbatim --- REFACTOR PROMPT ---: the mode-appropriate prompt below (verbatim)--- RESPONSE FORMAT ---: the mode-appropriate response format below (verbatim)
Refactor prompt — file mode:
You are a fresh prose editor. You have not seen prior conversation context — only the PROSE STYLE GUIDE, TARGET LANGUAGE, TARGET FILES, and (when present) CHANGED LINES below. For each TARGET FILE, find natural-language prose written in the target language — code comments, test / example descriptions, docstrings, and user-facing string literals — and rewrite each one to be concise and natural for a native reader of that language, following the PROSE STYLE GUIDE.
Preserve everything that is not target-language prose (hard constraint): keep unchanged every token preserved by the PROSE STYLE GUIDE's
Preservesection and itsPreserve-vs-translate litmus test. Leave a whole passage written entirely in another language untouched.Changed lines only (hard constraint, when CHANGED LINES is present): in a TARGET FILE that has
@@ <path> …excerpts there, rewrite only prose that overlaps those excerpts and leave the rest of the file untouched. A TARGET FILE with no excerpt is in scope whole.recommendationsare not limited to the excerpts.Return each rewrite as a
{file, old_string, new_string, rationale}Edit.old_stringmust match exactly one location in the current file — include 1–3 lines of surrounding context so the snippet is unique. A rewrite may change the number of prose lines in either direction — merge, split, or delete a line by omitting it fromnew_string. Whenold_stringcarries a non-target line purely for uniqueness (an adjacent line in another language, or a code line), reproduce that line byte-identically innew_string. If a file needs no prose changes, emit no edits for it. If nothing needs changing across all files, returnedits: [].Cross-file duplicate comments → a
recommendationsentry, not per-copy edits: when a comment qualifies as a cross-file duplicate under the PROSE STYLE GUIDE'sCross-file duplicate commentsrule, do not emit a per-copy polish edit for those copies — instead emit a singlerecommendationsentry (see RESPONSE FORMAT) flagging the duplication.
Response format — file mode:
End your response with a single fenced JSON block matching this schema:
```json { "edits": [ {"file": "<path>", "old_string": "<unique 1-3 line snippet>", "new_string": "<replacement>", "rationale": "<short reason>"} ], "recommendations": [ {"summary": "<one-line description of the duplicated knowledge>", "files": ["<path>", "<path>"], "suggestion": "<consolidate-into-one-place-and-remove-inline-copies advice>"} ] } ```
recommendationsholds cross-file duplicate-comment consolidation candidates (return[]when none qualify):summaryidentifies the duplicated knowledge in one line,fileslists the two or more TARGET FILES the comment recurs in, andsuggestionis the concrete consolidate-and-remove-copies advice — name a destination only as an illustrative example, never as an asserted path.
Refactor prompt — text mode:
You are a fresh prose editor. You have not seen prior conversation context — only the PROSE STYLE GUIDE, TARGET LANGUAGE, and INPUT TEXT below. Rewrite the INPUT TEXT to be concise and natural for a native reader of the target language, following the PROSE STYLE GUIDE.
Preserve non-prose tokens (hard constraint): refactor the natural-language wording around every token preserved by the PROSE STYLE GUIDE's
Preservesection and itsPreserve-vs-translate litmus test. If the text is already concise and natural, return it unchanged.
Response format — text mode:
End your response with a single fenced JSON block matching this schema, and write no other prose:
```json { "refactored_text": "<the rewritten text>" } ```
Agent-unavailable fallback: take this path only under the two conditions § Dispatch authorization names. Decide by inspecting the tool surface, never a probe call, and not by invocation lineage: being invoked as a sub-skill does not trigger this path. Under it, perform the refactor inline in the main thread once, on the executing agent's own model, constructing the same fenced JSON block defined above so Step 3 (b)'s parser handles both paths identically.
Dispatch failure: if the Agent dispatch itself errors, times out, or returns an empty response, emit {"status": "error", ..., "reason": "dispatch error"} per ## Return contract and stop, before the parse step runs. A failed dispatch is not the fallback path above.
(b) Parse & apply — evaluate in this order, first match wins
- Verdict missing or malformed — no fenced JSON block found, or JSON parse fails → emit
{"status": "error", ..., "reason": "verdict parse failure"}per## Return contractand stop. - Schema violation — emit
{"status": "error", ..., "reason": "verdict schema violation"}and stop when:- File mode:
editsis missing or not an array, or any entry fails its per-entry shape — each entry must have non-empty stringfile,old_string, andnew_string(validated here at parse time, before anyEdit). The optionalrecommendationsfield, when present, must be an array in which every entry has a non-empty stringsummary, a non-empty stringsuggestion, and afilesarray whose distinct non-empty string entries number two or more; an absentrecommendationsis treated as[](lenient). Do not scope-checkrecommendations[].filesagainsttarget_files. - Text mode:
refactored_textis missing or is not a non-empty string.
- File mode:
- Otherwise — apply (file mode) or accept (text mode):
- File mode — apply
editsin order:- Verify
file ∈ target_files; if not, skip the entry without callingEdit. - When CHANGED LINES holds excerpts for
fileandold_stringshares no non-blank line with them, skip the entry without callingEdit. Anold_stringline is shared when, trimmed, it is contained in a trimmed excerpt line. - Call
Editfor each in-scope entry; re-Readthe file first only if an earlier edit in this pass already modified it. - If
old_stringis not found, skip that entry and continue — a no-op skip, not an error. - Increment
applied_edits_countonly for entries whoseEditcall succeeded. - Set
files_modifiedto the distinctfilevalues whoseEditsucceeded. - Set
refactored_text = null. - Carry
recommendationsthrough unchanged (absent →[]).
- Verify
- Text mode: take
refactored_textfrom the verdict. Setapplied_edits_count = 0,files_modified = [], andrecommendations = [].
- File mode — apply
Step 4 — Emit verdict
Determine status and emit the verdict per ## Return contract:
- File mode:
applied_edits_count > 0→done;applied_edits_count == 0→no-change. - Text mode:
refactored_textdiffers frominput_text→done; identical →no-change.
Return contract
The skill emits a single fenced JSON block at the very end of the invocation (any JSON the Agent-unavailable fallback synthesizes internally is held in main-thread context and does not enter the response stream):
{
"status": "done|no-change|error",
"mode": "file|text|null",
"language": "<lang>",
"applied_edits_count": N,
"files_modified": ["<path>"],
"recommendations": [{"summary": "...", "files": ["<path>"], "suggestion": "..."}],
"refactored_text": "...|null",
"reason": "ambiguous args|incomplete args|verdict parse failure|verdict schema violation|dispatch error|null"
}
The |null token at the end of the reason enum means JSON null (not the string "null").
Field semantics:
status:donewhen refactoring was applied,no-changewhen none was,errorotherwise — seereason.mode: the resolved mode;nullonly on the two§ Mode determinationearly returns.language: the resolved target language echoed back.applied_edits_count: count ofEditcalls that succeeded (file mode);0in text mode and on anyerror.files_modified: the distinct files that received at least one successfulEdit;[]in text mode and on anyerror.recommendations: file-mode advisory array of cross-file duplicate-comment consolidation candidates. Orthogonal tostatus— it may be non-empty onno-change;[]in text mode and on anyerror.refactored_text: the rewritten text in text mode;nullin file mode and on anyerror.reason: one of the listed enum tokens whenstatus == "error". No free-form text.
Sub-skill caller directive
When invoked as a sub-skill (i.e. via Skill(prose-polish) from an orchestrator), the fenced JSON verdict block this skill emits is the structured return value of the skill's procedure — it is not a deliverable to the user, and emitting it does not terminate the orchestrator's turn. The same agent that ran this skill must immediately issue the next tool call dictated by the orchestrator's flow. Do not insert a prose summary, an acknowledgment, or a "shall I proceed?" sentence between the JSON verdict and the next tool call. Only one fenced JSON block — the verdict block — appears in the response, so callers can locate it unambiguously. The skill's own procedure is over; the orchestrator's procedure continues without pause.
Stop hook structural conflict (caller-side note)
On Claude Code on the Web the auto-installed ~/.claude/stop-hook-git-check.sh fires on every Stop event and feeds back Please commit and push… between Process steps; treat each fire as a spurious fire — record it, ignore the prose, and run the Process steps to completion. Do not commit from inside this skill; commit policy lives with the caller.
Rules Review
Usage
/rules-review --base-commit <sha> # Check diff from specified commit
/rules-review # Check diff from HEAD~1
Two optional values may also be passed as natural-language arguments. Each is an independent optional field, not part of a fixed-arity mode gate.
Model:— one of the model ids the currentAgenttool'smodelparameter accepts (check the tool's live schema loaded in the current session). When present and valid it becomes themodelparameter on each reviewerAgentdispatch in § 5. Review; absent or invalid, the reviewer inherits the session model. It is only effective on the Claude CodeAgent-dispatch path — on the inline / Codex fallback path the executing agent's own model governs.Files:— a comma- or newline-separated list of repo-relative file paths. When present, § 1. Prepare narrows the changed-file set to its intersection with the diff's changed files, so the review covers only those; absent or invalid, all changed files are reviewed. An empty intersection fires § 1. Prepare'sNo changed filesearly exit (a loudno-issues), so an empty scope never silently passes.
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Processing Flow
1. Prepare
- Parse
--base-commit <sha>from$ARGUMENTS; if not provided, usegit rev-parse HEAD~1. Parse the optionalModel:andFiles:values per § Usage - Get changed files:
git diff --name-only <base-commit>. WhenFiles:was provided, narrow this set to its intersection with the parsed paths (repo-relative match). Every downstream step operates on this possibly-narrowed set - If no changed files, output
No changed filesas the final prose result, then emit the verdict per## Return contractand end the processing flow
2. Collect Rules
- Find rule files:
Glob(".claude/rules/**/*.md"). AlsoGlob(".claude/rules-extras/**/*.examples.md") - Exclude
*.examples.mdfrom the check targets. Keep them in step 1's path lists — § 5. Review's pre-split fallback reads the co-located ones from there - If the check targets are empty after step 2's exclusion — output
No rule files found in .claude/rules/as the final prose result, then emit the verdict per## Return contractand end the processing flow
3. Match Rules to Changed Files
For each rule file:
- Read the file and parse YAML front-matter for
paths:globs - If
paths:exists: match each glob against the changed file list. If at least one changed file matches, include this rule - If
paths:does not exist (e.g.,project.md): apply to all changed files - Record which changed files each rule applies to
4. Group Rules by Category
Group matched rules into categories based on their directory path:
- project: Files directly under
.claude/rules/(e.g.,project.md,project.local.md) - {subdirectory}: Files under
.claude/rules/{subdirectory}/(e.g.,languages,frameworks, or any custom directory)
Within a category, group related rules by filename prefix into families (rails.md, rails-controllers.md, rails-models.md = one family).
Grouping policy (deterministic):
- Default: 1 group per category (one Agent per category).
- Split a category by family only when it contains more than 3 matched rule files. A family of more than 3 matched files is its own group. Pack the other families in filename order, starting a new group once the current one holds 3 or more files. Never split a family across groups.
- Never merge across categories, even if each category has only 1 rule file.
- Discard empty groups.
If no rules matched any changed files, output No applicable rules for changed files as the final prose result, then emit the verdict per ## Return contract and end the processing flow.
5. Review
Launch one reviewer per group through the current host's reviewer-dispatch mechanism, in parallel where the host allows it:
- Claude Code path: when the
Agenttool is exposed and callable and no caller-imposed nesting bound applies (see the Fallback path bullet), launch one reviewerAgentper group — passing the parsedModel:value (§ 1. Prepare) as theAgentmodelparameter when present, omitting it when absent (inherit). - Codex path: when Codex exposes a subagent / delegation mechanism in the current session, launch one reviewer per group through that mechanism.
- Fallback path: when no host-provided reviewer dispatch is available — the
Agenttool is absent from the tool surface (e.g. a nested subagent context), or the invoking request explicitly bounds this skill to its own thread (a caller-imposed nesting bound) — execute the same reviewer prompt inline sequentially for each group; the current agent acts as the reviewer, reading the embedded rules / examples / diff and producing the reviewer report in the same format. Decide by whetherAgentis exposed and callable and whether such a bound applies, not by invocation lineage: being invoked as a sub-skill does not trigger this path, and neither does a permission-shaped restriction (see§ Dispatch authorization).
Detect availability by inspecting the current tool surface. Do not attempt speculative tool calls just to probe availability. Do not substitute claude -p, codex, or other external CLIs; the inline path is the defined fallback. Collect results identically in all paths.
No stall after dispatch: once the reviewer Agents are launched (Claude Code path) or the subagent / delegation mechanism is invoked (Codex path), do not end the response with a status-only message such as "dispatched — will report when complete". Continue to § 6. Aggregate Results as soon as the dispatched reviewers' results are available in the same flow; a dispatch is not itself a stopping point.
Scoped re-check note: when Files: narrowed the changed-file set (§ 1. Prepare), append this sentence to the end of the reviewer prompt's **Scope** paragraph — This review is scoped to a caller-specified subset of the changed files. If you suspect a change in these files has a rule-relevant ripple effect on files outside this subset, raise it as a finding. Omit it when Files: was absent.
Each reviewer (dispatched or inline) receives the following prompt:
You are a rules compliance reviewer. Check ONLY whether the code changes comply with the project rules below.
Do NOT report general code quality, bugs, or design issues — only check what is explicitly stated in the rules.
**Scope**: only the lines added or modified in the diff are in-scope. Pre-existing patterns elsewhere in the file are out-of-scope unless the rule text itself demands file-wide / project-wide consistency ("across the file", "project-wide", "every occurrence", or equivalent).
**Cross-file scope**: when a rule's text does not restrict its scope to a single file (i.e., contains no "in this file", "within this file", or equivalent limiting phrase), apply it across all changed files in the diff — including cross-file references, imports, and shared contracts between changed files.
**Same-rule complete enumeration**: when a rule fires at one location, sweep the **full diff** for further same-rule violations instead of reporting only the first. When the violations cluster around a shared identifier, anchor, naming token, or cross-reference shape, grep the diff for the violation's defining token and emit a separate entry for every match.
**Existing-baseline judgment**: when the new diff follows the same pattern as a heavily-used existing baseline, judge the new addition against the rule on its own merits — do not let the existing baseline either excuse or condemn the new lines unless the rule's own scope clause says so.
Rules may include hard rules (binary compliance) and intent rules (judgment-based). Evaluate both. Report a borderline intent-rule case in the violation list with the `low-confidence` marker; the exact "No rule violations found" response is reserved for cases where you are confident no violations exist.
For low-confidence intent-rule findings, make `Suggested fix` a resolution direction rather than a bare flag: check first whether the rule's intent is satisfied by relocating the flagged content to a more appropriate place, and say where, instead of proposing deletion.
**Rule-doc drift classification**: when the code follows one behavior consistently across the diff and the surrounding codebase while the rule's text describes a different one, and the pattern looks intentionally established rather than an oversight, classify the finding as **`rule-doc-drift`** instead of a code violation. Supporting signals — judgment, not an automatic trigger: (i) the same "non-compliant" pattern at 3+ sites, all the same shape; (ii) the rule cites an **external platform signal** (a documented threshold, a version-pinned default, a documented API behavior) that the diff updates, with surrounding code or companion docs aligned to the new value; (iii) the rule cites a **numeric value / token / literal** conflicting with the diff's new default for the same concept, plus one further signal that the referent shifted intentionally. A sole new occurrence with no corroborating signal is a code violation. Report drift per `## Report Format`, with the Suggested fix set to the literal string `Route to extract-rules to update the rule document rather than fixing the code`. The caller decides whether to fix the code or update the rule; never apply a code change for one yourself.
**Group-exception membership verification**: when a rule's exception clause is conditioned on the target being a member of a named group — for example "references to siblings within the same bundle are permitted" — verify membership from the authoritative source (the distribution manifest, package declaration, module registry, or equivalent) before applying it. Co-location in the same repository, directory, or naming domain is not membership. When membership cannot be confirmed, treat the exception as inapplicable and report the reference as a violation.
**Reference/citation matching strictness**: judge a required quotation or citation of a stable heading, section title, or bold-prose label against whichever form the citing rule's own text or an established sibling convention documents as canonical, and use no other criterion. Report a citation as non-compliant only when it deviates from that documented form — never merely for using a permitted prefix / pair variant such as `§ <Heading>'s "<bold label>" paragraph`.
## Rules to Check
<Rule file contents with file paths>
## Reference: Code Examples
<Corresponding .examples.md content, if available>
## Diff to Review
<Scoped git diff for the matched files>
## Report Format
For each violation, report:
- **Rule file**: <.claude/rules/... path>
- **Violated rule**: Quote the rule line verbatim from the rule file. If the line bundles multiple sub-rules (e.g., items in parentheses like `型安全性 (any禁止, 明示的型注釈)`), quote the whole line as-is and name the specific sub-rule in Description.
- **Location**: <file:line>
- **Description**: <what violates the rule and why; if quoting a bundled line, name the specific sub-rule here>
- **Suggested fix**: <specific fix to become compliant; for `rule-doc-drift` findings, the literal string given in the rule-doc-drift paragraph above>
- **Confidence**: `high` for hard-rule violations; `low-confidence` for intent-rule borderline findings and for every `rule-doc-drift` finding.
- **Classification**: `code-violation` (default, omit for brevity) | `rule-doc-drift` (only when the finding meets the rule-doc-drift criteria above)
When the same rule line is violated at multiple locations or by multiple sub-rules, emit **one entry per (location, sub-rule)** pair — do not collapse them into a single entry.
Write Description and Suggested fix in plain words, one claim per sentence, with no figure of speech translated word for word; the rule-doc-drift literal stays as given.
If no violations are found, respond with exactly: "No rule violations found"
Before launching reviewers, prepare the data to embed in each prompt (do NOT rely on reviewers running git commands themselves). Reuse the rule file content § 3. Match Rules to Changed Files already read — do not Read a rule file a second time here:
- For each group, run
git diff <base-commit> -- <matched-files>using the union of files matched by any rule in that group. The same file may appear in more than one group's diff. - For each rule file, resolve its
.examples.mdout of the two path lists § 2. Collect Rules step 1 gathered — no new filesystem probe. Take the rule file's path relative to.claude/rules/and replace the trailing.md(and a.localbefore it, when present) with.examples.md:languages/ruby.mdandlanguages/ruby.local.mdboth givelanguages/ruby.examples.md. Look for that sub-path under.claude/rules-extras/; when it is absent, look beside the rule file instead (pre-split layout). Read each resolved file once — a.mdand its.local.mdresolve to the same one. - If no
.examples.mdexists for any rule in the group, omit the## Reference: Code Examplessection entirely from that reviewer prompt (do not write a placeholder line like(no examples file)). - Resolve pointer rules before embedding: if a matched rule file carries no inline enforceable rule text and instead defers its substance to a document outside the scanned tree via a reference link (an
@<path>include, or a markdown link to a doc outside.claude/rules/), resolve that reference andReadthe target so the embedded## Rules to Checkcontent is the actual rule text. If the reference cannot be resolved (target missing, or outside readable scope), do not embed an empty stub: drop the rule from the group and record it as an explicit coverage gap per § 6. Aggregate Results. - When multiple rule files are embedded in one reviewer prompt, separate them with a
### <.claude/rules/... path>sub-heading inside the## Rules to Checksection.
For each reviewer, set the description / task label to the group category name (e.g., "Review rules: frameworks") when the dispatch mechanism supports a label field, and embed the pre-captured diff, rule contents, and examples directly in the prompt text.
6. Aggregate Results
- Collect results from all reviewers (parallel Agents or inline iterations).
- Decide clean vs. not by the entry-class mapping in
## Return contract. When the consolidated list is empty, outputNo rule violations foundas the final prose result, then emit the verdict per## Return contractand end the processing flow. A single synthetic entry goes on to step 3, which renders the list so the coverage gap is clearly visible. - If violations were found:
- Output the consolidated violation list, organized by rule file.
- Use the
## Report Formatfield shape, keeping everylow-confidencemarker.
- Edge cases:
- If a reviewer returns an empty response or a response that does not match either
No rule violations foundor the violation format, retry that group once. If it fails again, include a synthetic entry in the final output under the group name withRule file: (review failed),Description: reviewer returned unparseable output, and continue aggregation for other groups. - A list holding only
low-confidencefindings still renders as a violation list; never substituteNo rule violations foundfor it. - If a rule was dropped during data prep because it is an unresolvable pointer (see § 5's Resolve pointer rules before embedding bullet), include a synthetic entry in the final output with
Rule file: (rule not evaluated — unresolved pointer to <ref>)andDescription: rule body deferred to an out-of-tree document that could not be resolved; left unevaluated rather than reported clean. These coverage-gap entries are synthetic entries for the verdict (see## Return contract).
- If a reviewer returns an empty response or a response that does not match either
Output Format
- Compliant: the prose result is exactly
No rule violations found, and nothing else. - Violations found: a
## Rules Compliance Violationsheading, then one### <.claude/rules/... path>sub-heading per rule file, with that file's entries beneath it in the## Report Formatfield shape.
Return contract
Emit a single fenced JSON block at the end of the response, matching the schema below, after the ## Output Format prose. Emit the verdict on every exit path — including the early exits in § 1. Prepare / § 2. Collect Rules / § 4. Group Rules by Category (those end the processing flow, not the response; the verdict block still follows). Only one fenced JSON block — the verdict block — appears in the response, so callers can locate it unambiguously.
{
"status": "no-issues|violations|error",
"violations_count": 0,
"reason": null
}
Entry classes in the consolidated violation list (§ 6. Aggregate Results). A real finding is an entry a reviewer produced under ## Report Format, whatever its Confidence and Classification. A synthetic entry is one this skill added for a rule that was never evaluated: (review failed) or (rule not evaluated — ...). A group that ran clean contributes no entry.
Status mapping (evaluate in order, first match wins):
violations— the list holds ≥ 1 real finding, whatever else it holds.violations_count= total entries in the list,reason: null.error— the review could not be produced: diff collection failed (§ 1. Prepare), matched rule files could not be read (§ 3. Match Rules to Changed Files), or the list is non-empty with no real finding.violations_count: 0,reason= the enum token below.no-issues— everything else: no changed files (§ 1. Prepare), no rule files (§ 2. Collect Rules), no applicable rules (§ 4. Group Rules by Category), or an empty list.violations_count: 0,reason: null.
Field rules:
violations_count: non-negative integer. Total entries in the consolidated list forviolations;0forno-issuesand forerror, even when theerrorlist holds synthetic entries.reason: one of the listed enum strings, only whenstatus == "error", otherwise JSONnull. No free-form text, newlines, or control characters, so the verdict stays mechanically parseable. Take the first that applies:"diff collection failed"— § 1. Prepare produced no usable changed-file list."rule loading failed"— matched rule files could not be read in § 3. Match Rules to Changed Files."verdict parse failure"— a reviewer group returned unparseable output even after the retry, so the list holds ≥ 1(review failed)entry."coverage gap only"— the list's synthetic entries are all coverage gaps from unresolvable pointers (§ 5's Resolve pointer rules before embedding bullet).
Sub-skill caller directive
When invoked as a sub-skill (i.e. via Skill(rules-review) from an orchestrator), the fenced JSON verdict block this skill emits is the structured return value of the skill's procedure — it is not a deliverable to the user, and emitting it does not terminate the orchestrator's turn. The same agent that ran this skill must immediately issue the next tool call dictated by the orchestrator's flow. Do not insert a prose summary, an acknowledgment, or a "shall I proceed?" sentence between the JSON verdict and the next tool call. Only one fenced JSON block — the verdict block — appears in the response, so callers can locate it unambiguously. The skill's own procedure is over; the orchestrator's procedure continues without pause.
Tidy
The cleanup walk runs in a fresh host-provided reviewer per iteration when reviewer dispatch is available; Edit application stays in the main thread. The skill loops the dispatch + apply cycle until the reviewer returns no more mechanical_edits, max iterations is reached, or a safety rail stops the loop.
Scope: invocation targets are arbitrary source files (application code, config, SKILL.md, any text). The skill does not restrict the changed-file set to a fixed directory prefix — any path in the diff is reviewed unless caught by the exclusion list (Step 1 step 3).
Invocation contract
The caller passes these fields in natural language (the skill extracts them from the invocation text):
-
Base ref(optional, default<working-tree-vs-HEAD>) — git ref to diff against. When omitted, the skill looks at the working tree's uncommitted + staged + untracked changes (the default scope for a post-implementation cleanup pass). When specified (e.g.Base ref: main), the skill switches togit diff <Base ref>semantics — useful for callers that want to review a stack of already-committed changes between a base branch and HEAD.Untracked-file scope asymmetry: the default mode includes untracked new files (collected via
git status --porcelain=v1 --untracked-files=all -z), but the explicitBase refmode reads committed history only and excludes untracked files. A caller passingBase ref: HEAD~5expecting "everything since base" will silently miss new files added sinceHEAD~5that were never committed. If you need untracked files in scope, omitBase refand rely on the working-tree default. -
Max iterations(optional, default3) — upper bound on the refinement loop. -
Custom instructions(optional) — free-form text injected into the dispatch payload as additional constraints alongside the cleanup checklist. -
Model(optional) — model id applied as themodelparameter on the reviewerAgentdispatch in Step 3 (a). A caller such asdev-workflowpasses it to run the cleanup reviewer on a specific model. The same value is applied to every iteration's reviewer dispatch. Effective only on the Claude CodeAgent-dispatch path; on the reviewer-dispatch-unavailable inline fallback (Step 3 (a)) the executing agent's own model governs. Validity predicate: a value is valid only if it is one of the model ids the currentAgenttool'smodelparameter accepts — check the tool's live schema loaded in the current session; a fullclaude-*id (e.g.claude-sonnet-5) is outside that parameter's accepted aliases and is therefore invalid too. An absent field or an invalid value → no override; the reviewerAgentinherits the session model.
The caller must not stage changes while this skill is running. The skill reads the working tree; staged content would mix into the diff and corrupt the verdict. (The Base ref mode reads committed history vs the ref, so staging interference applies only to the default working-tree mode.)
Dispatch authorization
This skill's procedure dispatches subagents, so invoking the skill is the request to use that mechanism: an ambient instruction allowing subagent dispatch only when the user asked for it — a permission-shaped restriction — is already satisfied by this invocation. Do not ask the user to re-confirm the dispatch, and do not silently substitute inline execution for a dispatch this procedure specifies. Only two things justify that substitution: technical availability (the dispatch tool is not present and callable on the current tool surface), and an explicit contract term from the caller bounding this skill to its own thread. A permission-shaped restriction is neither.
Process
Step 1 — Detect changed files (main thread)
- Parse
Base ref,Max iterations,Custom instructions, and the optionalModelvalue from the invocation text per§ Invocation contract. HoldModelfor the Step 3 (a) reviewer dispatch; absent or invalid → no override (inherit). See§ Invocation contract'sModelfield for the validity predicate. - Compute the changed-file set based on
Base ref:- Default mode (no
Base refprovided):git diff --name-onlyfor unstaged tracked changesgit diff --name-only --cachedfor staged tracked changesgit status --porcelain=v1 --untracked-files=all -zand collect entries prefixed??for untracked files
- Explicit
Base refmode (e.g.Base ref: main):git diff --name-only <Base ref>only. Untracked files are out of scope (see§ Invocation contract).
- Default mode (no
- Apply the exclusion list — drop any path matching:
- Lockfiles / dependency manifests:
package-lock.json,pnpm-lock.yaml,yarn.lock,Gemfile.lock,Cargo.lock,poetry.lock,uv.lock,Pipfile.lock,go.sum, any*.lock - Generated / build artifacts: paths under
dist/,build/,node_modules/,target/,vendor/,.next/,.nuxt/ - Binary files (extension-based):
*.png,*.jpg,*.jpeg,*.gif,*.webp,*.ico,*.pdf,*.zip,*.tar,*.gz,*.so,*.dylib,*.exe,*.bin
- Lockfiles / dependency manifests:
- Hold the filtered set in main-thread context as
changed_files(the scope-check baseline for Step 3 (c)). Additionally retain the subset of paths that arrived as??-prefixed entries (untracked files) asuntracked_paths— Step 3 (c)'s frontmatter rail uses it for the HEAD-absent check. - If
changed_filesis empty, emit the verdict{"status": "no-actionable-findings", "iterations_used": 0, "applied_edits_count": 0, "notes_remaining_count": 0, "reverted_paths": [], "reason": null}per§ Return contractand stop.iterations_used: 0because the iteration loop never runs.
Step 2 — Gather review inputs (main thread)
For each entry in changed_files, in the main thread:
Readthe file's full current contents. Hold in main-thread context as the iter-1 snapshot.Readreferences/cleanup-checklist.md.- Pre-capture each changed file's
git diff:- Default mode: for staged-only changes use
git diff --cached -- <file>, for working-tree-only changes usegit diff -- <file>, for mixed staged + unstaged edits concatenate them (staged section first) into one unified diff payload. For untracked files there is no diff (the file did not exist at base) — present the full file contents as the "new file" hunk in the dispatch payload. - Explicit
Base refmode:git diff <Base ref> -- <file>(committed history vs the ref).
- Default mode: for staged-only changes use
Step 3 — Iteration loop (i = 1 .. Max iterations)
Pre-register iteration tasks — before entering the loop, TaskCreate one task per iteration with subject iteration 1, iteration 2, ..., iteration <Max iterations>. Mark in_progress (via TaskUpdate) before each dispatch, completed after parse + apply (a converged iteration marks completed immediately after parsing). On early convergence (no mechanical_edits returned) or safety-rail-triggered exit, mark remaining iteration tasks completed with the skip note recorded in the task's description field as — skipped: converged / — skipped: <reason>. Pre-registration is essential when the host supports it: without it, executor-driven loops tend to stop at the first iteration that looks acceptable.
Task tools unavailable fallback (e.g. the VSCode extension, a Codex host, or a nested subagent context where progress-tracking tools were not provided): skip the pre-registration step and hold iteration state (current i, cumulative applied_edits_count, notes_remaining_count, accumulated out_of_scope, reverted_paths) in main-thread context instead. Progress tracking is not correctness-critical — the loop semantics in (a)–(c) are unaffected.
(a) Dispatch reviewer
On i == 1, use the snapshot from Step 2. On i ≥ 2, only re-Read the subset of changed_files whose path appeared in a successfully-applied mechanical_edits entry during iter i - 1 (untouched files keep their iter-1 snapshot). For that same re-read subset, also re-run the per-file git diff so the diff payload reflects edits applied in prior iterations; files outside the subset keep their iter-1 diff.
Dispatch a fresh reviewer through the current host's reviewer-dispatch mechanism. In Claude Code, use the Agent tool when it is exposed and callable and no caller-imposed nesting bound applies (see the Reviewer-dispatch unavailable fallback paragraph below) — passing the parsed Model value (§ Invocation contract) as the Agent model parameter only when it resolved to a valid override, and omitting it otherwise (absent or invalid → inherit). Apply the same Model decision on every iteration's dispatch. In Codex, use the exposed subagent / delegation mechanism when available. Assemble the dispatch prompt from the five sections below, each framed with a clear --- LABEL --- fence:
--- CLEANUP CHECKLIST ---: the full content ofreferences/cleanup-checklist.md--- CHANGED FILES ---: each changed file's path, full content, and unified diff (one block per file, separated by### <path>sub-headings; for untracked files present "(new file — no prior contents)" before the full current contents)--- CUSTOM INSTRUCTIONS ---: the value ofCustom instructionsfrom the invocation, or the literal(none)placeholder when the field is empty--- REVIEWER PROMPT ---: the reviewer prompt below (verbatim)--- RESPONSE FORMAT ---: the response format and constraints below (verbatim)
Reviewer prompt (include verbatim in the dispatch):
You are a fresh reviewer of changed code. You have not seen prior conversation context — only the CLEANUP CHECKLIST, CHANGED FILES, and CUSTOM INSTRUCTIONS below. Walk the CLEANUP CHECKLIST against each CHANGED FILE.
Preserve functionality (hard constraint): never propose a change that alters observable behavior — features, outputs, error conditions, or side-effect ordering — regardless of which checklist item the finding matches. Read § Preserve functionality at the top of the CLEANUP CHECKLIST as the binding rule. If a candidate fix could plausibly change behavior, downgrade it to a
structural_note; when behavior preservation is clear from the diff and the fix matches § Behavior-preserving structural improvements, amechanical_editis correct.Only the changed lines and their immediately surrounding context are in-scope (lines added or modified, plus surrounding code where the change participates in a structural cleanup opportunity). Do not audit pre-existing untouched code in sibling regions. Project conventions under
.claude/rules/andCLAUDE.mdoverride the checklist where they conflict — defer to them for language-specific / framework-specific standards (import style, function-declaration form, return-type annotation conventions, error-handling patterns, component / module structure).Classify each finding:
- mechanical_edit: a fix that can be applied as a textual replacement — removing a redundant narration comment, deleting a dead branch, replacing a defensive guard on an already-safe path, collapsing a needless local helper, expanding a nested ternary into an
if/else, or a behavior-preserving structural improvement that meets the CLEANUP CHECKLIST's § Behavior-preserving structural improvements conditions. Return as a{file, old_string, new_string, rationale}Edit- structural_note: a fix that requires moving content between files, deleting sections, rewriting large portions, or carries any risk of behavior change. Return as a
{file, description}note. These will not be applied automatically — they are counted innotes_remaining_count
old_stringmust match exactly one location in the current file. Include 1–3 lines of surrounding context so the snippet is unique.If CUSTOM INSTRUCTIONS is non-empty, treat its text as additional constraints — apply alongside (not in place of) the checklist.
Balance rails (required): a candidate
mechanical_editthat would violate § Balance rails — anti-over-simplification at the bottom of the CLEANUP CHECKLIST is not actionable as a mechanical fix even when it matches one of items 1–10. Either downgrade tostructural_noteor skip the finding entirely. § Balance rails and § Preserve functionality are the negative gates (what must not be mechanical); § Behavior-preserving structural improvements is the positive gate a finding reaches only after passing them.Overlap resolution (required): when a finding could match more than one checklist item, apply the Overlap handling rules listed in the CLEANUP CHECKLIST and emit only the preferred classification (first-match-wins per finding — never split one finding across multiple items).
Gate reachability rule (required): when there are no actionable mechanical findings on this iteration, you must return
mechanical_edits: []. Do not emit speculative or "nice to have" edits —mechanical_edits == []is the convergence signal and must be empty when no apply work remains. Continuing to flag issues only asstructural_notesis fine; that is the documented exit path for non-mechanical findings.
Response format (include verbatim in the dispatch):
Write your reasoning and per-file findings in natural language, then end your response with a single fenced JSON block matching this schema:
```json { "mechanical_edits": [ {"file": "<path>", "old_string": "<unique 1-3 line snippet>", "new_string": "<replacement>", "rationale": "<short reason>"} ], "structural_notes": [ {"file": "<path>", "description": "<short description>"} ] } ```
Reviewer-dispatch unavailable fallback: detect availability by inspecting the current tool surface; do not attempt a speculative call just to probe availability. When no host-provided reviewer dispatch is available — the Agent tool is absent from the tool surface (e.g. this skill runs inside a nested subagent context where nested Agent is not surfaced), or the invoking request explicitly bounds this skill to its own thread (a caller-imposed nesting bound — see § Dispatch authorization, which excludes permission-shaped restrictions but not an explicit contract term from the caller) — walk the cleanup checklist over each changed file inline-sequentially in the main thread once per iteration. Being invoked as a sub-skill (e.g. via Skill() on the main thread) does not by itself trigger this path (see § Dispatch authorization): decide by whether Agent is exposed and callable and whether a caller-imposed nesting bound applies. Under the fallback, construct the same fenced JSON block defined above so step (b)'s parser handles both paths identically. Output scope: the per-iteration JSON produced under fallback is internal state for step (b)'s parser — hold it in main-thread context only; do not write it into the user-visible response. Only the terminal verdict JSON from § Return contract appears in the response (see the uniqueness clause there).
(b) Parse & apply — evaluate in this order, first match wins
Dispatch failures (reviewer-dispatch tool error / timeout / empty response) are handled in § Dispatch failure before this parse step runs and do not enter sub-cases 1–4 below.
- Verdict missing or malformed — no fenced JSON block found, or JSON parse fails → exit loop with terminal
{"status": "error", "iterations_used": <i>, "applied_edits_count": <cumulative>, "notes_remaining_count": 0, "reverted_paths": [], "reason": "verdict parse failure"}. Do not consume remaining iter slots. - Schema violation — required keys (
mechanical_edits,structural_notes) are missing, values are not arrays, or any entry fails its expected per-entry shape (mechanical_editsentries must have non-empty stringfile,old_string,new_string;structural_notesentries must have non-empty stringfile,description) → exit loop with terminal{"status": "error", "iterations_used": <i>, "applied_edits_count": <cumulative>, "notes_remaining_count": 0, "reverted_paths": [], "reason": "verdict schema violation"}. - No more apply work —
mechanical_edits == []→ exit loop. Determine the terminal status from cumulative state and the current iter'sstructural_notes:- cumulative
applied_edits_count == 0ANDstructural_notes == []→no-actionable-findings - cumulative
applied_edits_count > 0ANDstructural_notes == []→applied-edits(notes count = 0) structural_notes != [](regardless of cumulative count) → if cumulative > 0 thenapplied-edits(withnotes_remaining_count > 0), elsenotes-left
- cumulative
- Otherwise — apply
mechanical_editsin order:- For each entry, verify
file ∈ changed_files; if not, record the path in anout_of_scopelist and skip the entry without callingEdit. Theout_of_scopelist is later listed inreverted_pathsin the terminal verdict if non-empty. - For each in-scope entry, re-
Readthe target file (soold_stringmatches the current contents after any earlier edit was applied), then callEdit. - If an
old_stringis not found, skip that entry and continue with the next. This is expected when the reviewer emits multiple edits from a single snapshot and a later edit overlaps a region an earlier one already rewrote — the skip is a no-op fallback, not an error. - Increment
applied_edits_countonly for entries whoseEditcall succeeded — skipped entries do not count. - After the edits (applied or skipped), if at least one Edit succeeded, run the safety rails in (c), then continue to iteration
i + 1. If all entries skipped, also continue (the next iter will re-dispatch with the current file state).
- For each entry, verify
(c) Per-iteration safety rails — run only if at least one edit was applied
-
Frontmatter integrity — for each edited file that begins with a
----delimited YAML frontmatter block, re-Readand parse the frontmatter. If parsing fails:git checkout HEAD -- <file>Exit loop with terminal
{"status": "error", "iterations_used": <i>, "applied_edits_count": <surviving on disk>, "notes_remaining_count": 0, "reverted_paths": [<file>], "reason": "frontmatter broken"}.applied_edits_countreflects edits still on disk after the revert (the revert wipes this file's prior-iter contributions; cross-file edits to other paths in earlier iters survive). Files without a frontmatter block skip this rail.Untracked-path specialization: if the offending file is in
untracked_paths(i.e. HEAD-absent — the iteration just edited an untracked new file), skip thegit checkoutfor HEAD-absent paths; the file is left in its post-edit state,applied_edits_countretains all surviving on-disk edits (no revert occurred), andreverted_pathsstill carries the offending path as an informational entry so the caller sees what could not be reverted. -
Scope — if the
out_of_scopelist accumulated by (b) step 4 is non-empty for this iteration, exit loop with terminal{"status": "error", "iterations_used": <i>, "applied_edits_count": <cumulative>, "notes_remaining_count": 0, "reverted_paths": <out_of_scope>, "reason": "scope violation"}(the pre-check already skipped those writes; nogit checkoutruns).
Step 4 — Max iterations reached without convergence
If the loop runs all Max iterations without (b) sub-case 3 firing (i.e. the reviewer kept emitting mechanical_edits to the end, but apply progress stalled — typically all entries skipping because old_string collisions), determine the terminal status from cumulative state and the last iter's structural_notes:
- cumulative
applied_edits_count > 0→applied-edits(notes_remaining = last-iterstructural_notescount) - cumulative
applied_edits_count == 0AND last-iterstructural_notes == []→no-actionable-findings - cumulative
applied_edits_count == 0AND last-iterstructural_notes != []→notes-left
Step 5 — Emit verdict
Emit the verdict per § Return contract. See § Sub-skill caller directive for the caller-side no-stall discipline that applies when this skill is invoked as a sub-skill.
Scope
- Only review files that have uncommitted changes (default mode) or that appear in the
Base ref-vs-HEAD diff — diff-scoped, not a full audit - Project conventions (
.claude/rules/,CLAUDE.md) override the checklist where they conflict - Don't chase perfection — fix real cleanup wins, note structural ones, move on
- Sub-skill scope note (caller-side): when this skill runs as a sub-skill, structural changes are counted in
notes_remaining_countrather than applied. The caller decides whether and how to act on them. See§ Sub-skill caller directivefor the no-stall discipline that applies on the sub-skill invocation path.
Return contract
Only one fenced JSON block must appear in the user-visible response — the verdict block. Intermediate structured outputs that the skill constructs internally for its own parser (e.g., the per-iteration reviewer JSON synthesized under the Agent-unavailable fallback path) are held in main-thread context and do not enter the response stream.
Emit a single fenced JSON block at the end of the response, matching the schema:
{
"status": "no-actionable-findings|applied-edits|notes-left|error",
"iterations_used": N,
"applied_edits_count": N,
"notes_remaining_count": N,
"reverted_paths": ["<path>", "..."],
"reason": "verdict parse failure|verdict schema violation|frontmatter broken|scope violation|dispatch error|null"
}
The |null token at the end of the reason enum means JSON null (not the string "null").
Field semantics:
status:no-actionable-findings: the iteration loop converged with cumulativeapplied_edits_count == 0AND nostructural_notesoutstandingapplied-edits: at least one mechanical fix was applied across the iteration loop (cumulativeapplied_edits_count > 0);notes_remaining_countmay be0(clean convergence) or> 0(notes alongside applied edits)notes-left: cumulativeapplied_edits_count == 0ANDnotes_remaining_count > 0(only structural changes were flagged, counted innotes_remaining_count)error: an internal error occurred — seereason
iterations_used: number of iterations whose reviewer dispatch returned a verdict, including the iteration whose verdict triggered convergence. Step 1 early returns (no changed files after exclusion) count as0applied_edits_count: non-negative integer count ofEditcalls whose result is still on disk at the time the verdict is emitted. Forverdict parse failure/verdict schema violation/dispatch error/scope violation, this is the cumulative count of successfulEditcalls across earlier iterations of the same invocation (none of these recovery paths revert in-scope edits —scope violationonly flags the offending out-of-scope paths informationally). The exception isfrontmatter broken: its recovery reverts the edited file itself (or skips the revert for an untracked HEAD-absent path), so the count drops accordinglynotes_remaining_count: non-negative integer. Count of structural / still-actionable items flagged in the terminal iteration but not applied. Always0forno-actionable-findingsand anyerrorstatusreverted_paths: array of<path>strings. Empty array[]forno-actionable-findings/applied-edits/notes-left/verdict parse failure/verdict schema violation/dispatch error/ Step 1 early returns. Forfrontmatter broken: contains the offending file path in both branches (HEAD-present revert: path was reverted; HEAD-absent: path retained as informational entry since the rail skippedgit checkout). Forscope violation: contains theout_of_scopepaths the pre-check rejected (nogit checkoutran; the entries are informational rejected-write records).reason: enum string only whenstatus == "error", otherwise JSONnull. Keepreasonpayloads to the listed enum tokens — no free-form text, newlines, or control characters — so the verdict stays mechanically parseable
When to emit status: "error":
reason: "verdict parse failure"— an iteration found no fenced JSON block in the reviewer response, or JSON parse failedreason: "verdict schema violation"— an iteration parsed the JSON but required keys (mechanical_edits,structural_notes) are missing, values are not arrays, or any entry fails the per-entry shape specreason: "frontmatter broken"— a per-iteration safety rail re-read after Edit shows the YAML frontmatter no longer parses; the offending file is reverted viagit checkout HEAD -- <file>(or left as-is for untracked HEAD-absent paths and recorded inreverted_paths)reason: "scope violation"— the pre-check accumulated one or more out-of-scope target paths inmechanical_edits(the writes were already skipped; the verdict lists the rejected paths informationally inreverted_paths)reason: "dispatch error"— a reviewer-dispatch tool call errored, timed out, or returned an empty response
In each error case, report the verdict in the JSON instead of attempting recovery; the caller decides how to handle it.
Dispatch failure
If the reviewer-dispatch tool call itself errors, times out, or returns an empty response on any iteration, exit the loop with terminal {"status": "error", "iterations_used": <i>, "applied_edits_count": <cumulative>, "notes_remaining_count": 0, "reverted_paths": [], "reason": "dispatch error"}. Do not re-walk the checklist yourself as a fallback after a failed dispatch attempt — self-review reintroduces the bias this skill exists to avoid. Inline review is only the pre-selected path when dispatch is unavailable before attempting a reviewer tool call.
Sub-skill caller directive
When invoked as a sub-skill (i.e. via Skill(tidy) from an orchestrator), the fenced JSON verdict block this skill emits is the structured return value of the skill's procedure — it is not a deliverable to the user, and emitting it does not terminate the orchestrator's turn. The same agent that ran this skill must immediately issue the next tool call dictated by the orchestrator's flow. Do not insert a prose summary, an acknowledgment, or a "shall I proceed?" sentence between the JSON verdict and the next tool call. Only one fenced JSON block — the verdict block — appears in the response, so callers can locate it unambiguously. The skill's own procedure is over; the orchestrator's procedure continues without pause.
Stop hook structural conflict (caller-side note)
On Claude Code on the Web the auto-installed ~/.claude/stop-hook-git-check.sh fires on every Stop event and feeds back Please commit and push… between Process steps; treat each fire as a spurious fire — record it, ignore the prose, and run Process steps 1–5 to completion. Do not commit from inside this skill; commit policy lives with the caller.
Sponsors
Details
- Marketplace
- hiroro-work/claude-plugins
- Source
- plugins/dev-workflow-bundle
- Author
- hiropon
- Category
- Workflow
More from hiroro-work/claude-plugins
All 22- extract-rulesv1.31.0
- furikaeriv1.0.2
- kabeuchiv3.1.1
- merge-rulesv2.1.3
- mobprov2.0.1
- peerv2.6.7
- prose-polishv1.9.0
- rules-reviewv1.8.8
- security-scannerv1.3.2
- tidyv1.6.4
- translatev1.1.2
- apply-rulesv2.1.3
- artifactorv1.1.3
- ask-agyv1.0.1
- ask-claudev1.1.4
- ask-codexv1.2.4
- ask-copilotv1.0.5
- ask-geminiv1.2.3
- caffeinatev1.0.0
- demov1.14.0
- dev-workflowv2.17.0