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

# מדיניות מותאמות אישית

> כתוב את הכללים שלך בJavaScript - אכוף קונוונציות, עצור סטייה, גלה כשלים, השתלב עם מערכות חיצוניות

מדיניות מותאמות אישית מאפשרת לך לכתוב כללים לכל התנהגות סוכן: אכוף קונוונציות של פרויקט, עצור סטייה, חסום פעולות הרסניות, גלה סוכנים תקועים, או השתלב עם Slack, זרימות אישור, ועוד. הם משתמשים באותה מערכת אירועי hook וה-`allow`, `deny`, `instruct` כמו מדיניות מובנית.

***

## דוגמה מהירה

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

customPolicies.add({
  name: "no-production-writes",
  description: "Block writes to paths containing 'production'",
  match: { events: ["PreToolUse"] },
  fn: async (ctx) => {
    if (ctx.toolName !== "Write" && ctx.toolName !== "Edit") return allow();
    const path = ctx.toolInput?.file_path ?? "";
    if (path.includes("production")) {
      return deny("Writes to production paths are blocked");
    }
    return allow();
  },
});
```

התקנה:

```bash theme={null}
failproofai policies --install --custom ./my-policies.js
```

***

## שתי דרכים לטעון מדיניות מותאמת אישית

### אפשרות 1: מבוססת קונוונציה (מומלץ)

זרוק קבצים `*policies.{js,mjs,ts}` לתוך `.failproofai/policies/` והם נטענים באופן אוטומטי — אין צורך בדגלים או שינויי תצורה. זה עובד כמו git hooks: זרוק קובץ, זה פשוט עובד.

```
# Project level — committed to git, shared with the team
.failproofai/policies/security-policies.mjs
.failproofai/policies/workflow-policies.mjs

# User level — personal, applies to all projects
~/.failproofai/policies/my-policies.mjs
```

**איך זה עובד:**

* שני הספריות של פרויקט ומשתמש נסרקים (union — לא first-scope-wins)
* קבצים נטענים בסדר אלפבתי בתוך כל ספריה. הוסף קידומת עם `01-`, `02-` כדי לשלוט בסדר
* רק קבצים התואמים `*policies.{js,mjs,ts}` נטענים; קבצים אחרים מתעלמים
* כל קובץ נטען באופן עצמאי (fail-open לכל קובץ)
* עובד לצד `--custom` מפורש ומדיניות מובנית

<Tip>
  מדיניות קונוונציה היא הדרך הקלה ביותר לבנות תקן איכות לארגון שלך. Commit `.failproofai/policies/` ל-git וכל חברי הצוות יקבלו את אותם הכללים באופן אוטומטי — אין צורך בהגדרה לכל מפתח. כשהצוות שלך מגלה מצבי כשלים חדשים, הוסף מדיניות ודחוף. עם הזמן אלה הופכים לתקן איכות חי שמשתפר עם כל תרומה.
</Tip>

### אפשרות 2: נתיב קובץ מפורש

```bash theme={null}
# Install with a custom policies file
failproofai policies --install --custom ./my-policies.js

# Replace the policies file path
failproofai policies --install --custom ./new-policies.js

