見出し画像

開発も記事生成も、AIは「ハーネス」で強くなる

Claude CodeのSkills/Hooks/Subagentsで“再現性”を資産化する設計

生成AIを日常運用していると、最初はうまくいっても、次第にこう感じ始めます。

  • 返答の品質が日によってブレる

  • 途中から会話が汚れて、意図と違う方向へ行く

  • 「毎回同じこと」を言い直している

  • そして、手順・ノウハウが資産にならない

ここで効いてくるのが「ハーネス(harness)」という発想です。
Anthropicは、Claude Agent SDKを 汎用の“agent harness”として位置づけ、コンテキスト管理(compaction など)を備えていても、それだけでは長距離タスクに十分ではない、と述べています。

この記事では、Claude Codeで実装できる「ハーネス」の部品(CLAUDE.md / Skills / Hooks / Subagents / Slash Commands)を整理し、開発と記事生成を同じ骨格で運用するための最小テンプレまで落とし込みます。



ハーネスとは何か(結論:モデルではなく“箱”を育てる)

ハーネスを一言で言うと、LLMを“現場で再現性高く動かす”ための外側の仕組みです。

Anthropicの「長時間稼働エージェント」の話では、compaction があってもそれだけでは不十分で、初回に環境を整える initializer agent と、毎回少しずつ前進しつつ次セッションに引き継げる成果物を残す coding agent という二段構えを提示しています。
つまり、重要なのは「賢いモデルを一発当てる」よりも、継続運用で劣化しない“作法と仕組み”を持つことです。

この発想は、そのまま記事生成にも当てはまります。
「構成」「文体」「根拠の扱い」「仕上げチェック」を、プロンプトの気合ではなく 仕組みとして固定できるかが、継続品質を左右します。


Claude Codeでの“ハーネス部品”を整理する

ここからは、Claude Codeで実際に使える部品を、役割ベースで整理します。

1) CLAUDE.md:不変ルールの置き場(ただし膨らませない)

CLAUDE.md はセッションに自動で取り込まれ得る指示ファイルで、/init で自動生成されることも明記されています。
また、親ディレクトリ/子ディレクトリ配置など複数の探索ルールがあり、運用で共有しやすい形(git管理)も推奨されています。

重要なのは、Anthropic自身が「CLAUDE.md は頻用プロンプト同様にチューニングすべきで、内容を増やすだけは失敗しやすい」と釘を刺している点です。

結論:CLAUDE.mdは“最小”にして、詳細は後述のSkills/Commandsへ逃がす。


2) Skills:手順と知識を“段階的開示”で資産化する

Skills は SKILL.md を含むディレクトリとして管理され、YAMLフロントマター+Markdown本文で定義します。
ポイントは、補助ファイル(scripts/templates等)を同梱しても、必要なときだけ読む(progressive disclosure)ことでコンテキストを節約する設計であることです。

さらに、Skills は以下の場所から自動発見されます。

  • 個人:~/.claude/skills/

  • プロジェクト:.claude/skills/

  • プラグイン同梱(plugin skills)

また allowed-tools で「このSkill中はこのツールしか使えない」を制限でき、これは Claude CodeのSkillsにのみ対応と明記されています。

結論:Skillsは“再現性の中核”。PDCAで育てる対象そのもの。


3) Slash Commands:人が明示的に起動する定型手順

Slash Command は、Markdownファイルとして .claude/commands/(プロジェクト)または ~/.claude/commands/(個人)に置きます。
引数は $ARGUMENTS(全部)や $1, $2…(位置引数)で参照でき、frontmatterで allowed-tools / argument-hint / model 等も指定できます。

結論:Commandsは「人が押すボタン」。習慣化に効く。


4) Subagents:関心分離と“文脈汚染”対策

Subagents は、特定目的に特化したエージェントで、メイン会話とは別のコンテキスト窓を持てます。
プロジェクト単位なら .claude/agents/、個人なら ~/.claude/agents/ に保存し、YAMLフロントマターで tools/model/permissionMode/skills 等を定義できます。

