> ## 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   # 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 이벤트 처리 |
