Skip to content

Claude Code skills and hooks: from the concepts to project rules in practice

Interactive Diagram

새 탭 ↗

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.

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.

FeatureWhen context is addedSelection or executionPurpose
CLAUDE.mdStartup or nested-file accessLoaded by Claude CodeProject principles
SkillDescription ahead of time; body on invocationPerson or ClaudeTask steps
Command hookResults from an eventClaude CodeBlocking or formatting
SubagentSeparate context for delegated workClaude or a person’s requestRole-specific work
/loopScheduled prompt executionInvocation and scheduling toolsRepeated 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.

PlantUML Diagram

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.

.claude/skills/add-migration/SKILL.md
---
name: add-migration
description: 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.
## Steps
1. 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.

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.

ScopeMajor eventsTiming and purpose
SessionSessionStart, SessionEndSession entry, such as startup or resumption, and session exit
User turnUserPromptSubmitBefore Claude processes the user prompt
Before a tool callPreToolUsePre-execution checks and blocking
After a tool callPostToolUseChecks, formatting, and feedback after a tool succeeds
Response completionStopWhen 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 statusDefault meaningMeaning in this case
0Success. Without a separate blocking decision, continue the normal permission flowNot a target, edit permitted, or formatting succeeded
2Block or provide feedback, depending on the eventPreToolUse blocks Edit or Write; PostToolUse delivers stderr to Claude
OtherA non-blocking error by defaultA 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.

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.

Example Claude Code input
/loop 5m check whether the current build has finished and summarize its result

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

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.

KindName or locationResponsibility
PreToolUse.claude/hooks/protect-migrations.mjsBlock Edit or Write attempts against migrations committed in HEAD
PostToolUse.claude/hooks/format-java.mjsFormat the single edited Java or Gradle Kotlin file
Skilladd-migrationOrder migration and entity changes
Skilladd-eventOrder contracts, tests, and event implementation
Skilladd-serviceCreate 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.

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.

.claude/settings.json
{
"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.

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.

.claude/hooks/protect-migrations.mjs core excerpt
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.

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 -i or 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 PostToolUse does 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.md supplies guidance and skills help select procedures. Neither grants permissions, and automatic skill selection can be missed.
  • /loop schedules 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.

Setting to merge into .claude/settings.local.json
{
"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.

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 workflowDecisionReason
Turn intent into spec, plan, and tasksExisting intent-to-spec skillThe procedure already exists
Review specs and implementationExisting poppy-reviewer subagentThe role is already separate
Pass worktree, branch, and base commit to reviewReview instructions in CLAUDE.mdThree lines of information; transport depends on the environment
Prepare the final verdictKeep the existing processThe final task checks acceptance criteria; the reviewer has isolated-build steps
Update Phase tables and intent stateKeep the existing processAutomating human-approved shared documents would blur approval boundaries
Worktree and parallel-development rulesCLAUDE.mdDo not generalize restrictions valid only when several builders share one checkout
Failing test first, one task per commitKeep the existing processAlready in AGENTS.md and tasks
Check Spring Boot 4 property namesadd-service checkpointsA 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.

The command below tests the hook scripts. The session records that follow cover model selection of skills separately.

Terminal window
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 testObservationWhat it demonstrated
Edit committed V1__catalog.sqlPreToolUse blocked the edit and the file stayed unchanged. Claude did not retry or bypass itBlocking on that Edit path and the session’s subsequent response
Add a product description column, maximum 500 charactersAutomatically selected add-migration; a failing test, new V4__product_description.sql, entity change, and passing product-service buildSkill selection from its description and steps for approved work
Publish an event on stock arrivalSelected add-event; changed asyncapi.yaml, contract tests, failing tests, implementation, then built changed modulesA contract-first workflow
Create review-service scaffoldingSelected only add-service; explained that no tables or events required the other skills. The formatting hook also ranDistinguishing necessary from unnecessary skills
Create a Java file with WriteThe formatting hook reformatted the file immediately after writingActual 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.

QuestionLocationCriterion in this case
Is it a short principle needed for almost all work?CLAUDE.mdApproved tasks, work boundaries, review handoff information
Is it a sequence needed only for a particular task?SkillMigration, event, and service creation
Can the execution point be identified by tool and path?Command hookProtection before Edit or Write and formatting afterward
Does it need a separate role and context?SubagentSpec and implementation reviewer
Does it require human approval or preserved rationale?Source documents and tasksPhase and intent state, conditional parallel-work rules
Does it need another check after a time interval?Consider /loopNot 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.

These are the sources for the concepts above. The documents were checked on October 29, 2026.