結論:開発も記事生成も「調査」「校正」「レビュー」を分離すると安定する。


5) Hooks:LLM任せをやめ、決定論で“必ず実行”する

Hooks は、Claude Codeのライフサイクル各点で動く ユーザー定義のシェルコマンドです。
「LLMが選ぶかどうか」に依存せず、必ず起きるようにできるのが価値、と公式が明言しています。

設定は settings.json に置き、場所は ~/.claude/settings.json(ユーザー)や .claude/settings.json(プロジェクト)など。
プロジェクト内スクリプト参照には CLAUDE_PROJECT_DIR を使えることも公式に記載されています。

また重要な仕様として:

  • exit code 2 はブロッキング扱いで、PreToolUse ならツール呼び出し自体を止められます。

  • PostToolUse の exit code 2 は「ツールは既に実行済み」で、以後のフィードバックとして機能します。

  • JSON出力(exit code 0時)で、PostToolUse に対して "decision": "block"+reason を返し、Claudeへ自動フィードバックできます。

そして、Hooksは自動実行されるため セキュリティ上の注意が必要(悪意あるhookがデータ流出し得る)とも明記されています。

結論:Hooksは“品質ゲート”と“安全柵”。入れると運用が変わる。


「開発×記事生成」を同じハーネスで回す設計

ここまでを踏まえると、両者を同じ骨格に乗せられます。

  • CLAUDE.md:全体方針(最小)

  • Skills:再現性の核(開発用 / 記事用)

  • Commands:起動ボタン(実装 / 下書き生成 / 公開パック)

  • Subagents:関心分離(コードレビュー / 校閲)

  • Hooks:決定論の品質ゲート(危険操作ブロック / 自動整形)


コピペ運用できる「最小テンプレ」(雛形)

0) ディレクトリ構成

公式が示す配置(settings / skills / agents / commands)に合わせます。

.
├─ CLAUDE.md
├─ .claude/
│  ├─ settings.json
│  ├─ hooks/
│  │  ├─ pretool-bash-guard.sh
│  │  └─ postwrite-md-lint.sh
│  ├─ skills/
│  │  ├─ dev-shipper/
│  │  │  └─ SKILL.md
│  │  └─ note-article-factory/
│  │     └─ SKILL.md
│  ├─ commands/
│  │  ├─ implement.md
│  │  ├─ outline-article.md
│  │  ├─ draft-article.md
│  │  └─ publish-pack.md
│  └─ agents/
│     ├─ code-reviewer.md
│     └─ copy-editor.md
└─ docs/
   └─ articles/

1) CLAUDE.md

「共通の最小方針だけ」に絞るのがコツです(膨張は失敗しやすい)。

# Project Harness (Dev + Writing)

## What to optimize for
- Reproducibility over cleverness
- Small diffs, fast feedback loops
- Explicit "Fact / Inference / Opinion" separation in articles

## Where outputs go
- Dev: follow repo conventions
- Writing: write Markdown to `docs/articles/<slug>.md`

## How to run workflows (preferred)
### Development
- Use /plan-issue -> /implement -> /commit
- Run tests/lint before commit (hooks will guard common pitfalls)

### Writing (note/article)
- Use /outline-article -> /draft-article -> /publish-pack
- Keep claims disciplined: Fact must be attributable; otherwise mark as inference/opinion.

## Safety
- Do not run destructive shell commands (hooks will block obvious ones).
- If a task is ambiguous, ask for missing constraints before generating large diffs.

2) Skills(再現性の中核)

SKILL.mdはYAMLフロントマター必須で、補助ファイルは必要時だけ読まれます。allowed-tools で権限制限も可能です。

開発用:.claude/skills/dev-shipper/SKILL.md

---
name: dev-shipper
description: Implement features and fixes with high reproducibility. Use for coding tasks, refactors, bugfixes, adding tests, and preparing PR-ready changes.
allowed-tools: Read, Grep, Glob, Edit, Write, Bash
---