# Remove the custom policies path from config
failproofai policies --uninstall --custom
```

הנתיב המוחלט המוחזר מאוחסן ב-`policies-config.json` כ-`customPoliciesPath`. הקובץ נטען בטרי בכל אירוע hook - אין caching בין אירועים.

### שימוש בשניהם יחד

מדיניות קונוונציה וקובץ `--custom` מפורש יכולים להתקיים. סדר טעינה:

1. קובץ `customPoliciesPath` מפורש (אם מוגדר)
2. קבצי קונוונציה של פרויקט (`{cwd}/.failproofai/policies/`, בסדר אלפבתי)
3. קבצי קונוונציה של משתמש (`~/.failproofai/policies/`, בסדר אלפבתי)

***

## API

### Import

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

### `customPolicies.add(hook)`

רושם מדיניות. קרא זאת כמו שרוצה פעמים רבות עבור מדיניות מרובה באותו קובץ.

```ts theme={null}
customPolicies.add({
  name: string;                         // required - unique identifier
  description?: string;                 // shown in `failproofai policies` output
  match?: { events?: HookEventType[] }; // filter by event type; omit to match all
  fn: (ctx: PolicyContext) => PolicyResult | Promise<PolicyResult>;
});
```

### עוזרי החלטות

| פונקציה             | אפקט                | השתמש כאשר                              |
| ------------------- | ------------------- | --------------------------------------- |
| `allow()`           | אפשר את הפעולה בשקט | הפעולה בטוחה, אין צורך בהודעה           |
| `deny(message)`     | חסום את הפעולה      | הסוכן לא צריך לבצע פעולה זו             |
| `instruct(message)` | הוסף הקשר ללא חסימה | תן לסוכן הקשר נוסף כדי להישאר על המסלול |

`deny(message)` - ההודעה מופיעה ל-Claude עם קידומת `"Blocked by failproofai:"`. ה-`deny` יחיד מקצר הערכה נוספת.

`instruct(message)` - ההודעה מצורפת להקשר של Claude לקריאת הכלי הנוכחי. כל הודעות `instruct` מצטברות ומועברות יחד.

<Tip>
  אתה יכול לצרף הנחיה נוספת לכל הודעת `deny` או `instruct` על ידי הוספת שדה `hint` ב-`policyParams` — אין צורך בשינוי קוד. זה עובד עבור מדיניות מותאמת אישית (`custom/`), קונוונציה של פרויקט (`.failproofai-project/`), וקונוונציה של משתמש (`.failproofai-user/`) גם כן. ראה [Configuration → hint](/he/configuration#hint-cross-cutting) לפרטים.
</Tip>

### הודעות allow אינפורמטיביות

`allow(message)` מאפשר את הפעולה **וגם** שולח הודעה אינפורמטיבית חזרה ל-Claude. ההודעה מועברת כ-`additionalContext` בתגובת stdout של מטפל ה-hook — אותו מנגנון המשמש ל-`instruct`, אך שונה מבחינה סמנטית: זה עדכון סטטוס, לא אזהרה.

| פונקציה          | אפקט                    | השתמש כאשר                              |
| ---------------- | ----------------------- | --------------------------------------- |
| `allow(message)` | אפשר ושלח הקשר ל-Claude | אשר בדיקה עברה, או הסבר למה בדיקה דולגת |

מקרי שימוש:

* **אישורי סטטוס:** `allow("All CI checks passed.")` — אומר ל-Claude שהכל ירוק
* **הסברי fail-open:** `allow("GitHub CLI not installed, skipping CI check.")` — אומר ל-Claude למה בדיקה דלגה כדי שיהיה לו הקשר מלא
* **הודעות מרובות מצטברות:** אם כמה מדיניות כל אחת מחזירה `allow(message)`, כל ההודעות מחוברות עם עלינוליים ומועברות יחד

```js theme={null}
customPolicies.add({
  name: "confirm-branch-status",
  match: { events: ["Stop"] },
  fn: async (ctx) => {
    const cwd = ctx.session?.cwd;
    if (!cwd) return allow("No working directory, skipping branch check.");

    // ... check branch status ...
    if (allPushed) {
      return allow("Branch is up to date with remote.");
    }
    return deny("Unpushed changes detected.");
  },
});
```

### שדות `PolicyContext`

| שדה         | סוג                                    | תיאור                                                       |
| ----------- | -------------------------------------- | ----------------------------------------------------------- |
| `eventType` | `string`                               | `"PreToolUse"`, `"PostToolUse"`, `"Notification"`, `"Stop"` |
| `toolName`  | `string \| undefined`                  | הכלי שנקרא (לדוגמה `"Bash"`, `"Write"`, `"Read"`)           |
| `toolInput` | `Record<string, unknown> \| undefined` | פרמטרי הקלט של הכלי                                         |
| `payload`   | `Record<string, unknown>`              | דיפלומת אירוע גולמית מלאה מ-Claude Code                     |
| `session`   | `SessionMetadata \| undefined`         | הקשר סשן (ראה להלן)                                         |

### שדות `SessionMetadata`

| שדה              | סוג      | תיאור                           |
| ---------------- | -------- | ------------------------------- |
| `sessionId`      | `string` | מזהה סשן Claude Code            |
| `cwd`            | `string` | ספרייה עובדת של סשן Claude Code |
| `transcriptPath` | `string` | נתיב לקובץ תמליל JSONL של הסשן  |

### סוגי אירועים

| אירוע          | כאשר הוא משתלח             | תוכן `toolInput`                                                                                                                              |
| -------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `PreToolUse`   | לפני Claude מריץ כלי       | הקלט של הכלי (לדוגמה `{ command: "..." }` עבור Bash)                                                                                          |
| `PostToolUse`  | לאחר השלמת כלי             | הקלט של הכלי + `tool_result` (הפלט)                                                                                                           |
| `Notification` | כאשר Claude שולח הודעה     | `{ message: "...", notification_type: "idle" \| "permission_prompt" \| ... }` - hooks חייבים תמיד להחזיר `allow()`, הם לא יכולים לחסום הודעות |
| `Stop`         | כאשר הסשן של Claude מסתיים | ריק                                                                                                                                           |

***

## סדר הערכה

מדיניות מוערכת בסדר זה:

1. מדיניות מובנית (בסדר הגדרה)
2. מדיניות מותאמת אישית מפורשת מ-`customPoliciesPath` (בסדר `.add()`)
3. מדיניות קונוונציה מ-`.failproofai/policies/` של פרויקט (קבצים אלפבתיים, סדר `.add()` בתוך)
4. מדיניות קונוונציה מ-`~/.failproofai/policies/` של משתמש (קבצים אלפבתיים, סדר `.add()` בתוך)

<Note>
  ה-`deny` הראשון מקצר את כל המדיניות הלאה. כל הודעות `instruct` מצטברות ומועברות יחד.
</Note>

***

## ייבוא טרנזיטיבי

קבצי מדיניות מותאמים אישית יכולים לייבא מודולים מקומיים באמצעות נתיבים יחסיים:

```js theme={null}
// my-policies.js
import { isBlockedPath } from "./utils.js";
import { checkApproval } from "./approval-client.js";

