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

# Examples

title: Các ví dụ
description: "Cách thiết lập hooks cho Claude Code và Agents SDK"
icon: book-open
---------------

Các ví dụ sẵn sàng sử dụng cho những kịch bản phổ biến. Mỗi ví dụ cho thấy cách cài đặt và những gì bạn nên 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 và chúng sẽ được kích hoạt trên mỗi lệnh 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 sẽ chạy tự động trên mỗi lệnh 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 một hệ thống hook theo 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 quá trình agent của bạn. Các hooks được kích hoạt giống như trong Claude Code - thông qua JSON stdin/stdout:

    ```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 phá hoại

Thiết lập phổ biến nhất - ngăn agent gây ra các thiệt hại không thể hoàn tác.

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

Điều này thực hiện những gì sau:

* `block-sudo` - chặn tất cả các lệnh `sudo`
* `block-rm-rf` - chặn xóa tệp đệ 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 agent khỏi việc nhìn thấy hoặc rò rỉ thông tin đăng nhập 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 chính sách này được kích hoạt trên `PostToolUse` - sau khi một công cụ chạy, chúng sẽ làm sạch đầu ra trước khi agent nhìn thấy nó.

***

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

Sử dụng notification hook để chuyển tiếp các cảnh báo chờ đợi đế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ữ agent trên một nhánh

Ngăn agent chuyển đổi nhánh hoặc push đế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 tra trước khi commit

Nhắc nhở agent chạy các bài kiểm tra 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 một kho lưu trữ production

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

Tạo `.failproofai/policies-config.json` trong kho lưu trữ 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 trong nhóm có cài đặt failproofai sẽ tự động chọn những quy tắc này.

***

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

Thiết lập có tác động lớn nhất: commit `.failproofai/policies/` đến kho lưu trữ 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 trong 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 đến 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 phải những chế độ lỗi mới, hãy thêm chính sách và push. Mọi người sẽ nhận được bản cập nhật trên `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>

***

## Thêm nhiều ví dụ

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

| Tệp                          | Những gì nó cho thấy                                                             |
| ---------------------------- | -------------------------------------------------------------------------------- |
| `policies-basic.js`          | Chính sách khởi động - chặn ghi production, force-push, piped scripts            |
| `policies-notification.js`   | Cảnh báo Slack cho các thông báo chờ đợi và kết thúc phiên                       |
| `policies-advanced/index.js` | Nhập quá độc lập, async hooks, PostToolUse output scrubbing, Stop event handling |