# Dev Shipper

## Goal
Ship correct changes with tests and minimal regressions.

## Operating rules
1. Start with context: read relevant code + tests + docs.
2. Create a short task list (3–8 items).
3. Make small diffs; run checks early and often.
4. Always add or update tests when behavior changes.
5. Summarize what/why and any risks.

## Definition of Done (DoD)
- Tests updated/added and pass
- Lint/format passes (if applicable)
- Behavior change is documented (README/CHANGELOG if needed)
- Clear PR summary: what/why/how to verify

## Failure handling
- If tests fail: stop and fix before adding features.
- If requirements ambiguous: ask 1–3 targeted questions before proceeding.

## Version History
- v1.0.0: initial

記事用:.claude/skills/note-article-factory/SKILL.md

---
name: note-article-factory
description: Write Japanese articles for note/blog in Markdown. Use for outlining, drafting, revising, fact discipline (Fact/Inference/Opinion), and generating publish assets (title/lead/summary/hashtags/X copy).
allowed-tools: Read, Grep, Glob, Edit, Write
---

# Note Article Factory

## Output target
- Markdown article saved to `docs/articles/<slug>.md`

## Writing protocol
1. Clarify the brief (purpose, audience, desired length, tone).
2. Produce an outline (H1 + multiple H2/H3).
3. Draft with clear sectioning:
   - Lead (problem framing + promise)
   - Main (3–7 sections)
   - Summary (what to do next)
4. Fact discipline:
   - Fact: attributable or based on provided sources
   - Inference: mark as inference
   - Opinion: mark as opinion
5. Final pass:
   - Remove fluff, avoid noun-stacking
   - Ensure “next action” is explicit

## Publish pack (deliverables)
- Title candidates (5–10)
- Lead (120–250 Japanese chars)
- Summary (3–5 bullets)
- Hashtags (single line)
- X promo copy (2 variants)

## Version History
- v1.0.0: initial

3) Slash Commands(ボタン化)

コマンドは .claude/commands/、引数は $ARGUMENTS / $1 等。

/outline-article:構成を出す

---
description: Create a structured outline for a Japanese note/blog article
argument-hint: [topic] [audience-optional]
allowed-tools: Read, Grep, Glob, Write
---

Use the note-article-factory Skill.

Topic: $ARGUMENTS

Deliver:
- Working title (3 candidates)
- Outline with H1 + H2/H3
- Key points per section (1–3 bullets)
- Assumptions (if any)

/draft-article:下書きを保存する(slug付き)

---
description: Draft a full Markdown article into docs/articles/<slug>.md
argument-hint: [slug] [topic]
allowed-tools: Read, Grep, Glob, Write, Edit
---

Use the note-article-factory Skill.

Write to: docs/articles/$1.md
Topic: $2

Constraints:
- Japanese, polite tone
- Fact/Inference/Opinion separation where relevant
- Include a clear “next action” at the end

Return:
- Path written
- Short changelog of what you generated

/publish-pack:公開用素材をまとめる

---
description: Generate publish assets (titles/lead/summary/hashtags/X copy) for an existing article
argument-hint: [slug]
allowed-tools: Read, Write
---

Read: @docs/articles/$ARGUMENTS.md

Generate:
1) Titles (5–10)
2) Lead (120–250 chars)
3) Summary bullets (3–5)
4) Hashtags (single line)
5) X promo copy (2 variants)

4) Subagents(関心分離)

Subagentsは .claude/agents/ にYAML frontmatterで定義できます。

コードレビュー専用:.claude/agents/code-reviewer.md

---
name: code-reviewer
description: Review diffs for quality, security, and tests.
tools: Read, Grep, Glob
model: inherit
permissionMode: default
---

You are a strict code reviewer.
Return: issues, risks, and concrete fix suggestions.

校閲専用:.claude/agents/copy-editor.md

