Claude Code skills and hooks: from the concepts to project rules in practice
Using Claude Code led to repeated instructions. Check the approved task first. Do not edit committed migrations. Change the contract before adding an event. Format files after editing them. Writing an instruction once and applying it at the right moment every time turned out to be different problems.
This post is for readers who have used Claude Code but are new to its extension features. It first distinguishes when each feature enters context and who decides to run it. It then examines how a personal shopping project for learning and teaching, poppy-shop, moved some repeated instructions into skills and hooks.
The concepts follow the official Claude Code documentation. The case results come from Claude Code session records dated October 29, 2026.
How Claude Code handles one request
Section titled âHow Claude Code handles one requestâThe official explanation describes the agentic loop as gathering context, taking action, and verifying results repeatedly. Asked to fix a failing test, Claude might find files, read code, make an edit, inspect the test result, and decide what to do next. Producing one response can involve several tool calls.
Here Claude is the model deciding what to do, while Claude Code is the program providing tools and settings and coordinating execution. A skill generally gives the model a procedure. The command hooks in this post instead have the program execute a command at a defined event.
Think of CLAUDE.md as a note kept at hand, a skill as a manual opened when needed, and a hook as a check that runs at a particular moment. A subagent is a colleague working in a separate context; /loop schedules the same request to come back later.
| Feature | When context is added | Selection or execution | Purpose |
|---|---|---|---|
CLAUDE.md | Startup or nested-file access | Loaded by Claude Code | Project principles |
| Skill | Description ahead of time; body on invocation | Person or Claude | Task steps |
| Command hook | Results from an event | Claude Code | Blocking or formatting |
| Subagent | Separate context for delegated work | Claude or a personâs request | Role-specific work |
/loop | Scheduled prompt execution | Invocation and scheduling tools | Repeated checks |
Keep project-wide guidance in CLAUDE.md. The memory documentation recommends concise, specific instructions. Ancestor instructions load at startup; nested instructions load when files in that directory are read or changed.
A subagent can have its own context window, role instructions, available tools, and permissions. Delegating a review avoids filling the main conversation with every investigation output while still returning results. Use a separate checkout or worktree when file isolation is needed.
Permissions are a separate layer deciding whether tools may run. Skill selection and hook results are processed within that permission flow.
The diagram shows one pass in which a skill is invoked and a tool succeeds. If the result calls for more work, context gathering and tool selection repeat.
A skill attaches a procedure to the relevant task
Section titled âA skill attaches a procedure to the relevant taskâIn the skills documentation, the basic unit is a SKILL.md file inside a directory. Use .claude/skills/<name>/SKILL.md for a shared project skill and ~/.claude/skills/<name>/SKILL.md for a personal skill across projects.
The file contains YAML frontmatter and a Markdown body. name sets its name; description helps Claude decide when to select it. Both can be explicit, as below. In the current Claude Code documentation, frontmatter fields are not all mandatory; the directory name is used when the name is omitted.
---name: add-migrationdescription: Change a service DB schema with Flyway migrations. Use when the user asks to "add a migration", "add a column", "create a table", "change the schema", or "change seed data", or when an entity needs a new persisted field.---# Add a migration
The source rules are the DB rules in AGENTS.md and section 5 of docs/guides/service-template.md.Read both before starting. This skill contains only steps and checkpoints.
## Before starting- Is this change within an approved tasks.md task? If not, stop and ask a person.
## Steps1. Choose the next migration number after the current maximum.2. Write a failing test first.3. Write a new migration file. Do not edit a committed migration.4. Align the entity. Keep ddl-auto: validate.5. Build only the changed service.
## Checkpoints- [ ] No committed db/migration file appears in the diff.This is a shortened excerpt of the caseâs skill, with its Korean text translated into English. The description includes expressions a person would actually use, not just a technical category. The intent was to connect a request such as âadd a column to productâ to the migration procedure.
A person can explicitly request the procedure by typing /add-migration in Claude Code. Frontmatter can control automatic invocation, so the basic description here assumes a skill without an additional invocation restriction.
Putting every long procedure into CLAUDE.md adds overhead even in sessions that do not need it. A skill body loads only when used, so keep standing principles in CLAUDE.md and move situational steps into skills. This case did not copy every detailed rule from the source documents. Skills point to those documents and retain only the steps and checkpoints.
Custom commands are no longer a separate system to memorize. Both .claude/commands/x.md and .claude/skills/x/SKILL.md create /x. Existing command files keep working, while new procedures can use a skill directory with supporting files. Claude Code skills follow the Agent Skills open standard and add features such as invocation controls.
There are also bundled skills. Examples in the checked documentation include /doctor, /code-review, /batch, /debug, /loop, and /claude-api. A / prefix does not make everything the same kind of feature. Bundled skills provide instructions to Claude and differ from built-in commands such as /help. Check the commands documentation and the installed version for availability.
A hook fixes an execution point in code
Section titled âA hook fixes an execution point in codeâThe hooks guide describes hooks as user-defined actions at particular points in the session lifecycle. This post covers type: "command", which executes a command. Prompt-based and agent-based hooks are different types that use a model.
Claude Code calls a command hook without Claude having to decide to run that check each time. It is deterministic in the sense that matching events and conditions trigger the command.
The following selects only major events from the reference. Use the official documentation for the complete list and input schemas.
| Scope | Major events | Timing and purpose |
|---|---|---|
| Session | SessionStart, SessionEnd | Session entry, such as startup or resumption, and session exit |
| User turn | UserPromptSubmit | Before Claude processes the user prompt |
| Before a tool call | PreToolUse | Pre-execution checks and blocking |
| After a tool call | PostToolUse | Checks, formatting, and feedback after a tool succeeds |
| Response completion | Stop | When Claude is about to finish a response, not the session |
A matcher narrows the target within an event. For tool events, Edit|Write matches those two tool names. The scripts in this case check Java extensions and migration paths.
A command hook receives JSON on stdin. For file tools, it can read tool_input.file_path. Output and exit-code meanings depend on the event. The following is an introductory summary for synchronous command hooks without separate JSON decision output.
| Exit status | Default meaning | Meaning in this case |
|---|---|---|
0 | Success. Without a separate blocking decision, continue the normal permission flow | Not a target, edit permitted, or formatting succeeded |
2 | Block or provide feedback, depending on the event | PreToolUse blocks Edit or Write; PostToolUse delivers stderr to Claude |
| Other | A non-blocking error by default | A failed check is not successful protection |
This case uses the default exit-code flow in the table. JSON decision output and onFailure: "block" change that behavior; consult those reference sections when adding such controls.
PostToolUse runs after the edit. This implementation stays quiet on success and uses stderr with exit 2 on failure to ask Claude for follow-up.
Distinguish two meanings of loop
Section titled âDistinguish two meanings of loopâThe agentic loop is the basic process for handling one request. /loop is a bundled skill for repeatedly executing a prompt. Neither is the same as a hook reacting to a tool event.
The following is conceptual input only. This case did not use /loop.
/loop 5m check whether the current build has finished and summarize its resultThe scheduled tasks documentation describes scheduling prompts at an interval. Execution happens while Claude Code is running and available to accept work, so scheduled work follows the response already in progress.
Execution stops when the session process exits. Resuming with --resume or --continue can restore unexpired CronCreate tasks. Past-due one-shot tasks and expired recurring tasks are excluded. A self-paced /loop that chooses its own intervals needs to be started again.
The case started with human-approved tasks
Section titled âThe case started with human-approved tasksâpoppy-shop is a personal project using an AIDD workflow in which a person approves tasks and AI implements them. After repeated instructions throughout Phases 0 through 4, spec 0011, âAIDD skills and hooks,â organized those instructions. The goal was not to automate approval, but to reduce missed steps while executing already approved work.
The selected scope was two hooks and three skills.
| Kind | Name or location | Responsibility |
|---|---|---|
PreToolUse | .claude/hooks/protect-migrations.mjs | Block Edit or Write attempts against migrations committed in HEAD |
PostToolUse | .claude/hooks/format-java.mjs | Format the single edited Java or Gradle Kotlin file |
| Skill | add-migration | Order migration and entity changes |
| Skill | add-event | Order contracts, tests, and event implementation |
| Skill | add-service | Create service scaffolding and check recurring pitfalls |
This case focuses on procedures and tool calls inside Claude Code. The existing collaboration post covers operating multiple sessions and using the herdr skill, so those topics are not repeated here.
Why the repository uses only Claude Code hooks
Section titled âWhy the repository uses only Claude Code hooksâRegistration lives in .claude/settings.json; no git hook was added. AI performs implementation in this repository, so Claude Code tool calls were the target. Cloning the shared settings avoids a separate git-hook installation step. Human commits are covered by review and CI.
The scripts are .mjs files using only Node standard libraries. Node is already required. Reusing it for JSON input avoids adding jq or Python dependencies or writing the script body in Bash.
The case registers its hooks as follows.
{ "hooks": { "PreToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/protect-migrations.mjs\"", "timeout": 10 } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/format-java.mjs\"", "timeout": 15 } ] } ] }}CLAUDE_PROJECT_DIR locates the hooks, and the script path is quoted. Workspace trust also applies in interactive sessions. The current reference says -p and SDK sessions can execute settings-file hooks without displaying that trust dialog, so inspect .claude/ settings before running headlessly against an unfamiliar repository.
Block committed migrations before execution
Section titled âBlock committed migrations before executionâThe DB rules in AGENTS.md say not to modify a committed migration. Changing an already applied Flyway migration can fail checksum validation and prevent service startup. Express the change in a new migration with the next number.
The check covers Edit and Write targets under src/main/resources/db/migration/. It uses git cat-file -e to check whether the file exists in HEAD and exits 2 if it does. New uncommitted files are allowed even when staged, and db/seed is outside the path condition.
The following core excerpt shows the protection check. Imports have been added, and the diagnostic has been translated from Korean and shortened.
import { readFileSync, existsSync } from 'node:fs';import { resolve, dirname, basename } from 'node:path';import { spawnSync } from 'node:child_process';
const MIGRATION_DIR = /(^|\/)src\/main\/resources\/db\/migration\//;function filePath() { try { const input = JSON.parse(readFileSync(0, 'utf8')); const path = input?.tool_input?.file_path; return typeof path === 'string' && path.length > 0 ? resolve(path) : null; } catch { return null; }}const path = filePath();if (path === null || !MIGRATION_DIR.test(path.replaceAll('\\', '/')) || !existsSync(dirname(path))) process.exit(0);const committed = spawnSync('git', ['-C', dirname(path), 'cat-file', '-e', `HEAD:./${basename(path)}`]);if (committed.status !== 0) process.exit(0);process.stderr.write('Do not edit a committed migration. Add V<n>__<desc>.sql instead. A human must review any exceptional direct edit.\n');process.exit(2);Because git -C queries from the target fileâs directory, HEAD:./<filename> is interpreted relative to that location. The hook checks existence without including file contents in its output.
Format only the edited file immediately afterward
Section titled âFormat only the edited file immediately afterwardâThe formatting hook runs after a successful Edit or Write and targets only *.java and *.gradle.kts. The case projectâs Spotless configuration accepts -PspotlessIdeHook=<file> with spotlessApply to process that single file.
Gradle runs from the repository root containing the target file. A file in a worktree uses that worktreeâs root. The scope avoids processing another checkoutâs or builderâs files along with the intended file.
The Claude Code hook timeout is 15 seconds, with a 12-second internal execution limit. If another Gradle process holds a lock beyond that limit, the hook advises running ./gradlew spotlessApply before committing and ends.
Paths these hooks do not cover, and temporary disabling
Section titled âPaths these hooks do not cover, and temporary disablingâBoth hooks match Edit|Write. Their limits follow from that scope.
- Bash edits through
sed -ior a heredoc, direct human edits, and commits are outside these two hooks. - The migration check is fail-open: unreadable JSON or a failed git lookup allows the edit. This reduces false blocking but loses protection when checking fails. The code above illustrates the check rather than providing a complete deployment script.
- Formatting depends on the projectâs Spotless file-scoping configuration. Failure feedback from
PostToolUsedoes not undo a completed edit. Ordinary stdout on success does not by itself deliver feedback to Claude. - Execution requires Node, project tools, and enabled hooks. Script bugs, timeouts, the registration commandâs shell, and OS differences also matter.
CLAUDE.mdsupplies guidance and skills help select procedures. Neither grants permissions, and automatic skill selection can be missed./loopschedules work within a running session. Work requiring an always-on scheduler with an exact wall-clock cadence needs a separate design.- The formatting-hook tests below use a fake Gradle. They do not validate real lock waits or every OS combination. Skill selections in the five sessions are observations for those requests.
Review therefore checks committed migration changes again, and ./gradlew spotlessApply remains the final formatting step before committing. Adding hooks did not remove review or final checks.
For an incorrectly blocked exception, a person reviews the reason and edits directly in an editor. The workflow does not tell Claude to bypass the hook through Bash. To disable hooks temporarily in personal project settings, merge the following into the git-ignored .claude/settings.local.json. Do not replace an existing personal settings file wholesale.
{ "disableAllHooks": true}This disables all hooks in the applicable scope, not just one. Revert the temporary setting afterward and check registration with /hooks. Changing shared .claude/settings.json affects other people and sessions using that change. Current documentation does not allow personal settings to disable managed hooks. If the personal file is created by hand, also check that git ignores it.
Why not automate every repeated instruction
Section titled âWhy not automate every repeated instructionâThe three skills point to source documents: add-event to docs/contracts/README.md, add-service to docs/guides/service-template.md, and add-migration to that guide and the DB rules in AGENTS.md. This avoids duplicating rules across files that can diverge when the source changes.
Spec 0011 also considered whether each repeated workflow needed a new feature.
| Repeated workflow | Decision | Reason |
|---|---|---|
| Turn intent into spec, plan, and tasks | Existing intent-to-spec skill | The procedure already exists |
| Review specs and implementation | Existing poppy-reviewer subagent | The role is already separate |
| Pass worktree, branch, and base commit to review | Review instructions in CLAUDE.md | Three lines of information; transport depends on the environment |
| Prepare the final verdict | Keep the existing process | The final task checks acceptance criteria; the reviewer has isolated-build steps |
| Update Phase tables and intent state | Keep the existing process | Automating human-approved shared documents would blur approval boundaries |
| Worktree and parallel-development rules | CLAUDE.md | Do not generalize restrictions valid only when several builders share one checkout |
| Failing test first, one task per commit | Keep the existing process | Already in AGENTS.md and tasks |
| Check Spring Boot 4 property names | add-service checkpoints | A recurring pitfall when creating order, payment, and BFF services |
Parallel-work rules such as prohibiting git add -A in the main checkout were not enforced with a hook. They are useful in a shared checkout but can block normal commands for someone working alone. Rules whose applicability cannot be determined precisely retain their context and rationale in documentation.
Behavior observed in tests
Section titled âBehavior observed in testsâThe command below tests the hook scripts. The session records that follow cover model selection of skills separately.
node --test '.claude/hooks/*.test.mjs'In the case, protect-migrations.test.mjs has 94 lines and format-java.test.mjs has 98. The formatting tests inject a fake Gradle through an environment variable.
Five Claude Code sessions on October 29, 2026 produced the following observations.
| Request or test | Observation | What it demonstrated |
|---|---|---|
Edit committed V1__catalog.sql | PreToolUse blocked the edit and the file stayed unchanged. Claude did not retry or bypass it | Blocking on that Edit path and the sessionâs subsequent response |
Add a product description column, maximum 500 characters | Automatically selected add-migration; a failing test, new V4__product_description.sql, entity change, and passing product-service build | Skill selection from its description and steps for approved work |
| Publish an event on stock arrival | Selected add-event; changed asyncapi.yaml, contract tests, failing tests, implementation, then built changed modules | A contract-first workflow |
| Create review-service scaffolding | Selected only add-service; explained that no tables or events required the other skills. The formatting hook also ran | Distinguishing necessary from unnecessary skills |
| Create a Java file with Write | The formatting hook reformatted the file immediately after writing | Actual file processing through PostToolUse |
In the first test, the error Claude received began with PreToolUse:Edit hook error and continued with the scriptâs reason not to edit a committed migration. This was the program blocking a tool before execution, not simply Claude remembering a rule and declining to edit.
The stock-arrival event had no subscribers, so the result included x-poppy-subscribers: [] and a reason. Conversely, the review-service test did not force unnecessary migration or event procedures. That is why the checks covered appropriate selection and outputs, not merely the existence of skill names.
Deciding where each rule belongs
Section titled âDeciding where each rule belongsâ| Question | Location | Criterion in this case |
|---|---|---|
| Is it a short principle needed for almost all work? | CLAUDE.md | Approved tasks, work boundaries, review handoff information |
| Is it a sequence needed only for a particular task? | Skill | Migration, event, and service creation |
| Can the execution point be identified by tool and path? | Command hook | Protection before Edit or Write and formatting afterward |
| Does it need a separate role and context? | Subagent | Spec and implementation reviewer |
| Does it require human approval or preserved rationale? | Source documents and tasks | Phase and intent state, conditional parallel-work rules |
| Does it need another check after a time interval? | Consider /loop | Not used in this case |
Skills helped locate the relevant procedure; hooks fixed execution points on particular tool paths. The central distinction is between guidance, selection, execution, and verification. Automatic selection can be missed, hooks cannot see out-of-scope changes, and formatting failures do not undo edits. Checkpoints, review, and pre-commit verification therefore remain part of the workflow.
Official documentation
Section titled âOfficial documentationâThese are the sources for the concepts above. The documents were checked on October 29, 2026.