> ## Documentation Index
> Fetch the complete documentation index at: https://exosphere-auto-translate-docs-20260623-1106.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用例

> Claude CodeとAgents SDKにフックを設定する方法

一般的なシナリオですぐに使えるサンプル集です。各例では、インストール方法と期待される動作を説明しています。

***

## Claude Code にフックを設定する

Failproof AI は Claude Code の[フックシステム](https://docs.anthropic.com/en/docs/claude-code/hooks)を通じて統合されます。`failproofai policies --install` を実行すると、ツール呼び出しのたびに発火するフックコマンドが Claude Code の `settings.json` に登録されます。

<Steps>
  <Step title="failproofai をインストールする">
    ```bash theme={null}
    npm install -g failproofai
    ```
  </Step>

  <Step title="組み込みポリシーをすべて有効にする">
    ```bash theme={null}
    failproofai policies --install
    ```
  </Step>

  <Step title="フックが登録されているか確認する">
    ```bash theme={null}
    cat ~/.claude/settings.json | grep failproofai
    ```

    `PreToolUse`、`PostToolUse`、`Notification`、`Stop` イベントのフックエントリが表示されるはずです。
  </Step>

  <Step title="Claude Code を起動する">
    ```bash theme={null}
    claude
    ```

    これでポリシーがすべてのツール呼び出しに対して自動的に実行されます。Claude に `sudo rm -rf /` を実行するよう指示してみてください。ブロックされます。
  </Step>
</Steps>

***

## Agents SDK にフックを設定する

[Agents SDK](https://docs.anthropic.com/en/docs/agents-sdk) を使って開発している場合、同じフックシステムをプログラムから利用できます。

<Steps>
  <Step title="プロジェクトに failproofai をインストールする">
    ```bash theme={null}
    npm install failproofai
    ```
  </Step>

  <Step title="エージェントにフックを設定する">
    エージェントプロセスの作成時にフックコマンドを渡します。フックは Claude Code と同様に stdin/stdout の JSON 経由で発火します：

    ```bash theme={null}
    failproofai --hook PreToolUse   # ツール実行前に呼び出される
    failproofai --hook PostToolUse  # ツール実行後に呼び出される
    ```
  </Step>

  <Step title="エージェント用のカスタムポリシーを書く">
    ```javascript theme={null}
    import { customPolicies, allow, deny } from "failproofai";

    customPolicies.add({
      name: "limit-to-project-dir",
      description: "Keep the agent inside the project directory",
      match: { events: ["PreToolUse"] },
      fn: async (ctx) => {
        const path = String(ctx.toolInput?.file_path ?? "");
        if (path.startsWith("/") && !path.startsWith(ctx.session?.cwd ?? "")) {
          return deny("Agent is restricted to the project directory");
        }
        return allow();
      },
    });
    ```
  </Step>

  <Step title="カスタムポリシーをインストールする">
    ```bash theme={null}
    failproofai policies --install --custom ./my-agent-policies.js
    ```
  </Step>
</Steps>

***

## 破壊的なコマンドをブロックする

最も一般的な設定です。エージェントが取り消し不能な操作を行わないようにします。

```bash theme={null}
failproofai policies --install block-sudo block-rm-rf block-force-push block-curl-pipe-sh
```

各ポリシーの効果：

* `block-sudo` — すべての `sudo` コマンドをブロック
* `block-rm-rf` — ファイルの再帰的削除をブロック
* `block-force-push` — `git push --force` をブロック
* `block-curl-pipe-sh` — リモートスクリプトをシェルにパイプする操作をブロック

***

## シークレットの漏洩を防ぐ

ツールの出力から認証情報が見えたり漏洩したりするのを防ぎます。

```bash theme={null}
failproofai policies --install sanitize-api-keys sanitize-jwt sanitize-connection-strings sanitize-bearer-tokens
```

これらは `PostToolUse` で発火します。ツール実行後、エージェントが出力を受け取る前にスクラブ処理が行われます。

***

## エージェントが待機中のときに Slack 通知を送る

通知フックを使って、アイドル通知を Slack に転送します。

```javascript theme={null}
import { customPolicies, allow, instruct } from "failproofai";

customPolicies.add({
  name: "slack-on-idle",
  description: "Alert Slack when the agent is waiting for input",
  match: { events: ["Notification"] },
  fn: async (ctx) => {
    const webhookUrl = process.env.SLACK_WEBHOOK_URL;
    if (!webhookUrl) return allow();

    const message = String(ctx.payload?.message ?? "Agent is waiting");
    const project = ctx.session?.cwd ?? "unknown";

    try {
      await fetch(webhookUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          text: `*${message}*\nProject: \`${project}\``,
        }),
        signal: AbortSignal.timeout(5000),
      });
    } catch {
      // Slack に接続できなくてもエージェントをブロックしない
    }

    return allow();
  },
});
```

インストール：

```bash theme={null}
SLACK_WEBHOOK_URL=https://hooks.slack.com/... failproofai policies --install --custom ./slack-alerts.js
```

***

## エージェントをブランチに固定する

エージェントが他のブランチに切り替えたり、保護されたブランチにプッシュしたりするのを防ぎます。

```javascript theme={null}
import { customPolicies, allow, deny } from "failproofai";