---
name: copy-editor
description: Use when you need strict Japanese editing: clarity, structure, removing fluff, enforcing Fact/Inference/Opinion labeling.
tools: Read, Edit
model: inherit
permissionMode: default
---

Edit for:
- Clarity and flow
- Reducing noun-stacking
- Consistent tone
- Fact discipline (mark inference/opinion)
Return an edited version plus a change summary.

5) Hooks(安全柵と品質ゲート)

Hooksは「必ず実行される」決定論の仕組みで、/hooks で設定UIを開けます。設定ファイルは settings.json(ユーザー/プロジェクト/ローカル)です。

.claude/settings.json(例:PreToolUseで危険Bashをブロック)

Hooksの基本構造(matcher + hooks配列)と CLAUDE_PROJECT_DIR は公式仕様です。

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/pretool-bash-guard.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/posttool-quality-gate.sh"
          }
        ]
      }
    ]
  }
}

pretool-bash-guard.sh(exit code 2 でブロック)

exit code 2 はブロッキング扱いで、PreToolUseならツール呼び出し自体を止められます。

#!/usr/bin/env bash
set -euo pipefail

# Hook input is JSON via stdin (use jq).
input="$(cat)"

tool_name="$(echo "$input" | jq -r '.tool_name // empty')"
if [[ "$tool_name" != "Bash" ]]; then
  exit 0
fi

cmd="$(echo "$input" | jq -r '.tool_input.command // empty')"

# Very conservative deny-list (extend per your environment).
if echo "$cmd" | grep -Eqi \
  'rm\s+-rf\s+/\b|mkfs|dd\s+if=|:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:|curl[^|]*\|\s*bash|wget[^|]*\|\s*bash'; then
  echo "Blocked dangerous command: $cmd" >&2
  exit 2  # Blocks PreToolUse tool call :contentReference[oaicite:6]{index=6}
fi

exit 0

postwrite-md-lint.sh(記事の最低限構造をチェックしてフィードバック)

PostToolUseは「ツール実行後」なので、“差し戻し”ではなく自動フィードバックとして使うのが安全です。

(ここは実装方針だけに留めます。記事内で長くなるため、必要なら完成版を別途出します。)


“嘘”を混ぜないための運用上の注意(ここは仕組みで守る)

1) 記事生成は「事実・推測・意見」をラベル化する

これはClaude Codeの機能というより、あなたの編集ポリシーです。
Skill(note-article-factory)にルールとして埋め込み、校閲subagentで強制するとブレにくくなります。

2) Hooksは強力だが危険。必ずレビューする

Hooksは自動実行で、環境の資格情報を使うため、悪用すればデータ流出し得ると公式が注意しています。運用上は「チーム共有するhooksは最小」「ローカル個人は .claude/settings.local.json」のようにスコープ分離が無難です。

3) 機密ファイルは permissions.deny で見えなくする

Claude Codeは permissions.deny で機密ファイルの読み取りを防げます。
これは「うっかり混ざる」事故を減らす実務的な手段です。


まとめ:Skillsは“成果物”ではなく、運用で育つ“資産”

  • CLAUDE.md:最小の方針(増やしすぎない)

  • Skills:再現性の核(段階的開示でコンテキスト節約)

  • Commands:起動ボタン(習慣化)

  • Subagents:関心分離(文脈汚染を防ぐ)

  • Hooks:決定論の安全柵と品質ゲート(必ず実行)

そして、開発と記事生成は同じ構造で回せます。
「作って終わり」ではなく、失敗ログ→Skill/Hook/Commandに吸収→再発防止で資産化が進みます。


次にやること

  1. 上の雛形どおりに .claude/ と docs/articles/ を作る

  2. まずは記事側だけ(outline→draft→publish-pack)で回し、つまずきをSkillへ追記する

  3. 次に開発側へ広げ、危険操作だけPreToolUse hookでブロックする

いいなと思ったら応援しよう!