customPolicies.add({
  name: "approval-gate",
  fn: async (ctx) => {
    if (ctx.toolName !== "Bash") return allow();
    const approved = await checkApproval(ctx.toolInput?.command, ctx.session?.sessionId);
    return approved ? allow() : deny("Approval required for this command");
  },
});
```

כל היבוא יחסי הנגיע מקובץ ההרשמה מתוחזר. זה מיושם על ידי כתיבה מחדש של ייבוא `from "failproofai"` לנתיב dist בפועל ויצירת קבצי `.mjs` זמניים כדי להבטיח תאימות ESM.

***

## סינון סוג אירוע

השתמש ב-`match.events` כדי להגביל מתי מדיניות משתלחת:

```js theme={null}
customPolicies.add({
  name: "require-summary-on-stop",
  match: { events: ["Stop"] },
  fn: async (ctx) => {
    // Only fires when the session ends
    // ctx.session.transcriptPath contains the full session log
    return allow();
  },
});
```

השמט `match` לחלוטין כדי להיות בעל יכולת בכל סוג אירוע.

***

## טיפול בשגיאות ומצבי כשל

מדיניות מותאמת אישית היא **fail-open**: שגיאות לעולם לא חוסמות מדיניות מובנית או קורסות מטפל ה-hook.

| כשל                           | התנהגות                                                                           |
| ----------------------------- | --------------------------------------------------------------------------------- |
| `customPoliciesPath` לא מוגדר | לא מחוגות מדיניות מותאמת אישית מפורשת; מדיניות קונוונציה ומובנית ממשיכות בדרך כלל |
| קובץ לא נמצא                  | אזהרה מתועדת ל-`~/.failproofai/hook.log`; מובנית ממשיכה                           |
| שגיאת תחביר/ייבוא (מפורשת)    | שגיאה מתועדת ל-`~/.failproofai/hook.log`; מדיניות מותאמת אישית מפורשת דלגת        |
| שגיאת תחביר/ייבוא (קונוונציה) | שגיאה מתועדת; קובץ זה דולג, קבצי קונוונציה אחרים עדיין נטענים                     |
| `fn` זורק בזמן ריצה           | שגיאה מתועדת; ה-hook הזה מטופל כ-`allow`; hook אחר ממשיך                          |
| `fn` לוקח יותר מ-10s          | timeout מתועד; מטופל כ-`allow`                                                    |
| ספרייה קונוונציה חסרה         | לא מחוגות מדיניות קונוונציה; אין שגיאה                                            |

<Tip>
  כדי לתפוס שגיאות מדיניות מותאמת אישית, צפה בקובץ היומן:

  ```bash theme={null}
  tail -f ~/.failproofai/hook.log
  ```
</Tip>

***

## דוגמה מלאה: מדיניות מרובה

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

// Prevent agent from writing to secrets/ directory
customPolicies.add({
  name: "block-secrets-dir",
  description: "Prevent agent from writing to secrets/ directory",
  match: { events: ["PreToolUse"] },
  fn: async (ctx) => {
    if (!["Write", "Edit"].includes(ctx.toolName ?? "")) return allow();
    const path = ctx.toolInput?.file_path ?? "";
    if (path.includes("secrets/")) return deny("Writing to secrets/ is not permitted");
    return allow();
  },
});

// Keep the agent on track: verify tests before committing
customPolicies.add({
  name: "remind-test-before-commit",
  description: "Keep the agent on track: verify tests pass before committing",
  match: { events: ["PreToolUse"] },
  fn: async (ctx) => {
    if (ctx.toolName !== "Bash") return allow();
    const cmd = ctx.toolInput?.command ?? "";
    if (/git\s+commit/.test(cmd)) {
      return instruct("Verify all tests pass before committing. Run `bun test` if you haven't already.");
    }
    return allow();
  },
});

// Prevent unplanned dependency changes during freeze
customPolicies.add({
  name: "dependency-freeze",
  description: "Prevent unplanned dependency changes during freeze period",
  match: { events: ["PreToolUse"] },
  fn: async (ctx) => {
    if (ctx.toolName !== "Bash") return allow();
    const cmd = ctx.toolInput?.command ?? "";
    const isInstall = /^(npm install|yarn add|bun add|pnpm add)\s+\S/.test(cmd);
    if (isInstall && process.env.DEPENDENCY_FREEZE === "1") {
      return deny("Package installs are frozen. Unset DEPENDENCY_FREEZE to allow.");
    }
    return allow();
  },
});

export { customPolicies };
```

