---
title: "Writing policies"
description: "How to write a policy file, with its principals, statements, resources, actions, and conditions, how missing values decide, and what the checker refuses."
---

> Documentation Index
> Fetch the complete documentation index at: https://buildrforge.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Writing policies

A policy is a TypeScript file. Forge never runs it: the API parses the file, checks every name in it against the schema that the policy decides, and stores the result. TypeScript is the syntax because people and agents write it fluently and editors already read it.

## A policy file

A policy file imports builders from `@forge/policies` and exports policies made with `orgPolicy` or `repoPolicy`:

```ts
import { orgPolicy, allow, deny, group, model } from "@forge/policies";

export const finance = orgPolicy({
  name: "Finance",
  description: "Finance works on invoices and vendors in every repo, and never deletes a paid invoice.",
  principals: [group("Finance")],
  statements: [
    allow({
      actions: ["read", "create", "update"],
      resource: model("integrations.procore.Invoice"),
    }),
    allow({
      actions: ["read", "update"],
      resource: model("integrations.procore.Vendor"),
    }),
    deny({
      description: "Paid invoices stay.",
      actions: ["delete"],
      resource: model("integrations.procore.Invoice"),
      when: ({ record: invoice }) => invoice.status === "paid",
    }),
  ],
});
```

On its own, this policy shows Finance nothing. Every action in a repo also needs `read` on `repo`, which an allow on a model never grants, and reading the org and listing its repos take `read` and `listRepos` on `org`. A member of Finance gets those from the default Viewer or Editor policy when they're in that group too, or from allows of their own, as [Contractors limited to one repo](https://buildrforge.com/docs/permissions/recipes/#contractors-limited-to-one-repo) shows. See [Repo access](https://buildrforge.com/docs/permissions/#repo-access).

The file follows these rules:

- It holds only imports and `export const <name> = orgPolicy({...})` or `repoPolicy({...})` declarations.
- It imports only from `@forge/policies`, each builder under its own name. `import { deny as allow }` is refused.
- A file holds exactly one policy.
- Every value is a literal. Spreads, variables, computed keys, and function calls other than the builders are refused.

A policy takes these properties:

| Property | Required | What it holds |
| --- | --- | --- |
| `name` | Yes | The policy's name. No leading or trailing spaces. Names need not be unique. A draft that you simulate stands in for the policy whose `policy_id` it carries, not for a policy of its name. |
| `description` | No | What the policy is for, never empty. Each version takes it from its file, and reading a policy back writes it into `source`, so an edit that starts from `source` keeps it. |
| `principals` | Yes | At least one principal. |
| `repos` | No | Org policies only: the repos that the policy covers, by name or id. Without it, the policy covers every repo. |
| `statements` | Yes | The policy's allows and denies. |

An org policy grants and limits access across the org. A repo policy holds only denies and narrows access inside the one repo that it's saved to:

```ts
import { repoPolicy, deny, group, model } from "@forge/policies";

export const fieldStaff = repoPolicy({
  name: "Field staff",
  description: "Field staff never see project financials in this repo.",
  principals: [group("Field")],
  statements: [
    deny({
      actions: ["read"],
      resource: model("integrations.procore.Project financials"),
    }),
  ],
});
```

## Principals

A principal says who a policy applies to:

| Principal | Applies to |
| --- | --- |
| `everyone` | Every member of the org who isn't an owner. Owners bypass every policy. |
| `group("Finance")` | The members of the group. The name matches without regard to case. |
| `user("user_01...")` | One member, by user id. |
| `extension("integrations.procore")` | The extension acting on its own, as its schedules', triggers', webhooks', and mailboxes' runs and its public shares' guests do. `everyone`, groups, and users never match it. |

Forge stores a group principal by the group's id, so renaming a group keeps its policies attached. Deleting a group leaves its principal matching no one, and a new group that takes the deleted group's name doesn't inherit it. When you read a policy back, Forge writes the group under its current name, or a deleted group as its id.

## Statements

A statement is `allow({...})` or `deny({...})` with these properties:

| Property | Required | What it holds |
| --- | --- | --- |
| `actions` | Yes | At least one action, each named once, from the list for the resource's kind. See the [Action reference](https://buildrforge.com/docs/permissions/actions/). |
| `resource` | Yes | What the statement is about. See [Resources](#resources). |
| `when` | No | A condition. A statement without one always applies. See [Conditions](#conditions). |
| `description` | No | What the statement is for. |

A repo policy holds only `deny` statements, because the repo pass already allows everything that no repo deny covers.

## Resources

A statement names one resource, through the builder for its kind. A policy names an extension by its qualified name, `<repo slug>.<name>`: the slug of the repo that defines it, a dot, and its name, so two repos can publish extensions with the same name. The `procore` extension that the repo `integrations` defines is `integrations.procore` in every policy, the policies of the repo that defines it included:

| Kind | One resource | Every resource of the kind |
| --- | --- | --- |
| Model | `model("integrations.procore.Invoice")`, `model("ProjectMember")` | `models` |
| Schema | `schema("integrations.procore.Invoice")`, `schema("ProjectMember")` | `schemas` |
| Repo | `repo` | |
| Extension source | `extension("integrations.procore")` | `extensions` |
| Installation | `installation("integrations.procore")` | `installations` |
| Tool | `tool("integrations.procore/sync_projects")` | `tools("integrations.procore")` for one extension, `allTools` for every extension |
| Workflow | `workflow("integrations.procore/close_month")` | `workflows` |
| Schedule | `schedule("integrations.procore/nightly_sync")` | `schedules` |
| Trigger | `trigger("integrations.procore/invoice_created")` | `triggers` |
| Room | `room("integrations.procore/board")` | `rooms("integrations.procore")` for one extension, `allRooms` for every extension |
| Agent context | | `agentInstructions`, `agentSkills` |
| Org | | `org` |

Models and schemas follow two naming rules:

- A dotted name is an extension's model: the extension's qualified name, a dot, and the model's display name, as in `model("integrations.procore.Invoice")`. Write the display name as it appears, spaces included: `model("integrations.procore.Project financials")`.
- An undotted name is the repo's own model, by its display name, as in `model("ProjectMember")`.

Tools, workflows, schedules, triggers, and rooms are the extension's qualified name, a slash, and the entry's name, such as `tool("integrations.procore/sync_projects")`. An extension's tools that its MCP connection adds at run time aren't known when you save a policy, so reach them through `tools("integrations.procore")`. A prerelease declares nothing that a policy can name. A repo can't install an extension that it defines itself, so a repo policy in that repo can't name the extension's tools, workflows, schedules, or triggers. Release a version, and name them in an org policy that lists the repo.

Forge stores a repo's own model by id and an extension's model by API name, so renaming a model's display name doesn't change what a saved policy means. Reading a policy back writes the current display name.

### Where names resolve

The checker resolves names against the schema that the policy decides:

- A **repo policy** resolves against the repo's schema on `main`: its models, and the tools, workflows, schedules, and triggers that the versions it installs on `main` declare.
- An **org policy** resolves against the latest release of each extension in the org's registry. It can name only what is stable across repos: extension models such as `model("integrations.procore.Project")`, extension tools and workflows, and wildcards. An org policy can't name a model that a repo defines itself. To protect such a model at org level, move it into an extension.

The examples in these docs use this schema. The `integrations.procore` and `people.hr` extensions define most models, and the repo defines `ProjectMember` itself:

| Model | Custom fields |
| --- | --- |
| `integrations.procore.Project` | `name`, `region`, `project_manager` (a user), `status` |
| `integrations.procore.Project financials` | `project` (references `integrations.procore.Project`), `contract_value` |
| `integrations.procore.Vendor` | `name`, `tax_id` |
| `integrations.procore.Invoice` | `project` (references `integrations.procore.Project`), `vendor` (references `integrations.procore.Vendor`), `amount`, `status`, `submitted_by` (a user), `approved_by` (a user) |
| `people.hr.Employee` | `user` (a user), `manager` (a user) |
| `people.hr.Compensation` | `employee` (references `people.hr.Employee`), `salary` |
| `ProjectMember` | `project` (references `integrations.procore.Project`), `user` (a user), `role` |

Conditions read fields by API name (such as `submitted_by`), not display name. A user field holds a user id, so a condition compares it with `user.id`.

## Conditions

A condition is the statement's `when`: an arrow function whose body is one expression. It destructures one argument and can rename what it reads, as in `({ record: invoice, user })`:

```ts
import { repoPolicy, deny, everyone, model } from "@forge/policies";

export const largeInvoices = repoPolicy({
  name: "Large invoices",
  principals: [everyone],
  statements: [
    deny({
      description: "Outside Finance, nobody approves an invoice over 10,000 or edits an approved one over 10,000.",
      actions: ["update"],
      resource: model("integrations.procore.Invoice"),
      when: ({ record: invoice, user }) =>
        invoice.amount > 10_000 &&
        invoice.status === "approved" &&
        !user.groups.includes("Finance"),
    }),
  ],
});
```

### What a condition reads

The argument holds these names:

| Name | What it holds |
| --- | --- |
| `user` | `user.id`, and `user.groups`, which a condition reads only through `includes` |
| `record` | The record that the statement decides: its fields, its `id`, and the records that its references point to |
| `previous` | The record before a write |
| `next` | The record after a write |
| `resource` | For tools, workflows, schedules, triggers, and rooms: `resource.extension`, `resource.name`, and `resource.installation` |
| `request` | `request.channel`, which is `"Api"`, `"Mcp"`, or `"Extension"` when extension code made the request, `request.installation`, the id of the installation whose code made the request, and `request.principal`, which is `"automation"` when an extension acts on its own, `"guest"` for a [public share's](https://buildrforge.com/docs/extensions/extension-ui/#public-shares) guest, who acts as the extension, and `"member"` otherwise |

A statement whose condition reads `record`, `previous`, `next`, or `changed` must name one model as its resource, because only a model has records. Forge sets `request` from the credential that made the request, so extension code can't forge it.

### Operators

A condition is built from these parts:

| Part | Example |
| --- | --- |
| Comparisons: `===`, `!==`, `<`, `<=`, `>`, `>=` | `invoice.amount <= 10_000` |
| Logic: `&&`, `\|\|`, `!` | `!(a && b)` |
| Literals: strings, numbers, and booleans | `"paid"`, `10_000`, `true` |
| A null check on a record's field, with `===` or `!==` only | `invoice.approved_by !== null` |
| Paths that follow references | `invoice.project.project_manager` |
| A record's id, as the last step of a path | `project.id` |
| `includes` on a literal list | `["draft", "submitted"].includes(invoice.status)` |
| `includes` on the user's groups | `user.groups.includes("HR")` |
| `exists`, `canRead`, and `changed` | See the sections below |

A condition always compares. It never tests whether a value is truthy, so write `invoice.approved_by !== null`, not `invoice.approved_by`. It has no `==`, `!=`, `??`, function bodies, or other calls.

### Before and after

A condition on an update runs twice: once with `record` as the record before the write, and once with `record` as the record after it. An allow must hold on both runs, and a deny matches when it holds on either. So a plain `record.status` covers most status rules without a separate concept. "Members update invoices that are drafts or submitted" lets a member move a draft to submitted, and refuses setting the status to approved, because the record after the write fails the condition.

`previous` and `next` pin one side. In both runs, `previous` is the record before the write and `next` the record after it, so a rule about the direction of a change reads them:

```ts
import { repoPolicy, deny, everyone, model } from "@forge/policies";

export const noSendingBack = repoPolicy({
  name: "No sending back",
  principals: [everyone],
  statements: [
    deny({
      description: "A submitted invoice never goes back to draft.",
      actions: ["update"],
      resource: model("integrations.procore.Invoice"),
      when: ({ previous, next }) => previous.status === "submitted" && next.status === "draft",
    }),
  ],
});
```

A create has no record before it, and a delete has none after it, so on those writes `record`, `previous`, and `next` are all the one record that exists, and the condition runs once. Outside a write, all three are the record being read.

### Related records

A path follows a reference to the record that it points to, such as `invoice.project.project_manager`. Two helpers reach further:

- `exists("Model", (row) => ...)` is true when some record of the model matches. The model name follows the same rules as `model(...)`. The row's name can't be `user`, `record`, `previous`, `next`, `resource`, or `request`, even when the condition doesn't destructure it, or any other name in scope. Use `exists` only in a statement on `model(...)` or `models`. On any other resource, such as `repo` or `allTools`, the checker accepts it, but it errs with `unresolvedName` whenever a decision evaluates it, so an allow grants nothing and a deny matches. A deny on `read` on `repo` whose whole condition is an `exists` hides the repo from everyone that its policy names.
- `canRead(reference)` is true when the user can read the record that a reference points to, and false when the reference is `null`. When the target's own read rules call `canRead` in turn, the chain stops at three references.

A condition reads related records with full access, so a rule about `ProjectMember` works for a user who can't read `ProjectMember`. Only the decision leaves the engine, never what the condition read. That is also why `canRead` matters: a plain path such as `invoice.project.project_manager === user.id` doesn't check that the user can read the project.

```ts
import { repoPolicy, deny, canRead, exists, group, model } from "@forge/policies";

export const fieldProjects = repoPolicy({
  name: "Field projects",
  principals: [group("Field")],
  statements: [
    deny({
      description: "Field staff see only the projects that they manage or work on.",
      actions: ["read"],
      resource: model("integrations.procore.Project"),
      when: ({ record: project, user }) =>
        project.project_manager !== user.id &&
        !exists("ProjectMember", (member) => member.project === project.id && member.user === user.id),
    }),
    deny({
      description: "Field staff see invoices on projects that they can read, and the ones that they submitted.",
      actions: ["read"],
      resource: model("integrations.procore.Invoice"),
      when: ({ record: invoice, user }) => !canRead(invoice.project) && invoice.submitted_by !== user.id,
    }),
  ],
});
```

Inside an `exists`, a condition can't hold an `exists` or a `canRead` that reads a row that an `exists` binds. The checker refuses one with `unsupported`. A condition can't follow a reference into another repo.

### Changed fields

`changed("amount")` is true when an update gives the field a different value than it had, `null` included, and false otherwise, so it's false on a create or a delete. Unlike `previous.amount !== next.amount`, it's never unknown, so a deny about changing a field doesn't match a write that leaves a `null` field alone:

```ts
import { repoPolicy, deny, changed, everyone, model } from "@forge/policies";

export const amounts = repoPolicy({
  name: "Amounts",
  principals: [everyone],
  statements: [
    deny({
      description: "Only Finance changes an amount, and only before approval.",
      actions: ["update"],
      resource: model("integrations.procore.Invoice"),
      when: ({ record: invoice, user }) =>
        changed("amount") &&
        (!["draft", "submitted"].includes(invoice.status) || !user.groups.includes("Finance")),
    }),
  ],
});
```

### Groups in conditions

`user.groups.includes("HR")` is true when the user is in the group. It names the group as a principal does: by a string literal, matched without regard to case, which saving resolves to the group's id. A name that no group has is refused with `unknownGroup` and the closest name as a suggested fix, and an argument that isn't a string literal is refused.

Because Forge stores the id, a condition follows its group the way a principal does. Renaming the group keeps the condition, and a new group that takes a deleted group's name gets none of its conditions. Deleting the group makes `user.groups.includes(...)` false for everyone, so a deny that exempts the group with `!user.groups.includes(...)` then matches everyone. Reading the policy back writes the group's current name, or a deleted group's id.

### Tools and requests

A statement on tools, workflows, schedules, triggers, or rooms can read `resource`, and any statement can read `request`. This policy lets PMs call any `integrations.procore` tool, and keeps agents from deleting records through MCP:

```ts
import { orgPolicy, allow, deny, allTools, group, models } from "@forge/policies";

export const pmTools = orgPolicy({
  name: "PM tools",
  principals: [group("PMs")],
  statements: [
    allow({
      actions: ["call"],
      resource: allTools,
      when: ({ resource }) => resource.extension === "integrations.procore",
    }),
    deny({
      description: "Agents connected through MCP never delete records.",
      actions: ["delete"],
      resource: models,
      when: ({ request }) => request.channel === "Mcp",
    }),
  ],
});
```

`request.installation` is missing on a request over the API or MCP, and on a signed-in extension UI page's own call. A public share's page carries its installation's id. Where it's missing, a comparison with it is unknown, and a condition can't test it for `null`. So a deny on `request.installation !== "..."` alone also matches every API and MCP request. Write `request.channel === "Extension" && request.installation !== "..."` to leave those alone. The deny still matches a request from extension code that has no installation.

## Missing values

A condition evaluates to true, false, or unknown. A value is missing when a field is `null` or a path passes through a `null` reference. An empty text, rich text, date, or picklist field counts as `null`, so test it with `=== null`, never `=== ""`:

| Expression | Result |
| --- | --- |
| `a === b`, `a !== b`, `a < b`, and the other comparisons | Unknown when either side is `null` or missing |
| `a.b.c`, when `a.b` is `null` | Missing, so any comparison with it is unknown |
| `a === null`, `a !== null` | Known when `a` is a field of a record that exists. Unknown when the path to it passes through `null` |
| `list.includes(a)` | Unknown when `a` is `null` or missing |
| `canRead(reference)`, `changed("field")`, `exists(...)` | Always known, unless a rule that they run errs. `canRead` of `null` is false, and `exists` skips a row whose body is unknown |
| `!unknown` | Unknown |
| `false && unknown`, `true \|\| unknown` | The known side decides: false, and true |
| `true && unknown`, `false \|\| unknown` | Unknown |

At the top of a condition, unknown grants nothing in an allow and matches in a deny. So a deny such as `invoice.status === "paid"` also matches every invoice without a status. When a field can be empty, guard it: `invoice.status !== null && invoice.status === "paid"`. These are SQL's rules, not JavaScript's, where two missing values are equal and `null !== "user_01..."` is true. They keep a missing value from ever granting access. For example, `invoice.submitted_by !== user.id` never lets a PM approve an invoice that has no submitter, because the comparison is unknown and the deny that holds it matches.

To act on a missing value, test it with `=== null`. An error behaves as unknown too: a name that no longer resolves, a `canRead` deeper than three references or in a cycle, or a check that runs more than 64 related-record lookups (across paths, `exists`, and `canRead`). [Explain](https://buildrforge.com/docs/permissions/testing/#explain) reports an error separately from unknown, so you can tell a broken rule from a missing value. Because a deny that no longer resolves matches every record, Forge refuses with `SchemaChangeBreaksPolicy` when a schema or installation change leaves a field or model in a policy covering the repo — the repo's own or an org policy — unable to resolve (apart from deleting a model that a statement's own `resource` names), and its `problems` name each policy. Change or delete the policy first.

The checker checks names, not values. A comparison with an option that a picklist lacks, or of a text field with a number, saves. Values of two kinds are never equal and have no order, so on a field that holds a value, `===` is false, `!==` is true, and `<` is unknown.

## What the checker refuses

Checking and saving a policy report each problem with a `code`, a `message`, its `location` in the file, and often a suggested `fix`. An error keeps the policy from saving:

| Code | What it means |
| --- | --- |
| `syntax` | The file doesn't parse as TypeScript. |
| `unsupported` | The file uses something the policy language doesn't have, such as another import, a renamed import, `==`, `??`, a function body, a spread, an unknown property, or an `exists` or `canRead` over an `exists` row inside an `exists` body. |
| `truthiness` | A condition tests a value instead of comparing it. Compare explicitly, such as `record.approved_by !== null`. |
| `duplicate` | A property, action, or repo is listed twice, or one file holds two policies with the same name. |
| `unknownModel`, `unknownField` | No model or field has that name where the policy resolves. A field is checked on the model that a path reaches. |
| `unknownAction` | The action isn't on the list for the resource's kind. |
| `unknownExtension`, `unknownTool`, `unknownWorkflow`, `unknownSchedule`, `unknownTrigger` | No extension, or no tool, workflow, schedule, or trigger of one, has that name where the policy resolves: in an installed version for a repo policy, or in the latest release for an org policy. |
| `unknownGroup`, `unknownRepo` | No group or repo in the org has that name. |
| `notAReference` | A path or `canRead` follows a field that isn't a reference. |
| `noRecord` | A condition reads record fields, `changed`, or `resource` on a statement whose resource doesn't have them. |
| `crossRepo` | A path follows a reference into another repo. |
| `repoAllow` | A repo policy holds an `allow`. Move it to an org policy, or write the rule as a deny. |
| `orgActionInRepo` | A repo policy, or an org policy that lists `repos`, names `org`. Org actions belong to no repo. |
| `repoModelInOrgPolicy` | An org policy names a model that a repo defines itself. |

For example, checking this repo policy reports `repoAllow`:

```ts
// Refused: repoAllow
import { repoPolicy, allow, everyone, model } from "@forge/policies";

export const vendors = repoPolicy({
  name: "Vendors",
  principals: [everyone],
  statements: [allow({ actions: ["read"], resource: model("integrations.procore.Vendor") })],
});
```

A saved policy keeps the models it names: renaming a model doesn't change which records the policy covers, and a model that later takes the old name isn't one of them.

When a repo's schema changes, a stored policy can hold names that stopped resolving. Such a name is an error where Forge decides with it: an allow that names it or reads it grants nothing there, and a deny that names it or reads it denies there.

Source: https://buildrforge.com/docs/permissions/writing-policies/index.mdx
