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

# Ví dụ

> Cách thiết lập hooks cho Claude Code và Agents SDK

Các ví dụ sẵn sàng sử dụng cho các tình huống phổ biến. Mỗi ví dụ cho thấy cách cài đặt và những gì bạn có thể mong đợi.

***

## Thiết lập hooks cho Claude Code

Failproof AI tích hợp với Claude Code thông qua [hệ thống hooks](https://docs.anthropic.com/en/docs/claude-code/hooks) của nó. Khi bạn chạy `failproofai policies --install`, nó sẽ đăng ký các lệnh hook trong `settings.json` của Claude Code sẽ chạy trên mỗi lần gọi công cụ.

<Steps>
  <Step title="Cài đặt failproofai">
    ```bash theme={null}
    npm install -g failproofai
    ```
  </Step>

  <Step title="Bật tất cả các chính sách tích hợp">
    ```bash theme={null}
    failproofai policies --install
    ```
  </Step>

  <Step title="Xác minh hooks đã được đăng ký">
    ```bash theme={null}
    cat ~/.claude/settings.json | grep failproofai
    ```

    Bạn sẽ thấy các mục hook cho các sự kiện `PreToolUse`, `PostToolUse`, `Notification`, và `Stop`.
  </Step>

  <Step title="Chạy Claude Code">
    ```bash theme={null}
    claude
    ```

    Các chính sách giờ đã chạy tự động trên mỗi lần gọi công cụ. Hãy thử yêu cầu Claude chạy `sudo rm -rf /` - nó sẽ bị chặn.
  </Step>
</Steps>

***

## Thiết lập hooks cho Agents SDK

Nếu bạn đang xây dựng với [Agents SDK](https://docs.anthropic.com/en/docs/agents-sdk), bạn có thể sử dụng cùng hệ thống hook một cách lập trình.

<Steps>
  <Step title="Cài đặt failproofai trong dự án của bạn">
    ```bash theme={null}
    npm install failproofai
    ```
  </Step>

  <Step title="Cấu hình hooks trong agent của bạn">
    Truyền các lệnh hook khi tạo quy trình agent của bạn. Các hooks sẽ chạy giống như trong Claude Code - thông qua stdin/stdout JSON:

    ```bash theme={null}
    failproofai --hook PreToolUse   # được gọi trước mỗi công cụ
    failproofai --hook PostToolUse  # được gọi sau mỗi công cụ
    ```
  </Step>

  <Step title="Viết một chính sách tùy chỉnh cho agent của bạn">
    ```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="Cài đặt chính sách tùy chỉnh">
    ```bash theme={null}
    failproofai policies --install --custom ./my-agent-policies.js
    ```
  </Step>
</Steps>

***

## Chặn các lệnh tàn phá

Cài đặt phổ biến nhất - ngăn agents thực hiện các thiệt hại không thể khôi phục được.

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

Điều này làm gì:

* `block-sudo` - chặn tất cả các lệnh `sudo`
* `block-rm-rf` - chặn xóa file đệ quy
* `block-force-push` - chặn `git push --force`
* `block-curl-pipe-sh` - chặn piping các script từ xa đến shell

***

## Ngăn chặn rò rỉ bí mật

Dừng agents nhìn thấy hoặc rò rỉ thông tin xác thực trong đầu ra công cụ.

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

Những cái này chạy trên `PostToolUse` - sau khi một công cụ chạy, chúng sẽ xóa đầu ra trước khi agent nhìn thấy nó.

***

## Nhận cảnh báo Slack khi agents cần chú ý

Sử dụng hook thông báo để chuyển tiếp cảnh báo idle đến 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();
  },
});
```

Cài đặt nó:

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

***

## Giữ agents trên một nhánh

Ngăn agents chuyển đổi nhánh hoặc đẩy đến các nhánh được bảo vệ.

```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();
  },
});
```

***

## Yêu cầu kiểm thử trước khi commit

Nhắc nhở agents chạy kiểm thử trước khi commit.

```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();
  },
});
```

***

## Khóa chặt một repo sản xuất

Commit một cấu hình mức dự án để mỗi nhà phát triển trong nhóm của bạn nhận được các chính sách giống nhau.

Tạo `.failproofai/policies-config.json` trong repo của bạn:

```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"]
    }
  }
}
```

Sau đó commit nó:

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

Mỗi thành viên nhóm có failproofai được cài đặt sẽ tự động nhận những quy tắc này.

***

## Xây dựng tiêu chuẩn chất lượng toàn tổ chức với chính sách quy ước

Cài đặt có tác động lớn nhất: commit `.failproofai/policies/` vào repo của bạn với các chính sách được điều chỉnh cho dự án của bạn. Mỗi thành viên nhóm sẽ nhận được chúng tự động — không có lệnh cài đặt, không có thay đổi cấu hình.

<Steps>
  <Step title="Tạo thư mục và thêm chính sách">
    ```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="Commit vào git">
    ```bash theme={null}
    git add .failproofai/policies/
    git commit -m "Add team quality policies"
    ```
  </Step>

  <Step title="Tiếp tục cải thiện">
    Khi nhóm của bạn gặp các chế độ lỗi mới, hãy thêm chính sách và đẩy lên. Mọi người sẽ nhận được cập nhật vào `git pull` tiếp theo của họ. Những chính sách này trở thành một tiêu chuẩn chất lượng sống động phát triển cùng với nhóm của bạn.
  </Step>
</Steps>

***

## Các ví dụ khác

Thư mục [`examples/`](https://github.com/failproofai/failproofai/tree/main/examples) trong repo chứa:

| Tệp                          | Điều nó thể hiện                                                                  |
| ---------------------------- | --------------------------------------------------------------------------------- |
| `policies-basic.js`          | Các chính sách khởi đầu - chặn ghi sản xuất, force-push, piped scripts            |
| `policies-notification.js`   | Cảnh báo Slack cho thông báo idle và kết thúc phiên                               |
| `policies-advanced/index.js` | Nhập transitional, async hooks, PostToolUse output scrubbing, Stop event handling |
