> ## Documentation Index
> Fetch the complete documentation index at: https://docs.befailproof.ai/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   # called before each tool
    failproofai --hook PostToolUse  # called after each tool
    ```
  </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 {
      // never block the agent if Slack is unreachable
    }

    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";

    // Enforce your team's preferred package manager
    // (or enable the built-in prefer-package-manager policy instead)
    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();
      },
    });

    // Remind the agent to run tests before committing
    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`          | 기본 정책 - 프로덕션 쓰기, 강제 푸시, 파이프된 스크립트 차단             |
| `policies-notification.js`   | 유휴 알림 및 세션 종료에 대한 Slack 알림                       |
| `policies-advanced/index.js` | 전이적 임포트, 비동기 훅, PostToolUse 출력 스크러빙, Stop 이벤트 처리 |