***

## דוגמאות

ספרייה `examples/` מכילה קבצי מדיניות מוכנים להפעלה:

| קובץ                                                 | תוכן                                                                              |
| ---------------------------------------------------- | --------------------------------------------------------------------------------- |
| `examples/policies-basic.js`                         | חמש מדיניות מתחילים המכסות מצבי כשל סוכן נפוצים                                   |
| `examples/policies-advanced/index.js`                | דפוסים מתקדמים: ייבוא טרנזיטיבי, קריאות אסינכרוניות, הסרת פלט, וhooks של סיום סשן |
| `examples/convention-policies/security-policies.mjs` | מדיניות אבטחה מבוססת קונוונציה (חסום כתיבות .env, מנע כתיבה מחדש של git history)  |
| `examples/convention-policies/workflow-policies.mjs` | מדיניות זרימת עבודה מבוססת קונוונציה (תזכורות בדיקה, קובץ כתיבה ביקורת)           |

### שימוש בדוגמאות קבצים מפורשות

```bash theme={null}
failproofai policies --install --custom ./examples/policies-basic.js
```

### שימוש בדוגמאות מבוססות קונוונציה

```bash theme={null}
# Copy to project level
mkdir -p .failproofai/policies
cp examples/convention-policies/*.mjs .failproofai/policies/

# Or copy to user level
mkdir -p ~/.failproofai/policies
cp examples/convention-policies/*.mjs ~/.failproofai/policies/
```

אין צורך בפקודת התקנה — הקבצים נתונים באופן אוטומטי בהודעת hook הבאה.