customPolicies.add({
  name: "stay-on-branch",
  description: "Prevent the agent from checking out other branches",
  match: { events: ["PreToolUse"] },
  fn: async (ctx) => {
    if (ctx.toolName !== "Bash") return allow();
    const cmd = String(ctx.toolInput?.command ?? "");
    if (/git\s+checkout\s+(?!-b)/.test(cmd)) {
      return deny("Stay on the current branch. Create a new branch with -b if needed.");
    }
    return allow();
  },
});
```

***

## コミット前にテストを要求する

コミット前にテストを実行するようエージェントに促します。

```javascript theme={null}
import { customPolicies, allow, instruct } from "failproofai";

customPolicies.add({
  name: "test-before-commit",
  description: "Remind the agent to run tests before committing",
  match: { events: ["PreToolUse"] },
  fn: async (ctx) => {
    if (ctx.toolName !== "Bash") return allow();
    const cmd = String(ctx.toolInput?.command ?? "");
    if (/git\s+commit/.test(cmd)) {
      return instruct("Run tests before committing. Use `npm test` or `bun test` first.");
    }
    return allow();
  },
});
```

***

## 本番リポジトリをロックする

プロジェクトレベルの設定をコミットすることで、チームの全メンバーが同じポリシーを適用できます。

リポジトリに `.failproofai/policies-config.json` を作成します：

```json theme={null}
{
  "enabledPolicies": [
    "block-sudo",
    "block-rm-rf",
    "block-force-push",
    "block-push-master",
    "block-env-files",
    "sanitize-api-keys",
    "sanitize-jwt"
  ],
  "policyParams": {
    "block-push-master": {
      "protectedBranches": ["main", "release", "production"]
    }
  }
}
```

コミットします：

```bash theme={null}
git add .failproofai/policies-config.json
git commit -m "Add failproofai team policies"
```

failproofai をインストール済みのチームメンバー全員が、これらのルールを自動的に適用できます。

***

## コンベンションポリシーで組織全体の品質基準を構築する

最も効果的な設定です。プロジェクトに合わせたポリシーを `.failproofai/policies/` にコミットすることで、チームメンバー全員が自動的に適用できます。インストールコマンドや設定変更は不要です。

<Steps>
  <Step title="ディレクトリを作成してポリシーを追加する">
    ```bash theme={null}
    mkdir -p .failproofai/policies
    ```

    ```js theme={null}
    // .failproofai/policies/team-policies.mjs
    import { customPolicies, allow, deny, instruct } from "failproofai";

    // チームが推奨するパッケージマネージャーを強制する
    // （代わりに組み込みの prefer-package-manager ポリシーを有効にする方法もあります）
    customPolicies.add({
      name: "enforce-bun",
      match: { events: ["PreToolUse"] },
      fn: async (ctx) => {
        if (ctx.toolName !== "Bash") return allow();
        const cmd = String(ctx.toolInput?.command ?? "");
        if (/\bnpm\b/.test(cmd)) return deny("Use bun instead of npm.");
        return allow();
      },
    });

    // コミット前にテストを実行するようエージェントに促す
    customPolicies.add({
      name: "test-before-commit",
      match: { events: ["PreToolUse"] },
      fn: async (ctx) => {
        if (ctx.toolName !== "Bash") return allow();
        if (/git\s+commit/.test(ctx.toolInput?.command ?? "")) {
          return instruct("Run tests before committing.");
        }
        return allow();
      },
    });
    ```
  </Step>

  <Step title="git にコミットする">
    ```bash theme={null}
    git add .failproofai/policies/
    git commit -m "Add team quality policies"
    ```
  </Step>

  <Step title="継続的に改善する">
    チームで新たな問題が発生したら、ポリシーを追加してプッシュしてください。次の `git pull` 時に全員がアップデートを受け取れます。これらのポリシーはチームとともに成長する生きた品質基準となります。
  </Step>
</Steps>

***

## その他の使用例

リポジトリの [`examples/`](https://github.com/failproofai/failproofai/tree/main/examples) ディレクトリには以下のファイルが含まれています：

| ファイル                         | 内容                                                |
| ---------------------------- | ------------------------------------------------- |
| `policies-basic.js`          | 基本ポリシー — 本番環境への書き込み、force push、パイプスクリプトのブロック      |
| `policies-notification.js`   | アイドル通知やセッション終了時の Slack アラート                       |
| `policies-advanced/index.js` | 推移的インポート、非同期フック、PostToolUse による出力スクラブ、Stop イベント処理 |
