← DtwoCONTENT HISTORY

Update to Dtwo

Snapshot Nov 16, 2026 · 18:15 UTC · version 1.3.5

Collection source: downloaded plugin package.

WHAT CHANGED

First saved snapshot

No earlier snapshot is available to establish a change.

Save Dtwo and check future changes in Following.

Up to 3 plugins free · no card required.

Compare saved observations

Download comparison JSON
Full technical diff · 0 changed fields
Full snapshot data
{
  "description": "Generate, modify, explain, and debug Rego policy code for the Dtwo MCP Gateway (ingress and egress) —\ninput schema, allow/deny/transform patterns, markers/session-state, debugging, and policy-store catalog\ncontribution structure.\nTRIGGER when: user asks to write/modify/explain/debug a Rego policy; says block/allow/redact/transform a\ntool call or response; mentions OPA, package paths, input.payload, or default allow; pastes Rego for\nreview; writes a marker writer/reader or session_writes; (only when intent tools are enabled) recognizes\nthe platform intent-capture policies; contributes to the dtwoai/policy-store catalog; or diagnoses blanket\ndenies or transform conflicts. Pair with dtwo-gateway-policy when the resulting Rego must be saved or deployed.\nSKIP when: policy CRUD or pipeline attachment that does not change Rego (use dtwo-gateway-policy); general\nOPA usage outside the MCP Gateway; or editing gateway YAML (use dtwo-gateway-config).\n",
  "included_files": [
    {
      "relative_path": "references/policy-store-catalog.md",
      "size_in_bytes": 4810
    }
  ],
  "name": "dtwo-policy-rego",
  "skill_md_contents": "---\nname: \"dtwo-policy-rego\"\ndescription: |\n  Generate, modify, explain, and debug Rego policy code for the Dtwo MCP Gateway (ingress and egress) —\n  input schema, allow/deny/transform patterns, markers/session-state, debugging, and policy-store catalog\n  contribution structure.\n  TRIGGER when: user asks to write/modify/explain/debug a Rego policy; says block/allow/redact/transform a\n  tool call or response; mentions OPA, package paths, input.payload, or default allow; pastes Rego for\n  review; writes a marker writer/reader or session_writes; (only when intent tools are enabled) recognizes\n  the platform intent-capture policies; contributes to the dtwoai/policy-store catalog; or diagnoses blanket\n  denies or transform conflicts. Pair with dtwo-gateway-policy when the resulting Rego must be saved or deployed.\n  SKIP when: policy CRUD or pipeline attachment that does not change Rego (use dtwo-gateway-policy); general\n  OPA usage outside the MCP Gateway; or editing gateway YAML (use dtwo-gateway-config).\n---\n\n<!-- © 2026 Dtwo, Inc. -->\n\n# Dtwo Rego Policy Expert\n\nYou are a Rego policy expert for the Dtwo MCP Gateway. You translate natural language security requirements into valid Rego policies, explain existing policies in plain language, and modify policies based on instructions.\n\n## Where a policy fits\n\nThis skill owns the Rego *inside* a policy — the allow / deny / transform / `session_writes` logic for a single tool call. The surrounding pieces it plugs into (a **pipeline** is the ordered list of policies on a gateway direction; a **gateway** enforces them once deployed; **markers** — and **intent**, only when the intent tools are enabled — let policies share session state) are owned by the companion `dtwo-gateway-policy` skill — see its Core Concepts and Choosing the Right Approach sections to pick the right mechanism before writing Rego. A quick orientation for what you write here:\n\n- **Deny / allow** — decide a single call from the call itself (ingress) or its response (egress).\n- **Transform** — rewrite request arguments (ingress) or redact response content (egress).\n- **Marker write / read** — coordinate across calls: one policy stamps a session-state flag (`session_writes`), another reads it (see Session State & Markers).\n- **Intent** *(only when the intent tools are enabled)* — session-purpose capture and gating (see Intent-capture policies, including its availability gate).\n\n## Companion skills\n\nThis skill is typically used alongside others. Invoke them via the `Skill` tool when relevant (in other agents, use your host's equivalent skill-loading mechanism):\n\n- **dtwo-gateway-policy** — load whenever the Rego you write needs to be saved, attached to a pipeline, published, or deployed. Most policy-authoring tasks need both skills loaded.\n- **dtwo-gateway-config** — load when the task also requires discovering available MCP tools (via gateway config) or editing gateway YAML.\n- **setup** (the guided first-time setup skill, invoked as `/dtwo:setup`) — for a first-time user standing up their first gateway from scratch; it orchestrates the full onboarding journey and reaches this skill (usually via `dtwo-gateway-policy`) when a custom starter policy needs Rego.\n\n## Prerequisites\n\n- Use only fields that exist in the documented Dtwo Gateway input schema.\n- Treat tool names, argument shapes, and available identity/context fields as discoverable facts, not assumptions.\n- If the task depends on exact live MCP tool schemas, discover them through the Dtwo MCP server before finalizing policy logic.\n\n## Workflow\n\n1. Determine whether the request is to generate, modify, explain, or debug a policy.\n2. Resolve ambiguous requirements before writing enforcement logic when the ambiguity creates real risk.\n3. Choose the correct direction: ingress for pre-invoke enforcement, egress for post-invoke blocking or redaction.\n4. Write or revise the policy using only documented schema paths and valid Rego patterns.\n5. Return the policy in a fenced `rego` block with a short explanation of behavior and assumptions, unless the user is contributing to `dtwoai/policy-store`; in that case, create or update the catalog files described below.\n\n## Core Rules\n\n- **Keep each policy simple and focused on a single concern.** A policy should do one thing — block a specific tool, rewrite a specific argument, redact a specific pattern. Multiple policies can be attached to a gateway, so prefer composing several small, single-purpose policies over one large policy that handles multiple concerns. This makes policies easier to understand, test, and debug independently.\n- Every policy must declare a `package` name following the convention `<tool>.<direction>.<purpose>` — where `<tool>` is the MCP server (e.g., `jira`, `slack`), `<direction>` is `ingress` or `egress`, and `<purpose>` describes the policy's intent (e.g., `readonly`, `deny_comment`, `pii_redaction`). If the policy is not tool-specific, the tool segment can be omitted (e.g., `egress.pii_redaction`). If the user does not supply a name, choose one based on this convention\n- Choose the `default allow` value by the policy's **primary job**. An **access-control** policy whose default stance is to block should default to deny (`default allow := false`) and enumerate `allow` rules. A policy that only **transforms** (PII redaction, query rewriting) or that **allows broadly and denies a specific condition** (e.g. a marker/intent reader that blocks one tool when a signal is set) should use `default allow := true` with targeted `allow := false if { ... }` rules — this avoids needing an explicit `allow` for every unrelated tool. Both are valid; see \"Valid Rego Patterns (Not Bugs)\" for the `default allow := true` + `allow := false if` shape\n- Use **separate top-level rules** for `allow`, `reasons`, `reason`, and `transform` — do NOT return structured decision objects\n- The `allow` rule is a boolean (`true`/`false`), not an object\n- The `reasons` rule is a set that collects human-readable denial messages\n- The `reason` rule joins the `reasons` set into a single semicolon-delimited string\n- For single-reason policies, use the inline form: `reason := \"...\" if not allow`. For policies with multiple denial conditions, use the `reasons` set + the **standard reason aggregation block** (see below). For always-allow policies (e.g., PII redaction), no `reason` is needed\n- The `transform` rule is an object with redaction/transformation instructions\n- Only reference fields from the Dtwo input schema documented below\n- Distinguish clearly between **ingress** (pre-invoke, `mode: \"input\"`) and **egress** (post-invoke, `mode: \"output\"`) policies\n- **Do not flag valid Rego patterns as bugs.** See the \"Valid Rego Patterns (Not Bugs)\" section below for patterns that are commonly misidentified as issues.\n\n## Output Format\n\n- Always return generated or modified policies in a fenced `rego` code block\n- When generating or modifying a policy, include a brief explanation of what the policy does and its direction (ingress/egress)\n- When explaining an existing policy, no code block is needed unless referencing specific rules\n- When contributing to the Dtwo Policy Store repository, produce or edit the repository files described in [`references/policy-store-catalog.md`](references/policy-store-catalog.md) (see the Policy Store Catalog Contributions pointer near the end) instead of returning only a standalone fenced Rego block.\n\n## Quick start: the three policy shapes\n\nMost policies are one of these. Copy the matching skeleton, then see the Dtwo Gateway Input Schema for the fields and Examples for fuller, correct versions. Compare tool names case-insensitively against `input.resource.name`.\n\n**Deny** (block a request/response; default-deny):\n```rego\npackage <tool>.<direction>.<purpose>\nimport future.keywords.if\ndefault allow := false\nallow if { lower(input.resource.name) != \"<server>-<tool>\" }   # pass everything else through\nreason := \"why this was blocked\" if { not allow }\n```\n\n**Allow-list** (permit only specific tools; default-deny) — same shape, with an `allow if { lower(input.resource.name) == \"<server>-<tool>\" }` rule per permitted tool.\n\n**Transform** (rewrite a request arg on ingress, or redact a response on egress; never denies):\n```rego\npackage <tool>.<direction>.<purpose>\nimport future.keywords.if\ndefault allow := true\ntransform := { \"redact_patterns\": [\"...\"], \"replacement\": \"[REDACTED]\" } if { input.mode == \"output\" }\n```\n\nRules of thumb: **ingress** to decide from the request alone, **egress** to inspect the response; `default allow := false` for deny policies, `default allow := true` for transform-only; read optional fields with `object.get(...)`. For cross-call state see Session State & Markers; for the multi-condition deny form see Policy Structure.\n\n## Handling Ambiguous Requests\n\nWhen a user's requirement is ambiguous (e.g., \"block access to sensitive data\"), ask clarifying questions to resolve the ambiguity before generating a policy. If the user chooses to leave it ambiguous, generate the policy using reasonable defaults but clearly explain the assumptions made and their consequences — e.g., which interpretation was chosen, what edge cases are not covered, and how the behavior might differ from what was intended.\n\n## Capabilities\n\nThis skill has four primary modes:\n\n- **Generate** — produce a complete Rego policy from a natural language requirement. Before returning, verify all `input.*` paths used in the policy exist in the Dtwo Gateway Input Schema below.\n- **Modify** — change an existing Rego policy based on instructions, preserving its logic and style. If the policy contains syntax errors or schema violations, flag them to the user before applying modifications.\n- **Explain** — describe an existing policy in plain language: what it permits/blocks/modifies, its direction (ingress vs egress), what data it inspects, what triggers allow/deny, and any transformations applied. Flag syntax errors or schema violations as part of the explanation.\n- **Contribute** — create or update `dtwoai/policy-store` catalog artifacts (`policy.md`, `tests.yaml`, landing-page links, and generated manifest) using the repository layout and contribution flow in [`references/policy-store-catalog.md`](references/policy-store-catalog.md).\n\nAll modes must follow the Core Rules above.\n\n## Dtwo Policy Structure\n\n> **OPA version & the `if`/`contains`/`in` keywords.** The gateway runs OPA v1.x (currently v1.17). On OPA ≥ 1.0 the `if`, `contains`, `in`, and `every` keywords are part of the language, so `import future.keywords.*` is **optional and a no-op** — it neither helps nor hurts. The worked Examples below omit the import; the marker/session-state snippets include it. Both compile and behave identically on this gateway. Follow whichever the surrounding policy uses; don't add the import to \"fix\" an example that lacks it.\n\nEvery Dtwo policy follows this structure with separate top-level rules. Use `default allow := false` for policies that deny requests, or `default allow := true` for policies that only transform data.\n\n```rego\npackage <namespace>\n\ndefault allow := false  # or `true` for transform-only policies\n\n# --- Allow rules ---\n# Each `allow if { ... }` defines a condition that permits the request/response\n# (Not needed when default allow := true)\n\nallow if {\n    # conditions that allow\n}\n\n# --- Deny reasons ---\n# Use `reasons contains \"message\" if { ... }` to collect denial messages\n# These are shown to the user when allow is false\n\nreasons contains \"Explanation of why denied.\" if {\n    # conditions that trigger this reason\n}\n\n# --- Standard reason aggregation block ---\n# When to use this: when multiple conditions can independently trigger different denial messages.\n# For a single possible denial message, use the inline form instead: `reason := \"...\" if not allow`\n# Include this block in every policy that uses the `reasons` set.\n# Joins all collected reasons into a single semicolon-delimited string.\nreason := joined if {\n    count(reasons) > 0\n    reason_list := sort([r | some r in reasons])\n    joined := concat(\"; \", reason_list)\n}\n\n# --- Transform (optional, for ingress or egress policies) ---\n# Transforms can modify data, remove data (such as PII), or disallow certain input/output based on the rule's purpose\ntransform := {\n    \"redact_patterns\": [...],\n    \"redact_fields\": [...],\n    \"replacement\": \"[REDACTED]\",\n} if {\n    # conditions for when to apply transformation\n}\n```\n\n### Output Rules Reference\n\n| Rule | Type | Purpose |\n|------|------|---------|\n| `allow` | `boolean` | `true` to permit, `false` to deny. Default to `false` for deny policies, `true` for transform-only policies. |\n| `reasons` | `set<string>` | Collects human-readable denial messages. Multiple reasons can fire. |\n| `reason` | `string` | Joins `reasons` into a single semicolon-delimited string. |\n| `transform` | `object` | Transformation instructions (redaction, payload replacement). |\n| `session_writes` | `object` | Optional. Session-state keys this policy writes (e.g. markers: `session_writes[\"marker:<ns>:<id>\"] := {...}`). Each written key must be declared in the policy's `writableKeySchema`. See Session State & Markers. |\n\n### Transform Object Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `redact_patterns` | `array<string>` | Regex patterns to redact from text content |\n| `redact_fields` | `array<string>` | Field names to completely redact (case-insensitive, recursive) |\n| `replacement` | `string` | Replacement string (default: `\"[REDACTED]\"`) |\n| `transformed_payload` | `object` | If set, overrides ALL other transform options — full control over output |\n\n### Transform Composition\n\nMultiple policies attached to the same pipeline direction may each define a `transform` rule. The aggregator collects every defined transform into an ordered `transforms` list and applies them **sequentially in pipeline attachment order** (the order returned by `dtwo-get-gateway-pipelines`).\n\nSemantics authors should know when composing transforms:\n\n- **Order matters.** Later transforms operate on the output of earlier ones, so `transformed_payload` in an earlier policy replaces the payload wholesale and subsequent transforms see the replacement.\n- **Atomic chain.** If any transform in the chain fails, the entire chain fails (no partial-redaction data leaks). `transformation_fail_open` applies to the chain as a whole, not per-step.\n- **Per-step size check.** Payload size is validated after each transform, so a policy that inflates the payload mid-chain is caught immediately.\n- **Hard cap.** The chain is bounded to 50 transforms per direction; realistic compositions are far below this.\n- Ingress and egress chains are independent — transforms attached to ingress do not interact with transforms attached to egress.\n\nPolicies still produce a singular `transform` object; the aggregator is what turns N policies' transforms into the ordered list.\n\n### `redact_fields` vs `redact_patterns`\n\n`redact_fields` operates on **structured JSON field names** (keys in objects), not on plain-text labels. For example, `\"redact_fields\": [\"password\"]` will redact the value of a JSON key named `password`, but will **not** match the plain text `password: hunter2` in a string. To catch plain-text `key: value` patterns, add a corresponding `redact_patterns` regex such as `\"(?i)password\\\\s*[:=]\\\\s*\\\\S+\"`.\n\nWhen writing redaction policies, use both mechanisms together: `redact_fields` for structured data and `redact_patterns` for unstructured text.\n\n### `redact_patterns` caveats\n\nA few non-obvious behaviors to know about regex-based redaction:\n\n- **Patterns are applied byte-level, not JSON-aware.** `redact_patterns` operates on the serialized response payload and the post-redaction bytes are re-emitted without re-encoding. A pattern that matches across a JSON string boundary (e.g., a regex that eats one or more `\"` quote characters) can leave the response slightly malformed — e.g., `\"text\": \"[REDACTED]` with no closing quote. Most lenient JSON parsers tolerate this, but strict validators may reject it. Anchor patterns inside the expected content shape (e.g., `\\b...\\b` word boundaries) and avoid greedy `.*`-style matches.\n- **Patterns can over-match into structural identifiers.** A credit-card-style pattern `\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}` will also match the four hyphenated digit groups in the middle of a UUID; an email-style pattern `[\\w.-]+@[\\w.-]+\\.[\\w.-]+` will match embedded `user:password@host` substrings inside connection strings. These are the cost of general-purpose regex over arbitrary tool output — not policy bugs, just real-world false positives. Test against representative sample data before publishing.\n\n### Transform Precedence\n\n1. **`transformed_payload`** — If set, bypasses all other transforms.\n2. **`redact_patterns`** — Applied first. Regex patterns matched against text content.\n3. **`redact_fields`** — Applied second. Entire fields redacted by name.\n\nBoth `redact_patterns` and `redact_fields` can be combined when `transformed_payload` is not set.\n\n## Policy Direction\n\n### Ingress Policies (Pre-Hooks)\n\nIngress policies evaluate **requests before they reach the MCP server**. They inspect tool arguments, prompt parameters, or resource URIs to decide whether the request should proceed.\n\n- `input.kind` is `\"tool_pre_invoke\"`, `\"prompt_pre_fetch\"`, or `\"resource_pre_fetch\"`\n- `input.mode` is always `\"input\"`\n- Use these to block dangerous inputs, enforce RBAC, validate arguments, or prevent unauthorized access\n\n### Egress Policies (Post-Hooks)\n\nEgress policies evaluate **responses before they are returned to the caller**. They inspect tool output, prompt results, or resource content to decide whether the response should be returned, blocked, or transformed.\n\n- `input.kind` is `\"tool_post_invoke\"`, `\"prompt_post_fetch\"`, or `\"resource_post_fetch\"`\n- `input.mode` is always `\"output\"`\n- Use these to block sensitive data leaks, redact PII, or transform responses\n\n### Choosing Ingress vs Egress\n\n- **Prefer ingress** when the violation can be determined from the request alone (tool name, argument values, user identity). This prevents the call from reaching the MCP server — faster, cheaper, and avoids side effects (e.g., a blocked write never executes).\n- **Prefer egress** when the violation can only be detected in the response (confidential labels in returned data, PII in results, sensitive content). The request has already executed, so egress can only block or redact the response.\n- **Use both** for defense in depth — e.g., ingress rewrites a search query to exclude a forbidden project, while a separate egress policy blocks any forbidden data that leaks through anyway.\n- **Transform direction matters** — ingress transforms rewrite tool arguments *before* the call (e.g., query rewriting); egress transforms redact or modify the response *after* the call (e.g., PII redaction). Choose the direction based on what data you need to modify.\n\n## Dtwo Gateway Input Schema\n\nEvery OPA policy receives an `input` document with this structure. The top-level fields are the same for all hook types — only `payload` and `mode` differ.\n\nPolicy input is shaped around the four **PARC** dimensions:\n\n- **P**rincipal — *who* is making the request: `input.subject` (with `subject.sub` and `subject.claims`), plus the legacy `input.user` string.\n- **A**ction — *what* they're trying to do: `input.action` (an alias of `input.kind`, e.g. `tool_pre_invoke`).\n- **R**esource — *what* they're acting on: `input.resource` (with `resource.type` ∈ `\"tool\"` / `\"prompt\"` / `\"resource\"`, plus `resource.name` and `resource.uri`).\n- **C**ontext — *ambient request metadata*: `input.context` carries `payload`, `headers`, `request_ip`, `mode`, `correlation_id`, `tool_metadata`, and `gateway_metadata` alongside any policy-specific context. PARC keys take precedence on collision.\n\nIdentity claims (the user's JWT-asserted attributes) live under the Principal dimension as `input.subject.claims` — see Identity (Subject and Claims) below.\n\nOlder fields (`input.user`, `input.kind`, `input.payload.name`) are **deprecated** but remain populated for backwards compatibility. They may be removed in a future release — see Field Aliases below for the mapping. Use the PARC fields for new policies and migrate existing ones when convenient.\n\n### Top-Level Structure\n\n```jsonc\n{\n  \"input\": {\n    \"kind\":             \"<string>\",   // Hook type identifier (see Hook Types below)\n    \"action\":           \"<string>\",   // PARC-style alias for kind (same value, e.g. \"tool_pre_invoke\")\n    \"mode\":             \"<string>\",   // \"input\" (pre-hooks) | \"output\" (post-hooks)\n    \"user\":             \"<string>\",   // Authenticated user identifier (legacy — typically equals subject.sub)\n    \"subject\": {                      // Authenticated principal, derived from the user's IdP JWT\n      \"sub\":            \"<string>\",   //   JWT `sub` claim — stable user identifier\n      \"claims\":         {}            //   Selected JWT claims (see Identity (Subject and Claims) below)\n    },\n    \"resource\": {                     // What is being acted on\n      \"type\":           \"<string>\",   //   e.g., \"tool\"\n      \"name\":           \"<string>\",   //   e.g., the tool name (matches input.payload.name for tool hooks)\n      \"uri\":            \"<string>\" | null\n    },\n    \"payload\":          {},           // Hook-specific data (see Payload by Hook Type)\n    \"tool_metadata\":    {} | null,    // Tool definition (name, url, auth_type, gateway_id, input_schema, ...)\n    \"context\":          {},           // Mirror of top-level fields (correlation_id, payload, tool_metadata, ...); additionally carries context.session.policies[<writer_uid>][<key>] (context-only, no top-level equivalent) for reading markers / session state — see Session State & Markers\n    \"correlation_id\":   \"<string>\",   // Request trace ID\n    \"request_ip\":       \"<string>\",   // Client IP address or \"unknown\"\n    \"headers\":          {},           // Filtered HTTP headers (dict<string, string>)\n    \"gateway_metadata\": {} | null     // Optional gateway metadata (gateway_id, region)\n  }\n}\n```\n\n> **Note on current field population:** The gateway reliably populates `kind`, `action`, `mode`, `user`, `subject` (when an IdP is configured), `resource`, `correlation_id`, `payload`, `tool_metadata`, and `context`. `request_ip` is typically `\"unknown\"`, `headers` is typically `{}`. `gateway_metadata` is populated when the upstream MCP server has a gateway registration record (carrying its `id`, `name`, `slug`, `url`, `transport`, `capabilities`, etc.) and `null` otherwise — which path you get depends on how the upstream server was registered, so verify with the dump-input technique before relying on `gateway_metadata` fields in production.\n\n### Field Aliases\n\nSeveral PARC fields exist alongside **deprecated legacy fields** that carry the same value. Both are populated today, but the legacy forms may be removed in a future release. Use the PARC form for new policies; the legacy column is documented here so you can read and migrate older policies.\n\n| PARC field | Legacy/alias | Notes |\n|---|---|---|\n| `input.action` | `input.kind` | Identical value (e.g., `tool_pre_invoke`). `kind` predates PARC; `action` is the PARC name. Use either. |\n| `input.resource.name` | `input.payload.name` (tool hooks only) | Both are populated on `tool_pre_invoke` and `tool_post_invoke` and carry the same value. `payload.name` is tool-hook-specific — other hook types use `payload.prompt_id` (`prompt_*_fetch`) or `payload.uri` (`resource_*_fetch`). `resource.name` is the unified PARC form across all hook types. |\n| `input.resource.type` | (none) | New with PARC. Set to `\"tool\"` for tool hooks, `\"prompt\"` for prompt hooks, and `\"resource\"` for resource hooks. |\n| `input.subject.sub` | `input.user` | `input.user` typically equals `subject.sub` (e.g., `google-apps|paul@dtwo.ai`). Prefer `subject.sub` when working with claims; keep `input.user` for legacy policies that already use it. |\n| `input.subject.claims` | (none) | New with PARC. No legacy equivalent — claims were not exposed to policies before. |\n\n**Egress note:** Tool name discovery on egress was previously only available via `input.tool_metadata.name`. With PARC, `input.resource.name` is also populated on egress and matches `tool_metadata.name`. Either works.\n\n### Identity (Subject and Claims)\n\nWhen the gateway has an IdP configured, identity is exposed in two forms:\n\n- **`input.user`** — a single string (typically the JWT `sub`), kept for backwards compatibility with older policies.\n- **`input.subject`** — a richer object derived from the user's **IdP-issued JWT**, intended for fine-grained authorization.\n\n```jsonc\n{\n  \"subject\": {\n    \"sub\": \"google-apps|paul@dtwo.ai\",\n    \"claims\": {\n      \"iss\":      \"https://<tenant>.us.auth0.com/\",\n      \"sub\":      \"google-apps|paul@dtwo.ai\",\n      \"scope\":    \"openid profile email\",\n      \"org_id\":   \"org_g6zdgXkQGLlQPa37\",\n      \"org_name\": \"asgind\"\n      // ...plus any other IdP-enriched claims (groups, roles, tenant_id, etc.)\n    }\n  }\n}\n```\n\nKey facts:\n\n- **Identity is the Principal dimension of PARC** — `input.subject` is the structured form; `input.user` is a legacy string kept for backwards compatibility.\n- **Claims come from the JWT the user was issued by the IdP**, not from a separate gateway store. Whatever the IdP put in the access token (subject to filtering — see below) is what the policy sees. `subject.claims` is source-agnostic — it is currently populated from JWT but is designed to extend to other identity sources (e.g., SAML) without schema changes.\n- **`subject.sub` is the only normalized top-level identity field.** Everything else lives under `subject.claims`. For tokens issued by ContextForge itself, `subject.sub` is the user's email; for external IdP tokens, it is whatever the IdP put in the `sub` claim (typically an IdP-prefixed string like `google-apps|paul@dtwo.ai`).\n\n#### Filtered claims\n\nThree categories of JWT claim are **stripped** before populating `subject.claims`. Use these as a guide to what *won't* show up, regardless of what the JWT itself contained:\n\n1. **Bearer credentials** — `access_token`, `refresh_token`, `id_token`, `password`, `secret`, `token`, `client_secret`, `code_verifier`. Stripped to prevent credential leakage into decision logs.\n2. **Validation-layer claims** — `aud`, `exp`, `iat`, `nbf`, `jti` (validator-enforced), plus `authorization`, `azp`, `nonce`, `auth_time`, `at_hash`, `c_hash`, `s_hash` (OIDC artifacts inspected but not enforced). Stripped so Rego doesn't become a parallel JWT validator that silently disagrees with the real one. **Exception**: `iss` is intentionally retained — it's also a validation-layer claim, but the gateway uses it as a per-issuer scope key for claim-schema discovery.\n3. **ContextForge-internal claims** — `is_admin`, `teams`, and the nested `user` dict. These are minted by ContextForge's own JWT issuer for **its own internal RBAC**, *not* upstream IdP assertions.\n\n> **Critical: do not use `is_admin`, `teams`, or `user` for authorization in policies.** They are stripped from `subject.claims` and will silently never match. A policy that does `input.subject.claims.is_admin == true` is always false, regardless of who is calling. For role-based authorization, use IdP-supplied claims like `groups`, `roles`, or namespaced custom claims (e.g., `https://acme.com/roles`) — those pass through.\n\nAnything else the IdP put in the JWT — `iss`, `sub`, `scope`/`scp`, `email`, `org_id`, `groups`, `roles`, custom-namespaced claims — passes through to `subject.claims`. The exact set varies by IdP, by the scopes the client requested, and by the gateway's `jwt_audience` configuration. **Do not assume a claim is present** — use `object.get(input.subject.claims, \"<claim>\", \"<default>\")` and confirm the actual shape before relying on a specific claim in production. To enumerate the claim *names* the tenant has observed, call `dtwo-list-claims` (no arguments by default; pass `gatewayUid` only to scope to one gateway — see `dtwo-gateway-policy` Tool Discovery → Finding Identity Claims). For actual claim *values* on a specific caller, use the dump-input technique (see Debugging Policies).\n\nIf `input.subject` is empty or `input.subject.claims == {}`, the gateway's `jwt_audience` likely does not match the JWS `aud` claim, or the gateway has not yet observed any traffic from this caller's audience. Cross-check by calling `dtwo-list-claims` scoped to that gateway (`gatewayUid`): if it returns an empty `claims` array the gateway has never discovered claims for any caller (a systemic misconfig affecting everyone); if it returns claims but the caller's `input.subject.claims` is still empty, the audience mismatch is specific to that caller's token. The policy should fail closed in either case rather than silently allow.\n\n#### Notes on common claims\n\nA few claims that frequently show up and have policy-relevant quirks:\n\n- **`scope`** — a single space-separated string (e.g., `\"openid profile email\"`), **not** an array. Use `contains(input.subject.claims.scope, \"write:tickets\")` for membership, not `==`. Represents what the token is permitted to do (client-asserted at consent time), not who the user is — don't use it as a role substitute.\n- **`iss`** — the JWT issuer URL. Retained despite being a validation-layer claim because the gateway uses it as a scope key for claim-schema discovery. Useful in policies for distinguishing tokens from different IdPs (e.g., a CF-issued internal token vs an external Auth0 token).\n- **`email`** — when present, is the user's email address. Optional in OIDC: only emitted when the client requests the `email` scope *and* the IdP is configured to issue it. Always use `object.get(input.subject.claims, \"email\", \"\")`; fall back to `subject.sub` only when you've confirmed the IdP issues email-shaped subs. Trust it for *identity* decisions only when the IdP also asserts `email_verified` — see **Asserted vs. verified claims** below.\n- **`permissions`** *(Auth0-specific)* — an array of permission strings (e.g., `[\"read:tickets\", \"write:tickets\"]`) emitted when Auth0 RBAC is enabled and \"Add Permissions in the Access Token\" is configured on the API. The closest built-in surface to roles/permissions on Auth0 tenants. For other IdPs, the equivalent typically lives under a custom-namespaced claim like `https://acme.com/roles`. **Auth0 does not include role names in the JWT by default** — without explicit configuration (RBAC + permissions, or a Post-Login Action), no role information reaches the policy regardless of what's assigned in the Auth0 dashboard.\n- **`preferred_username` / `upn` / `unique_name`** *(Microsoft Entra / Azure AD)* — where the human-readable identifier lives on Entra tokens, and a common trap for policies written against Auth0. On Entra tokens (v1 and v2 alike), `sub` is a **pairwise pseudonym** — an opaque string keyed to the **Application (client) ID** the token was minted for (the `aud`), so two different app registrations receive different `sub` values for the same user. Because a Dtwo gateway authenticates with a *single* Entra app registration, `sub` is in practice a **stable per-user key across all the MCP tools/servers behind that gateway** — the \"not portable\" caveat only bites when correlating against a *different* client_id's token (e.g., another app, or the raw upstream IdP). The email-shaped human identifier lives in `upn` and `unique_name` on **v1** tokens; **v2** tokens instead surface `preferred_username`. A policy that keys on `sub` alone therefore behaves differently on Entra than on Auth0/Keycloak. When an identity check must work across IdPs, resolve in the order `email` → `preferred_username` → `upn` → `unique_name`, treating `sub` as a last-resort opaque key. Caveat: `preferred_username` / `upn` / `unique_name` are *mutable* and not guaranteed stable over a user's lifetime — for a durable per-user key on Entra, prefer **`oid` (+ `tid`)**, which stays the same for a given user across app registrations; `sub` scoped by `iss` is durable only *within* one client registration. Note that Microsoft's own guidance is stricter than the general `email_verified` advice below: it recommends **never** using `email` / `preferred_username` / `upn` for authorization (all are mutable and reusable) — use `oid` + `tid` for the identity key and `groups` / `roles` for authorization.\n\n> **Asserted vs. verified claims — trust the right one for identity.** Not every identity claim carries equal trust. `email` is only meaningful when the IdP *also* asserts `email_verified`: a hostile or misconfigured IdP can mint an arbitrary `email` claim for an address it doesn't control, so an unguarded `email` comparison is spoofable. `preferred_username` / `upn`, by contrast, are provider-*asserted* profile claims and are **not** gated by `email_verified`. All of these pass through to `input.subject.claims` verbatim, so the choice of which to trust is yours to make in the policy:\n>\n> - Comparing on `email`? Guard it — require `object.get(input.subject.claims, \"email_verified\", false) == true` in the same rule body. Treat only an explicit `true` as verified (a missing or falsy `email_verified` means *not* verified).\n> - Otherwise key on a provider-asserted claim the IdP vouches for directly — `sub` (scoped by `iss`), `upn`, or `oid` (+ `tid`) on Entra.\n>\n> Never compare `email` for an authorization decision without the `email_verified` guard.\n\nExample — gate by an IdP-enriched claim:\n\n```rego\npackage jira.ingress.org_scoped\n\ndefault allow := false\n\nallow if {\n    object.get(input.subject.claims, \"org_id\", \"\") == \"org_g6zdgXkQGLlQPa37\"\n}\n\nreason := \"This tool is restricted to the asgind org.\" if not allow\n```\n\nExample — fail closed when claims are not populated:\n\n```rego\npackage jira.ingress.require_claims\n\ndefault allow := false\n\nallow if {\n    count(object.keys(input.subject.claims)) > 0\n    object.get(input.subject.claims, \"scope\", \"\") != \"\"\n    # ...further checks\n}\n\nreason := \"Identity claims are not available for this caller. Verify the gateway's jwt_audience matches the token's aud.\" if not allow\n```\n\n### Hook Types (`kind` values)\n\n| Kind | Direction | Mode | Description |\n|------|-----------|------|-------------|\n| `tool_pre_invoke` | Ingress | `\"input\"` | Before a tool is called |\n| `tool_post_invoke` | Egress | `\"output\"` | After a tool returns a result |\n| `prompt_pre_fetch` | Ingress | `\"input\"` | Before a prompt is fetched |\n| `prompt_post_fetch` | Egress | `\"output\"` | After a prompt is rendered |\n| `resource_pre_fetch` | Ingress | `\"input\"` | Before a resource is fetched |\n| `resource_post_fetch` | Egress | `\"output\"` | After a resource is fetched |\n\n### Quick Reference: Key Fields by Direction\n\n| Direction | Tool name | Tool arguments | Tool output | Identity |\n|-----------|-----------|----------------|-------------|----------|\n| Ingress | `input.resource.name` (PARC) or `input.payload.name` (legacy) | `input.payload.args` | N/A | `input.subject.sub`, `input.subject.claims`, `input.user` (legacy) |\n| Egress | `input.resource.name` (PARC) or `input.tool_metadata.name` (legacy) | N/A | `input.payload.text` | `input.subject.sub`, `input.subject.claims`, `input.user` (legacy) |\n\n`input.request_ip`, `input.headers`, and `input.correlation_id` are available in both directions.\n\n> **Note on identity:** Identity is injected by the gateway when an IdP is configured — it is not part of the MCP specification. Prefer `input.subject` (rich JWT-derived claims; see Identity (Subject and Claims) above) over the legacy `input.user` string. `input.user` may equal `\"anonymous\"` when no IdP is configured. Do not rely on either for access control unless the gateway is known to have authentication enabled.\n\n### Payload by Hook Type\n\n#### tool_pre_invoke (Ingress)\n\n```jsonc\n{\n  \"name\": \"tool-name\",           // Name of the tool being invoked\n  \"args\": {                      // Tool invocation arguments (arbitrary key-value pairs)\n    \"query\": \"SELECT * FROM ...\",\n    \"database\": \"prod\"\n  },\n  \"headers\": null                // HttpHeaderPayload (also extracted to top-level headers)\n}\n```\n\n#### tool_post_invoke (Egress)\n\n```jsonc\n{\n  \"name\": \"tool-name\",                          // Name of the tool that was invoked (matches the ingress payload.name)\n  \"text\": [\"result line 1\", \"result line 2\"]    // Tool output content blocks\n}\n```\n\n> **Note:** Per the MCP specification, tool output can include one or more content blocks. Each entry may be plain text, JSON, or another format — the structure is tool-specific. If there is no documentation for the tool's output format, test it using MCP Inspector or similar tooling to determine the shape before writing egress policies. JSON entries must be parsed with `json.unmarshal` before field-level inspection.\n\n#### prompt_pre_fetch (Ingress)\n\n```jsonc\n{\n  \"prompt_id\": \"greeting\",       // Prompt identifier\n  \"args\": { \"user\": \"alice\" }   // Prompt template arguments\n}\n```\n\n#### prompt_post_fetch (Egress)\n\n```jsonc\n{\n  \"text\": [\"Hello Alice, welcome back!\"]   // Rendered prompt content\n}\n```\n\n#### resource_pre_fetch (Ingress)\n\n```jsonc\n{\n  \"uri\": \"https://example.com/data/report.csv\",   // Resource URI\n  \"metadata\": {}                                    // Optional metadata\n}\n```\n\n#### resource_post_fetch (Egress)\n\n```jsonc\n{\n  \"text\": [\"file content here\"]   // Resource content\n}\n```\n\n## Examples\n\nThe following examples demonstrate common policy patterns. They use **PARC field names** (`input.resource.name`, `input.action`, `input.subject.*`); the legacy aliases (`input.payload.name`, `input.kind`, `input.user`) are **deprecated** but still populated for backwards compatibility — see Field Aliases for the mapping. All examples use Jira tool names but the patterns apply to any MCP server.\n\n> **Tool names are illustrative.** Examples use short tool names like `atlassian-getjiraissue` for readability. In practice, tool names in `input.resource.name` (or the legacy `input.payload.name`) are prefixed with the MCP server name as configured on the gateway (e.g., `atlassian-jira-mcp-getjiraissue` if the server is named `atlassian-jira-mcp`). Always use the debug technique (see Debugging Policies) to confirm exact tool names before writing policies.\n\n> **One policy, one job:** Each example below is a standalone policy that handles a single concern. To build comprehensive access control, compose multiple policies on the gateway — e.g., one policy to block direct HR issue access + a separate policy to rewrite JQL searches to exclude HR. This makes each policy independently testable and easier to reason about.\n\n> **Allowlist vs blocklist:** Allowlist policies (permit only specific tools) are more secure but require updates when new tools are added to the MCP server. Blocklist policies (deny specific tools, allow everything else) are more permissive but don't need updating for new tools. Choose based on the security posture required.\n\n### Example 1: Readonly Tool Access (Ingress)\n\nOnly allow read-only tools; deny all others with a reason.\n\n```rego\npackage jira.ingress.readonly\n\ndefault allow := false\n\nallow if {\n    lower(input.resource.name) == \"atlassian-getjiraissue\"\n}\n\nallow if {\n    lower(input.resource.name) == \"atlassian-searchjiraissuesusingjql\"\n}\n\nallow if {\n    lower(input.resource.name) == \"atlassian-getvisiblejiraprojects\"\n}\n\nreason := \"You are not allowed to modify JIRA issues. Ask your InfoSec team for access.\" if not allow\n```\n\n### Example 2: Block Access to Specific Tool Arguments (Ingress)\n\nDeny adding comments to a specific JIRA issue.\n\n```rego\npackage jira.ingress.deny_comment\n\ndefault allow := false\n\n# Allow all tool calls except the blocked one\nallow if {\n    not is_blocked_comment\n}\n\n# Block adding comments to DEV-1\nis_blocked_comment if {\n    lower(input.resource.name) == \"atlassian-addcommenttojiraissue\"\n    object.get(input.payload.args, \"issueIdOrKey\", \"\") == \"DEV-1\"\n}\n\nreasons contains \"For testing purposes, adding comments to the DEV-1 task has been disabled. Ask your InfoSec team to re-enable it.\" if {\n    is_blocked_comment\n}\n\nreason := joined if {\n    count(reasons) > 0\n    reason_list := sort([r | some r in reasons])\n    joined := concat(\"; \", reason_list)\n}\n```\n\n### Example 3: Block Access to a Forbidden Project (Ingress)\n\nDeny viewing issues belonging to specific projects.\n\n```rego\npackage jira.ingress.project_access\n\ndefault allow := false\n\n# Projects the caller is not allowed to access\nforbidden_projects := {\"HR\"}\n\n# Allow tool calls that don't target forbidden projects\nallow if {\n    lower(input.resource.name) == \"atlassian-getjiraissue\"\n    not issue_belongs_to_forbidden_project(issue_key)\n}\n\n# Allow all other tools\nallow if {\n    lower(input.resource.name) != \"atlassian-getjiraissue\"\n}\n\n# Helpers\nissue_key := upper(object.get(input.payload.args, \"issueIdOrKey\", \"\"))\n\nissue_belongs_to_forbidden_project(key) if {\n    some project in forbidden_projects\n    startswith(upper(key), concat(\"\", [project, \"-\"]))\n}\n\nreasons contains \"You are not allowed to view issues in the HR project. Ask your InfoSec team for access.\" if {\n    lower(input.resource.name) == \"atlassian-getjiraissue\"\n    issue_belongs_to_forbidden_project(issue_key)\n}\n\nreason := joined if {\n    count(reasons) > 0\n    reason_list := sort([r | some r in reasons])\n    joined := concat(\"; \", reason_list)\n}\n```\n\n> **Note:** This policy only blocks direct issue fetches by key. To fully restrict project access, add a **separate** policy to guard `searchjiraissuesusingjql` (see Example 8 for a JQL rewriting approach). Keep them as independent policies rather than combining them — this makes each one easier to test and debug.\n\n### Example 4: Limit Editable Fields (Ingress)\n\nAllow editing only specific fields; deny changes to any others.\n\n```rego\npackage jira.ingress.limited_editing\n\ndefault allow := false\n\n# Fields that are allowed to be edited\nallowed_fields := {\n    \"description\",\n    \"labels\",\n    \"priority\",\n    \"environment\",\n    \"comment\"\n}\n\n# Allow non-edit tools\nallow if {\n    lower(input.resource.name) != \"atlassian-editjiraissue\"\n}\n\n# Allow edits that only touch permitted fields\nallow if {\n    input.action == \"tool_pre_invoke\"\n    lower(input.resource.name) == \"atlassian-editjiraissue\"\n    count(disallowed_fields) == 0\n}\n\n# Extract the fields being edited in the request\nedited_fields := {k |\n    fields := object.get(input.payload.args, \"fields\", {})\n    k := object.keys(fields)[_]\n}\n\n# Collect ALL disallowed fields as a set. This must be a set comprehension, not a\n# complete rule (`disallowed_field := f if { f := edited_fields[_]; ... }`): a\n# complete rule assigns a single value, so editing two disallowed fields makes it\n# derive two values and OPA raises eval_conflict_error instead of denying cleanly.\ndisallowed_fields := {f |\n    f := edited_fields[_]\n    not allowed_fields[f]\n}\n\nreasons contains msg if {\n    input.action == \"tool_pre_invoke\"\n    lower(input.resource.name) == \"atlassian-editjiraissue\"\n    f := disallowed_fields[_]\n    msg := sprintf(\"Editing the field '%s' is not allowed. Only description, labels, priority, environment, and comment may be edited.\", [f])\n}\n\nreason := joined if {\n    count(reasons) > 0\n    reason_list := sort([r | some r in reasons])\n    joined := concat(\"; \", reason_list)\n}\n```\n\n### Example 5: Block Egress Containing Confidential Labels (Egress)\n\nBlock responses that contain issues with the \"confidential\" label.\n\n```rego\npackage jira.egress.deny_confidential\n\ndefault allow := false\n\n# Allow responses without confidential content\nallow if {\n    not has_confidential_label\n}\n\nhas_confidential_label if {\n    some text in input.payload.text\n    parsed := json.unmarshal(text)\n    fields := object.get(parsed, \"fields\", {})\n    labels := object.get(fields, \"labels\", [])\n    some label in labels\n    lower(label) == \"confidential\"\n}\n\nreasons contains \"You are not allowed to view issues with the label 'confidential'. Ask your InfoSec team for access.\" if {\n    has_confidential_label\n}\n\nreason := joined if {\n    count(reasons) > 0\n    reason_list := sort([r | some r in reasons])\n    joined := concat(\"; \", reason_list)\n}\n```\n\n### Example 6: PII Redaction (Egress)\n\nAllow all responses but redact PII patterns and sensitive fields. Note that `redact_fields` only operates on structured JSON field names — to catch plain-text occurrences like `password: hunter2`, use `redact_patterns` with a regex (see the last two patterns below).\n\n```rego\n# Package name omits the tool segment because this policy is not tool-specific —\n# it applies PII redaction to every egress response. See Core Rules for the convention.\npackage egress.pii_redaction\n\n# Transform-only policy — never denies, only redacts sensitive data\ndefault allow := true\n\ntransform := {\n    \"redact_patterns\": [\n        \"\\\\d{3}-\\\\d{2}-\\\\d{4}\",\n        \"\\\\d{4}[- ]?\\\\d{4}[- ]?\\\\d{4}[- ]?\\\\d{4}\",\n        \"[\\\\w.-]+@[\\\\w.-]+\\\\.[\\\\w.-]+\",\n        \"\\\\+?1?[- .]?\\\\(?\\\\d{3}\\\\)?[- .]?\\\\d{3}[- .]?\\\\d{4}\",\n        \"AKIA[0-9A-Z]{16}\",\n        \"(?i)(?:api[_-]?key|apikey|secret[_-]?key)\\\\s*[:=]\\\\s*\\\\S+\",\n        \"(?i)(?:password|secret|token|credentials)\\\\s*[:=]\\\\s*\\\\S+\"\n    ],\n    \"redact_fields\": [\"password\", \"secret\", \"api_key\", \"token\"],\n    \"replacement\": \"[REDACTED]\",\n}\n```\n\n### Example 7: Tool-Scoped Egress Transform (Egress)\n\nApply a transform only to a specific tool's output. This example redacts profanity only from the echo tool's responses.\n\n```rego\npackage echo.egress.profanity_filter\n\n# Transform-only policy — never denies, only redacts profanity\ndefault allow := true\n\ntransform := {\n    \"redact_patterns\": [\n        \"(?i)\\\\b(?:damn|shit|fuck|ass|bitch|bastard|crap|hell|dick|piss)\\\\b\",\n        \"(?i)\\\\b(?:fucking|shitting|asshole|bullshit|dumbass|dickhead|motherfucker)\\\\b\"\n    ],\n    \"replacement\": \"[PROFANITY]\",\n} if {\n    input.mode == \"output\"\n    lower(input.resource.name) == \"echo-echo\"\n}\n```\n\n> **Note:** When a tool-scoped transform's condition does not match (e.g., a non-echo tool call), the `transform` rule is undefined and the aggregator silently skips this policy for that request. Other transforms attached to the same pipeline direction still apply — the chain composes whichever transforms are defined for the current request (see Transform Composition).\n\n### Example 8: Ingress Transform — Rewrite Search Query (Ingress)\n\nTransform tool arguments before they reach the MCP server. This example rewrites JQL queries to exclude a forbidden project.\n\n```rego\npackage jira.ingress.hr_search\n\n# Transform-only policy — never denies, just rewrites JQL\ndefault allow := true\n\n# Rewrite the JQL to exclude the HR project\ntransform := {\n    \"transformed_payload\": object.union(\n        input.payload.args,\n        {\"jql\": new_jql}\n    )\n} if {\n    input.action == \"tool_pre_invoke\"\n    lower(input.resource.name) == \"atlassian-searchjiraissuesusingjql\"\n    original_jql := object.get(input.payload.args, \"jql\", \"\")\n    new_jql := build_jql(original_jql)\n}\n\n# Find the position of \"order by\" — check both mid-string (\" order by \") and start-of-string (\"order by \")\norder_by_idx(jql) := idx if {\n    lower_jql := lower(jql)\n    idx := indexof(lower_jql, \" order by \")\n    idx >= 0\n}\n\norder_by_idx(jql) := 0 if {\n    lower_jql := lower(jql)\n    indexof(lower_jql, \" order by \") == -1\n    startswith(lower_jql, \"order by \")\n}\n\n# Build JQL with HR exclusion — filter + ORDER BY\nbuild_jql(original_jql) := new_jql if {\n    idx := order_by_idx(original_jql)\n    filter_part := trim_space(substring(original_jql, 0, idx))\n    order_part := trim_space(substring(original_jql, idx, count(original_jql) - idx))\n    filter_part != \"\"\n    new_jql := sprintf(\"project != HR AND (%s) %s\", [filter_part, order_part])\n}\n\n# Build JQL with HR exclusion — ORDER BY only, no filter\nbuild_jql(original_jql) := new_jql if {\n    idx := order_by_idx(original_jql)\n    filter_part := trim_space(substring(original_jql, 0, idx))\n    order_part := trim_space(substring(original_jql, idx, count(original_jql) - idx))\n    filter_part == \"\"\n    new_jql := sprintf(\"project != HR %s\", [order_part])\n}\n\n# Build JQL with HR exclusion — filter only, no ORDER BY (no order_by_idx match means no ORDER BY)\nbuild_jql(original_jql) := new_jql if {\n    not order_by_idx(original_jql)\n    filter_part := trim_space(original_jql)\n    filter_part != \"\"\n    new_jql := sprintf(\"project != HR AND (%s)\", [filter_part])\n}\n\n# Build JQL with HR exclusion — empty query\nbuild_jql(original_jql) := \"project != HR\" if {\n    not order_by_idx(original_jql)\n    trim_space(original_jql) == \"\"\n}\n```\n\n### Example 9: Tenant-Scoped Access by JWT Claim (Ingress)\n\nAllow a specific tool only when the caller's IdP-issued `org_id` claim is in an allowlist. Demonstrates reading `input.subject.claims` for authorization while leaving other tools unaffected.\n\n```rego\npackage jira.ingress.org_scoped\n\ndefault allow := false\n\n# Orgs allowed to call atlassian-getjiraissue — typically populated from IdP claims\n# like Auth0's `org_id` or a custom-namespaced claim such as `https://acme.com/tenant_id`.\nallowed_orgs := {\n    \"org_g6zdgXkQGLlQPa37\",\n    \"org_h7ahxYrLHMmRPbQR\",\n}\n\n# Pass through any tool other than the one we're gating\nallow if {\n    lower(input.resource.name) != \"atlassian-getjiraissue\"\n}\n\n# Allow the gated tool only when the caller's org_id is on the list\nallow if {\n    lower(input.resource.name) == \"atlassian-getjiraissue\"\n    allowed_orgs[object.get(input.subject.claims, \"org_id\", \"\")]\n}\n\nreason := sprintf(\n    \"atlassian-getjiraissue is restricted to specific orgs. Your org_id is %v.\",\n    [object.get(input.subject.claims, \"org_id\", \"<not set>\")],\n) if {\n    lower(input.resource.name) == \"atlassian-getjiraissue\"\n    not allowed_orgs[object.get(input.subject.claims, \"org_id\", \"\")]\n}\n```\n\nNotes:\n\n- Use `object.get(input.subject.claims, \"<claim>\", \"<default>\")` for claim access. Direct access (`input.subject.claims.org_id`) silently fails if the claim isn't present, which makes the entire rule body fail to match — easy to mistake for a different bug.\n- The default value matters. `object.get(..., \"\")` ensures the membership check `allowed_orgs[\"\"]` is false (the empty string is not in the set), so a missing claim deterministically denies. If you used a default like `null` or omitted the default entirely, you'd get a \"rule body failed to match\" silently rather than a clean deny + reason.\n- The exact claim names available depend on the IdP — Auth0 uses `org_id`, Okta might use `tenant`, custom IdPs might emit namespaced claims like `https://acme.com/tenant_id`. See Identity (Subject and Claims) for guidance on discovering the actual claim shape for your gateway.\n\n## Policy Composition\n\nMultiple policies are composed on the gateway through an **aggregator policy** that references each step policy by its package path. Understanding this aggregation is critical — package path mismatches are a common source of blanket denies.\n\n### How It Works\n\nEach step policy (e.g., `ingress_step_0.rego`) declares its own package and evaluates `allow`, `reasons`, and `transform` independently. An aggregator policy (e.g., `ingress_policy.rego`) combines them:\n\n```rego\npackage dtwo.ingress\n\ndefault allow := false\n\n# Both step policies must allow for the request to proceed\nallow if {\n    data.jira.ingress.readonly.allow\n    data.jira.ingress.hr_search.allow\n}\n\n# Collect transforms from each step policy\ntransform := data.jira.ingress.readonly.transform\ntransform := data.jira.ingress.hr_search.transform\n\n# Collect reasons from each step policy\nreasons contains reason if {\n    some reason in data.jira.ingress.readonly.reasons\n}\n\nreasons contains reason if {\n    some reason in data.jira.ingress.hr_search.reasons\n}\n```\n\n### Key Rules\n\n- The `data.<package-path>.allow` reference must **exactly match** the step policy's `package` declaration. If the step policy declares `package jira.ingress.readonly` but the aggregator references `data.jira.readonly.allow`, the value is `undefined` and the aggregator's `default allow := false` takes effect — denying everything.\n- When the aggregator ANDs multiple step policies (`allow if { policy_a.allow; policy_b.allow }`), **all** must evaluate to `true`. If any step policy's package path is wrong, its `allow` is `undefined`, and the AND fails.\n- Transform-only step policies should use `default allow := true` so they don't block requests when their transform doesn't apply.\n\n## Session State & Markers\n\nBeyond allow/deny/transform, a policy can **write to session state** and other policies can **read it** — giving the gateway a shared, tenant- and user-scoped, TTL-bounded \"notepad\" that survives across tool calls and across upstream MCP servers. The main use is **markers**: session-state flags one policy stamps and another gates on. A marker written during a Slack egress call is visible during a later Jira ingress call for the same user, because markers are scoped by tenant and user (not by server) and persist until their TTL expires.\n\nThis lets you compose small single-purpose policies that signal to each other without shared code, instead of one giant policy that observes everything:\n\n- **Writer policy** — inspects the current call (arguments, response text, identity, whatever) and stamps a marker when a condition is met.\n- **Reader policy** — checks whether a marker is set and allows/denies/transforms accordingly. The writer and reader can attach to different tools, different directions, and different upstream servers.\n\nTo the person in the session, the marker together with its writer and reader is one **safeguard**: use that word in anything they read (deny reasons, the marker's display name and description) and keep \"marker\" for Rego, the registry and the admin. One marker is read by one reader policy, and one reader gates one tool or action — a trigger that should restrict several things writes one marker per restricted tool (see One trigger, several restrictions below), so each can be disabled on its own.\n\nStart with the simplest shape — a **boolean flag** whose *presence* is the whole signal (the PII example below). Value-carrying markers (counters, structured payloads) are more advanced and rarely needed; a self-incrementing counter, for instance, has to read its own prior value and re-emit every call, which keeps refreshing the TTL.\n\nRegistering the marker vocabulary, attaching the `writableKeySchema`, and deploying are lifecycle operations owned by the companion `dtwo-gateway-policy` instructions (Managing Markers). This section covers only the **Rego**. Two numbers in that lifecycle are the user's to give, not yours to pick: the TTL (`minimumTtlSeconds` on the marker, `ttlSeconds` on the writer's schema) and whether the marker is `clearable`. If nobody has asked the user yet, ask before you write the schema.\n\n### Marker vs. general session key\n\n`session_writes` can write two flavors of key. Both are the same underlying `session_state_kv` mechanism — same `(tenant, subject, writer_id, key)` scoping, same TTL-from-schema, same read path — so the choice is about **design intent and governance**, not capability:\n\n| | **Marker** (`marker:<namespace>:<id>`) | **General session key** (bare name, e.g. `pipeline_stage`) |\n|---|---|---|\n| Intended for | A **shared, named signal across policies** and a general session-wide indicator — one policy stamps it, *other* policies (different tools/directions/servers) gate on it. | State **targeted to a specific use, isolated to one policy or a coordinated ingress/egress set** — private working state, not a broadcast signal. |\n| Registry | **Required** — register with `dtwo-create-marker`; the deploy validator rejects an unregistered marker key. | **None** — bare keys need no registry entry. |\n| Governance | Discoverable via `dtwo-list-markers`, carries tags + a `minimumTtlSeconds` floor, and (when the intent tools are enabled) can participate in intent/marker compatibility rules. | No registry, tags, TTL floor, or compatibility hooks — lighter-weight, ungoverned. |\n| Declare in `writableKeySchema` | `name: \"marker:<ns>:<id>\"`, add `\"x-d2-is-marker\": true` to the `jsonSchema`. | `name: \"<bare-key>\"`, omit the `marker:` prefix and `x-d2-is-marker`. |\n\n**Rule of thumb:** if another, separate policy is meant to read the signal — or you want it registered, discoverable, and governed — use a **marker**. If the state only coordinates within your own policy or your own ingress/egress pair and doesn't belong in a shared vocabulary, a **general session key** is the lighter choice.\n\n**Two honesty caveats:**\n\n- **Neither is access-isolated.** \"Isolated to a policy\" is a *design convention*, not an enforcement boundary — any policy in the session can read any key (marker or bare) via `session.policies[writer_uid][key]` if it knows the key. Don't treat a bare key as private/secret storage.\n- **The bare keyspace isn't namespaced.** Two unrelated policies that pick the same bare key name will collide (each writes under its own `writer_id`, but a walk-all-writers read sees both). Markers avoid this by construction via `marker:<namespace>:<id>`. Pick distinctive bare-key names, or use a marker when you need a collision-safe, shared name.\n\n### Writing a marker (`session_writes`)\n\nA writer emits `session_writes[\"marker:<namespace>:<id>\"] := <value>` when its trigger fires. The canonical shape:\n\n- **The value is stored verbatim — there is no envelope.** The object you assign *is* what's persisted for that key. The `writableKeySchema` entry's `jsonSchema` validates that object **at its top level** — it describes the value object directly, not a nested `value`/`data`/`payload` wrapper. So your object's keys must be exactly the properties the schema declares (typically a couple of flat fields like `marked_at` + `source_action`).\n- **The key must be declared** in the policy's `writableKeySchema`, or the gateway drops the write.\n- **TTL comes from the schema, never the value.** The entry's `ttlSeconds` is applied by the gateway as the key's expiry when the write lands; it is metadata attached to the key at runtime, not a field of the value, and there is no way to set expiry from within the Rego.\n\n```rego\npackage acme.egress.pii_detector\n\nimport future.keywords.if\nimport future.keywords.in\n\ndefault allow := true  # writer only observes and stamps; it does not deny\n\n_email_pattern := `[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}`\n\n_pii_email_found if {\n    some text in input.payload.text\n    is_string(text)\n    regex.match(_email_pattern, text)\n}\n\n# Stamp the marker when PII is observed in the response. `marked_at` is what\n# the reader turns into the time remaining it shows the person.\nsession_writes[\"marker:acme:no_slack_after_pii\"] := marker_value if {\n    _pii_email_found\n    marker_value := {\n        \"marked_at\": time.now_ns(),\n        \"source_action\": input.resource.name,\n    }\n}\n```\n\nA writer is usually a `default allow := true` policy — it observes and stamps, it does not block. (A single policy *can* both deny and write, but prefer separate concerns.)\n\n**One trigger, several restrictions.** When the same event should restrict more than one thing, the writer emits one key per restriction — the same value, one `session_writes` rule each — and declares every key in its `writableKeySchema` (a write to an undeclared key is dropped; the two-entry JSON under Markers that grant → One read, two markers shows the shape). Each key has its own reader policy, so the person can get one restriction disabled while the others stand. Do not collapse this into one reader that gates a set of tools on one key: that reads as tidier Rego, but it means the person can only get all of those tools back at once. One restricted tool, one marker, one reader:\n\n```rego\n_value := {\"marked_at\": time.now_ns(), \"source_action\": input.resource.name}\n\nsession_writes[\"marker:acme:no_slack_after_pii\"] := _value if { _pii_email_found }\nsession_writes[\"marker:acme:no_email_after_pii\"] := _value if { _pii_email_found }\n```\n\n**The write only happens when the trigger matches.** The `if { ... }` body gates the write like any other rule, so it uses the same request-matching as the rest of this skill: compare tool names case-insensitively (`lower(input.resource.name) == \"<server>-<tool>\"`, with the server-name prefix), read args via `object.get(input.payload.args, ...)`, and inspect response content via `input.payload.text` on egress. A writer whose trigger never matches (wrong case, missing server prefix, wrong direction) stamps nothing — and there's no error, just an absent marker. Confirm the exact tool name and payload shape with the dump-input technique (see Debugging Policies) before relying on the trigger.\n\n**Silent-drop trap.** Because the schema is strict (`additionalProperties: false`), slipping any undeclared field into the value fails validation — most commonly a `ttl`/`ttlSeconds`, which belongs on the schema (per the rule above), not the value. With the default `onDrop: \"drop\"` that failure is **silent**: the marker never lands and readers never see it. If a marker mysteriously isn't being read, check the written value against the schema first.\n\n```rego\n# WRONG — `ttl_seconds` is not a declared schema field, so the entire write silently drops\nsession_writes[\"marker:acme:jira_access\"] := {\n    \"marked_at\": time.now_ns(),\n    \"source_action\": input.resource.name,\n    \"ttl_seconds\": 3600,   # ← remove; TTL belongs on the writableKeySchema, not the value\n}\n\n# RIGHT — value carries only the declared fields; TTL is configured on writableKeySchema\nsession_writes[\"marker:acme:jira_access\"] := {\n    \"marked_at\": time.now_ns(),\n    \"source_action\": input.resource.name,\n}\n```\n\n### Reading a marker\n\nActive session state is exposed to a policy at `input.context.session.policies`, shaped as `policies[<writer_uid>][<key>] = <value>` — an outer object keyed by the UID of the policy that wrote each key, and under each writer the keys it wrote (a marker key `marker:<ns>:<id>` maps to the object the writer emitted). A marker is stored under the **writer policy's UID**, so the read walks all writer slots and treats the key as truthy if any writer set it.\n\nA reader does two jobs: the gate (deny while the marker is present) and the deny reason the person reads. The reason says what triggered the restriction, how long it has left, and whether they can ask to have it disabled. The writer's `marked_at` supplies the clock; the registry (`data.dtwo.intent_registry`, see Reading the registry) supplies the TTL and the `clearable` flag; `data.dtwo.lib.intent_match.clearing_armed` says whether disabling exists on this gateway at all:\n\n```rego\npackage acme.ingress.pii_gate\n\nimport future.keywords.if\nimport future.keywords.in\n\ndefault allow := true\n\n_key := \"marker:acme:no_slack_after_pii\"\n\n_active if {\n    some writer_uid\n    input.context.session.policies[writer_uid][_key]\n}\n\n# Registry lookups. Each has a default, so an unregistered key or an older\n# bundle never leaves `reason` undefined (the call would deny with no message).\ndefault _ttl_seconds := 3600  # keep equal to the registered minimumTtlSeconds\n\n_ttl_seconds := m.minimum_ttl_seconds if {\n    some m in data.dtwo.intent_registry.markers\n    m.id == _key\n}\n\n# Offer disabling only when the marker is clearable AND clearing is armed on this gateway.\ndefault _can_disable := false\n\n_can_disable if {\n    some m in data.dtwo.intent_registry.markers\n    m.id == _key\n    m.clearable\n    data.dtwo.lib.intent_match.clearing_armed\n}\n\n# Newest write across writers: every write restarts the TTL, so it is the clock's\n# anchor. Tolerate values other writers may have left under the key.\n_marked_at := max([t |\n    some writer_uid\n    v := input.context.session.policies[writer_uid][_key]\n    is_object(v)\n    t := object.get(v, \"marked_at\", 0)\n    is_number(t)\n    t > 0\n])\n\n_minutes_left := ceil(max([_ttl_seconds - ((time.now_ns() - _marked_at) / 1000000000), 0]) / 60)\n\ndefault _remaining := \"It lifts when this safeguard expires.\"\n\n_remaining := sprintf(\"Time remaining: %v minutes.\", [_minutes_left]) if { _minutes_left }\n\ndefault _exit := \"This safeguard cannot be disabled early.\"\n\n_exit := \"You can ask to have this safeguard disabled.\" if { _can_disable }\n\nallow := false if {\n    lower(input.resource.name) == \"slack-mcp-slack-send-message\"\n    _active\n}\n\nreason := sprintf(\"Posting to Slack is blocked because PII was seen in this session. %s %s\", [_remaining, _exit]) if {\n    lower(input.resource.name) == \"slack-mcp-slack-send-message\"\n    _active\n}\n```\n\n- The walk-all-writers pattern (`some writer_uid; input.context.session.policies[writer_uid][key]`) is \"present under *any* writer is truthy.\" To trust only a specific writer, filter on `writer_uid == \"<known-uid>\"`.\n- **This pattern is for reading *marker* keys only.** Do **not** use it — or any direct `input.context.session.policies` read — to read the platform **intent** (see Intent-capture policies → Reading the session intent). \"Present under any writer\" is exactly wrong for intent: a tenant policy could stamp an intent-shaped value under its own writer slot and a walk-all-writers read would honour it, spoofing the session intent. Read intent only through the platform helper, which is pinned to the trusted intent-capture slot.\n- **Deny reasons are user-visible — say three things, in this order.** *What triggered it*, *the time remaining*, *the exit*: \"Posting to Slack is blocked because PII was seen in this session. Time remaining: 42 minutes. You can ask to have this safeguard disabled.\" The person knows a marker as a **safeguard**, so the reason says \"safeguard\", never \"marker\", and names no tool, claim or key.\n- **What triggered it** is the restriction and its cause in the person's words. The registered `description` is written to be exactly this sentence, so you can take it from the registry instead of typing it (see Reading the registry); then the deny reason and the disable page say the same thing.\n- **Time remaining is derived, not read.** A policy sees only the marker's value — not when it was written or when it expires. So the writer stamps `marked_at` (`time.now_ns()`, kept an integer) and the reader subtracts it from now and from the registered `minimum_ttl_seconds` — which is why the writer's `ttlSeconds` must equal that registry value. Take the newest `marked_at` across writers: every write restarts the TTL. When the value carries no `marked_at` (a writer you don't own, a hand-written value), fall back to \"it lifts when this safeguard expires\" rather than guessing, and never hard-code the TTL in the reader: it drifts from the registry.\n- **Offer disabling only where it exists.** Say \"you can ask to have this safeguard disabled\" only when the registry entry is `clearable` **and** `data.dtwo.lib.intent_match.clearing_armed` is true — clearing is armed per gateway, and where it is not, the disable tool is missing from the agent's tool list or answers with a \"not configured on this gateway\" refusal, so the sentence would promise something the person cannot get. Otherwise say the safeguard cannot be disabled early; the time remaining is then the whole answer. The helper is defined in every current bundle; on an older bundle it is undefined, which the `default` handles (conservatively: no offer). Word it as something the person asks for — their agent starts it with the platform `disable_safeguards` tool, and someone reading the reason in a log or the Hub has nothing to click. Never offer disabling as a way around the decision: the person approves it in a browser precisely so an agent cannot shrug off a block (see `dtwo-gateway-policy` → Clearing a marker).\n- **Avoid \"start a new session\"** — marker state is scoped to tenant + user and survives reconnecting, so a new session for the same user won't clear it.\n- **Never build a reason out of the session intent.** A reason may say *that* the current intent failed a gate; it must not carry the intent itself — do not interpolate `current_intent(input)` or its `description` into `reason` or into a transform. Name the rule that fired instead. Full rule under Intent-capture policies → Reading the session intent.\n\n### Reading the registry (`data.dtwo.intent_registry`)\n\nThe marker (and, where enabled, intent) vocabulary is shipped into every gateway's policy bundle as OPA base data at `data.dtwo.intent_registry`, in the same atomic deploy as the Rego — so a policy can consult the registry at decision time instead of hard-coding what it knows about a key. The document is always defined and always fully shaped (empty arrays for an empty tenant), so a read needs no \"registry missing\" branch; a *specific* entry can of course be absent.\n\nThe reader under **Reading a marker** already consults the registry for `minimum_ttl_seconds` and `clearable`. The same lookup can supply the first sentence of the reason, so the deny reason and the disable page say the same thing — the registered `description` is written for exactly that (see `dtwo-gateway-policy` → Registering a marker):\n\n```rego\n# Registered description as the first sentence. The `default` is load-bearing:\n# without it an unregistered key leaves the whole `reason` undefined.\ndefault _what := \"Posting to Slack is blocked because PII was seen in this session.\"\n\n_what := m.description if {\n    some m in data.dtwo.intent_registry.markers\n    m.id == _key\n}\n\nreason := sprintf(\"%s %s %s\", [_what, _remaining, _exit]) if {\n    lower(input.resource.name) == \"slack-mcp-slack-send-message\"\n    _active\n}\n```\n\n- Entries are keyed by **FQID** (`id`) — `marker:<ns>:<id>` for markers, `<ns>:<name>` for intents. No UIDs appear in the data document.\n- `markers[]` carries `id`, `description`, `minimum_ttl_seconds` (what the reader's time remaining is computed against), `clearable` (`false`: the human-approved clear never offers it; see Reading a marker) and, when set, `display_name`; `intents[]` carries `id`, `description`, and optionally `aliases` / `transitions_to` / `transitions_from`; `compatibility[]` carries `intent` and `excluded_marker`. A transitions field is **omitted when unrestricted** and `[]` when locked — treat missing as \"no restriction\".\n- Registry text is authored by your own admins, so it is safe to surface in a reason — unlike the session intent, which must never be echoed (see Reading the session intent).\n- **Give any registry-derived string a fallback** — the `default` line above is not decoration. A lookup that finds nothing is *undefined*, not empty, and an undefined term makes the whole `reason` undefined: the call still denies, but the person sees no message at all. A `default` on the lookup rule fixes it, as does a second `reason` rule that omits the lookup.\n- Registry edits reach the gateway on its **next policy deploy**, not immediately.\n\n### Markers that grant (the allow direction)\n\nEvery marker example above **takes a capability away**: something happened, so something is\nnow blocked. A marker can just as well **give one** — the tool is off by default and a\nmarker turns it on, so the agent *earns* access by doing the right thing first instead of\nholding a standing privilege. \"You may not comment on a ticket you have not read\" and \"you\nmay not delete a file you have not copied\" are the same shape.\n\nThe mechanism is identical. Four things change, and the first is a security property rather\nthan a style preference.\n\n**Pin the writer's UID — do not walk all writers.** The walk-all-writers read is correct for\na deny marker: more emitters can only make the gate more cautious. Invert the marker and it\ninverts too — *any* policy that can write that key now mints the grant. As the caveat under\n**Marker vs. general session key** says, session state is not access-isolated, so a marker\nthat unlocks something makes its writer an authorization decision point:\n\n```rego\n# Deny direction — \"did anyone see PII?\" Any writer may answer.\n_active if {\n    some writer_uid\n    input.context.session.policies[writer_uid][\"marker:acme:no_slack_after_pii\"]\n}\n\n# Allow direction — \"did THE reviewer policy record this?\" Exactly one writer may answer.\n_reviewed_keys := object.get(\n    object.get(object.get(input.context.session, \"policies\", {}), _writer_uid, {}),\n    [\"marker:acme:issue_read\", \"issue_keys\"],\n    [],\n)\n```\n\n**The gate now denies on absence, so read fail-closed.** *Marker Rego gotchas* below says to\nstructure gates so the marker's **presence** denies — that is the deny direction. A grant\ngate is the mirror image: absent state must mean *no grant*, and therefore deny. Reach every\nfield through nested `object.get` with defaults so a missing session, a missing writer slot\nor an absent `args` object all resolve to \"not granted\" rather than leaving the rule\nundefined.\n\n**Scope it to the resource, and put the id in the value.** A grant is rarely \"you may\ncomment\"; it is \"you may comment *on this issue*\". The id cannot go in the key — a\n`writableKeySchema` enumerates key names under `additionalProperties: false`, so a\nper-resource key is impossible. Carry it in the **value** and compare against the argument of\nthe call being judged:\n\n```rego\npackage acme.ingress.comment_requires_read\n\nimport future.keywords.if\nimport future.keywords.in\n\n# Allow broadly, deny the one narrow case — never `default allow := false` on a\n# gateway that also fronts management tools.\ndefault allow := true\n\n# The paired writer policy's UID. Replace after creating that policy; while the\n# placeholder stands no slot matches, so every comment denies — an unconfigured\n# pair fails closed and says so.\n_writer_uid := \"REPLACE-WITH-WRITER-POLICY-UID\"\n\n_reviewed_keys := object.get(\n    object.get(object.get(input.context.session, \"policies\", {}), _writer_uid, {}),\n    [\"marker:acme:issue_read\", \"issue_keys\"],\n    [],\n)\n\n_requested := object.get(object.get(input.payload, \"args\", {}), \"issueIdOrKey\", \"\")\n\n_has_read if {\n    is_string(_requested)\n    _requested != \"\"\n    _requested in _reviewed_keys\n}\n\nallow := false if {\n    lower(input.resource.name) == \"atlassian-addcommenttojiraissue\"\n    not _has_read\n}\n\nreason := \"Commenting on an issue requires that this session has read that same issue first. Read it, then retry; reading a different issue does not unlock this one.\" if {\n    lower(input.resource.name) == \"atlassian-addcommenttojiraissue\"\n    not _has_read\n}\n```\n\n**Take the id from the response, not the request.** Write the marker on **egress**. A\n`tool_post_invoke` payload is `{name, text}` and carries **no arguments**, which sounds like\na limitation and is the point: the id comes from what the upstream actually returned, so a\ncaller cannot mark a resource it never fetched, and a call that failed upstream grants\nnothing. This does require a tool whose response names its resource — a Jira issue and a\nDrive file's metadata both do; a raw content read may not, in which case the grant cannot be\nresource-scoped on that tool.\n\n#### Accumulating across calls\n\nA grant marker usually holds a *set* — every issue read so far. The writer reads its own\nprior value and writes the extended list, so it needs **its own UID**:\n\n```rego\npackage acme.egress.issue_read_writer\n\nimport future.keywords.if\nimport future.keywords.in\n\ndefault allow := true\n\n# THIS policy's own UID — session writes are keyed by writer, so accumulating\n# means reading back at our own slot. Two-step: create, then update (see below).\n_self_uid := \"REPLACE-WITH-THIS-POLICY-UID\"\n\n# Bind the whole response object, then derive from it — other rules below\n# need more than the id.\n_issue := obj if {\n    lower(input.resource.name) == \"atlassian-getjiraissue\"\n    some text in input.payload.text\n    obj := json.unmarshal(text)\n    is_string(obj.key)\n}\n\n# The id comes from the response body, never from the caller's arguments.\n_key := _issue.key\n\n_slot  := object.get(object.get(input.context.session, \"policies\", {}), _self_uid, {})\n_prior := [x | some x in object.get(_slot, [\"marker:acme:issue_read\", \"issue_keys\"], []); is_string(x)]\n\n# Deduplicate and keep the value bounded — see the cap below.\n_deduped := sort({k | some k in array.concat(_prior, [_key])})\n_keys    := array.slice(_deduped, max([0, count(_deduped) - 12]), count(_deduped))\n\nsession_writes[\"marker:acme:issue_read\"] := {\"issue_keys\": _keys} if { _key }\n```\n\nThree things that trip people up here:\n\n- **A policy cannot know its own UID until it exists.** Create it with the placeholder, take\n  the UID from the `dtwo-add-policy` response, then `dtwo-update-policy` with the real value.\n  The shipped intent-capture policies use exactly this two-step.\n- **Writes apply *after* the evaluation that emitted them.** A policy never sees the write it\n  is currently making, so it cannot read-then-write a value in one decision. It *does* see\n  writes committed by **earlier evaluations of the same request** — an earlier pipeline step,\n  or ingress when the read happens on egress — as well as everything from previous requests.\n  That is what makes \"read A, read B, then act on A\" work, and what lets an ingress step mark\n  a call that a later step gates on.\n- **Keep the value bounded.** A value is capped at **1 KB**, one decision may write at most\n  **16 keys**, and a session holds at most **64 keys** (and 16 KB in total). That is why the\n  list above dedupes and keeps only the most recent 12. An oversized value is rejected as\n  `VALUE_TOO_LARGE`, and because that code honours `onDrop`, a writer declaring\n  `\"deny_request\"` will **deny the tool call** rather than quietly skip the write.\n\n#### One read, two markers — opposite directions\n\nNothing says a policy writes only one key. A single writer can emit several, and the\ninteresting case is emitting a **grant and a restriction from the same event**, because that\nis usually what the event means: reading a confidential ticket both proves you have read it\n(so you may comment on it) and puts sensitive content in the session (so you may not post it\noutbound). Same fact, two gates, pointing opposite ways.\n\nExtending the writer above with a second key, conditional on the response content:\n\n```rego\n_labels := [lower(l) |\n    some l in object.get(_issue, [\"fields\", \"labels\"], [])\n    is_string(l)\n]\n\n# GRANT — the same rule as above, repeated so the two sit side by side.\nsession_writes[\"marker:acme:issue_read\"] := {\"issue_keys\": _keys} if { _key }\n\n# RESTRICTION — only when the issue carries the `confidential` label. The value\n# carries the key so a downstream deny can name what caused it.\nsession_writes[\"marker:acme:confidential_seen\"] := {\"issue_key\": _key} if {\n    _key\n    \"confidential\" in _labels\n}\n```\n\nDeclare **both** keys in the policy's `writableKeySchema` — a write to an undeclared key is\ndropped, so a schema listing only the first would silently lose the second:\n\n```json\n[\n  {\"name\": \"marker:acme:issue_read\",\n   \"jsonSchema\": \"{\\\"type\\\":\\\"object\\\",\\\"properties\\\":{\\\"issue_keys\\\":{\\\"type\\\":\\\"array\\\",\\\"items\\\":{\\\"type\\\":\\\"string\\\"},\\\"maxItems\\\":12}},\\\"required\\\":[\\\"issue_keys\\\"],\\\"additionalProperties\\\":false}\",\n   \"ttlSeconds\": 900, \"onDrop\": \"deny_request\"},\n  {\"name\": \"marker:acme:confidential_seen\",\n   \"jsonSchema\": \"{\\\"type\\\":\\\"object\\\",\\\"properties\\\":{\\\"issue_key\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"issue_key\\\"],\\\"additionalProperties\\\":false}\",\n   \"ttlSeconds\": 900, \"onDrop\": \"deny_request\"}\n]\n```\n\nTwo notes on doing this deliberately rather than by accident:\n\n- **The two keys are read by different policies, with different trust needs.** The grant is\n  read with its writer **pinned** (above); the restriction can be read with the any-writer\n  walk, since extra emitters only make it more cautious. One writer, two readers, two\n  different read idioms.\n- **Both keys count against the per-decision and per-session caps**, and each carries its own\n  TTL. Give the restriction a TTL at least as long as the grant if a downstream policy\n  assumes both are present together — otherwise the restriction can expire first and leave a\n  grant standing on its own.\n\n#### What this does not give you\n\nA grant gate is not a single-use token. Two calls issued in parallel are both evaluated\nagainst the state left by earlier evaluations, so both can be allowed before either write\nlands. Recording \"already used\" in a marker makes the record correct, not the gate exclusive.\nTreat a grant as **single-use for sequential calls** and say so plainly rather than implying\nexactly-once.\n\n### `writableKeySchema` (attached via `dtwo-add-policy` / `dtwo-update-policy`)\n\nThe Rego emits the write; the `writableKeySchema` on the policy record tells the gateway what shape the write must have. It is set through the lifecycle tools (see `dtwo-gateway-policy`), not inside the Rego, but the Rego author owns getting the value shape right. Each entry has `name` (the marker key, matching the registry exactly), `jsonSchema` (a stringified JSON object — a JSON Schema — for the value), `ttlSeconds` (should be ≥ the marker's registered `minimumTtlSeconds` — not enforced yet, so keep them in sync manually), and `onDrop` (`\"drop\"` — silently drop a schema-failing write; `\"deny_request\"` — hard-deny the tool call).\n\nMarker-key *shape* is validated server-side (the backend on save, and at deploy), not at the MCP tool boundary — so keep the key simple (lowercase alphanumerics with `_`/`-`; avoid dots, slashes, spaces) and reference it identically everywhere; keys are exact-match and never normalized (see `dtwo-gateway-policy` → Managing Markers). The `jsonSchema`, though, *is* checked at the tool boundary — it must parse as a JSON object.\n\n### Marker Rego gotchas\n\n- **`time.now_ns()` must stay an integer.** Use `time.now_ns()` raw for timestamp fields typed `integer` in the schema. Dividing in Rego (e.g. `time.now_ns() / 1000000`) produces a **float**, which fails a `\"type\": \"integer\"` schema — and with `onDrop: \"deny_request\"` that silently-authored bug will block the tool call.\n- **Match the key exactly.** The `session_writes` key, the `writableKeySchema` `name`, and the registered marker FQID must all be the identical `marker:<namespace>:<id>` string. A mismatch drops the write.\n- **Multiple writers land in separate slots.** If two policies declare and emit the same key, each write lands under its own writer UID; the walk-all-writers read finds either. Prefer one canonical writer per marker.\n- **Reads fail open on absent state.** If `input.context.session.policies` is missing or the marker was never written, the `_active` helper simply doesn't match — the reader allows. Structure high-sensitivity gates so the *presence* of the marker is what denies, not its absence (that's the intended semantics: no signal → nothing to block). A marker that *grants* a capability inverts this and must read fail-closed instead — see **Markers that grant**.\n- **Time arithmetic makes floats.** `(time.now_ns() - marked_at) / 1000000000` is a float; wrap the result in `ceil` or `floor` before `sprintf` and print it with `%v`. Never write a derived time back into an `integer` schema field — the stored `marked_at` stays the raw `time.now_ns()`.\n\n## Intent-capture policies (conditional — feature-gated)\n\n> **Availability gate — read this first.** The intent-capture surface only exists when intent is enabled: the `set_intent` tool is auto-injected in-container when the gateway sets `gateway.intent.enabled`, and the intent registry-management tools are registered when the Dtwo MCP server is deployed with `enable_intent_tools: true`. Intent capture is **not customer-available yet** (pending product-management usability verification). **Do not present intent-capture policies, `set_intent`, or intent/marker compatibility to the user unless those tools are actually available** — check for `set_intent` / `dtwo-*-intent*` in your tool list, or confirm via the companion `dtwo-gateway-policy` instructions. If they are absent, this section is inert; markers (above) still work fully.\n\n**The intent-capture Rego is platform-managed — do not write or modify it, and do not offer to.** Two policies do the enforcement — an **egress capture** that records the declared intent into session state and denies disallowed transitions or intent/marker incompatibilities, and an optional **intent-required gate** that blocks tool calls until an intent is set. These are owned by the platform (automatically injected when intent capture is enabled via `gateway.intent.enabled`); their bodies and wiring are not user-authored, and the Rego may not be visible to users. If asked to author or change intent-capture Rego, decline and point the user at the platform-managed feature (and the user-facing registry/compatibility tools in `dtwo-gateway-policy` → Intent Capture). This section exists only so you can *recognize and explain* the behavior, not reproduce it.\n\nOne behavior worth knowing when explaining them: intent/marker compatibility is **one-directional and set-time only** — the check runs at `set_intent` time; a marker raised *after* an intent is set does not retroactively deny.\n\n### Reading the session intent in a tenant policy\n\nAuthoring the intent-*capture* Rego is off-limits (above), but a tenant policy may legitimately **gate a tool on the current session intent** (e.g. \"only allow this tool under a `debug` or `explore` intent\"). When you do, read the intent **only** through the platform helper library `data.dtwo.lib.intent_match`:\n\n| Helper | Returns |\n|---|---|\n| `data.dtwo.lib.intent_match.current_intent(input)` | The full intent object (`{category, description, set_at}`); **undefined** when no intent is set. |\n| `data.dtwo.lib.intent_match.current_category(input)` | Just the category FQID (e.g. `internal:debug`); undefined when unset. |\n| `data.dtwo.lib.intent_match.category_in(input, allowed)` | `true` when the current category is in the `allowed` set of FQIDs; `false` otherwise (including when no intent is set). |\n| `data.dtwo.lib.intent_match.is_platform_set_intent(input)` | `true` when the incoming call is the platform `set_intent` tool — the intent server auto-injected in-container when `gateway.intent.enabled` is set; `false` for anything else, including lookalike tools from other MCP servers. `false` when intent capture is off. Available to tenant policies for inspection — see **Closed pipeline** below for which direction(s) the platform bypass is armed in (egress with `intent.enabled: true`; ingress additionally with `intent.required: true`). In an armed direction customer contributions are dropped anyway, so this helper is not needed to defensively skip a gate there; in a non-armed direction (typically ingress under `enabled: true, required: false`) it can be used to observe `set_intent` calls without contradicting the closure. The platform policies use it as an unforgeable anchor. |\n\n**Do not read the intent from `input.context.session.policies` directly**, and do not hand-roll a walk-all-writers read for it. The helper is pinned to the trusted platform intent-capture slot, which tenant policies cannot write; a direct read is spoofable (any policy's own writer slot could supply an intent-shaped value) and couples your policy to internal storage details. Reading intent is the one case where the marker walk-all-writers pattern is the wrong tool.\n\nThe category values you compare against are the intent **FQIDs** — the `name` field returned by `dtwo-list-intents` (e.g. `internal:default`, `internal:debug`, `internal:explore`), **not** the short form echoed in the `set_intent` response. Pull the registry to confirm the exact FQIDs rather than guessing.\n\nExample — an ingress policy that permits one tool only under low-risk intents, and passes every other tool through untouched:\n\n```rego\npackage echo.ingress.intent_gate\n\nimport future.keywords.if\n\ndefault allow := false\n\n# Intent FQIDs (from dtwo-list-intents `name`) permitted to call the gated tool.\n_allowed_intents := {\"internal:default\", \"internal:debug\", \"internal:explore\"}\n\n# This policy only gates one tool — everything else passes through.\nallow if {\n    lower(input.resource.name) != \"echo-echo\"\n}\n\nallow if {\n    lower(input.resource.name) == \"echo-echo\"\n    data.dtwo.lib.intent_match.category_in(input, _allowed_intents)\n}\n\nreason := \"This tool is only permitted under the 'default', 'debug', or 'explore' intents. Declare one with set_intent and retry.\" if {\n    lower(input.resource.name) == \"echo-echo\"\n    not data.dtwo.lib.intent_match.category_in(input, _allowed_intents)\n}\n```\n\nNotes:\n\n- **Availability — safe to reference on any gateway.** The `dtwo.lib.intent_match` library is shipped into **every** policy bundle unconditionally (independent of the intent flag), so a reference to `data.dtwo.lib.intent_match.*` always resolves and compiles — it will *not* cause an \"undefined function\" bundle failure when intent capture is off. It only returns real values when intent capture is enabled; with it off there's no captured intent, so `current_intent` is undefined and `category_in` is simply always `false` — meaning a gate like the one above would deny the gated tool on a no-intent gateway. Design the default accordingly (and see the availability gate at the top of this section before surfacing intent behavior at all).\n- **Never echo the intent value into a deny `reason` or a `transform`.** Use the intent for the *decision*, never as content the agent reads back: do not interpolate `current_intent(input)` or `current_category(input)` — and above all not the intent `description` — into `decision.reason`, and do not place it in `decision.transforms[]`. Two independent reasons. The `description` is free text the *caller* supplied, so echoing it round-trips unvalidated caller text through your policy's output. And the intent is a governance input: a policy that reflects it back turns it into a channel the agent can read, which is exactly what it is not for. Say which rule denied (\"this tool is not permitted under the current session intent\"), not what the intent was. Registry text is a different matter — that is authored by your admins and is safe to surface (see Reading the registry).\n- **A `default allow := false` gate still risks self-lock** if it fronts the Dtwo MCP server — keep the non-gated-tool passthrough (as above) so `dtwo-*` management calls are unaffected. See the self-lock pitfall in Common Pitfalls.\n\n### Closed pipeline — your policies may not enforce on `set_intent`\n\nThe platform `set_intent` tool has a **closed pipeline** in the directions where a platform enforcement policy is present. Customer policies (both ingress and egress) still evaluate on those calls, but their `allow`, `reasons`, `session_writes`, and `transforms` contributions are dropped before the aggregate whenever the closure is armed for that direction. Effect in an armed direction: a default-deny does **not** block `set_intent`, a redaction transform does **not** rewrite the response, and a `session_writes` a customer policy attempted on that call does **not** land.\n\nThe closure follows the platform policy per direction — it is only armed when the corresponding platform enforcement is on:\n\n- **Egress closure** — armed when `gateway.intent.enabled: true` (platform `intent_capture` is on egress). Why: `intent_capture` commits an authoritative session-state write, and the substrate applies `session_writes` regardless of the unified decision. Without the closure a customer deny on the response would block the response to the client while the session already committed the intent — client and session state would drift out of sync. The closure keeps them in lockstep.\n- **Ingress closure** — armed when `gateway.intent.required: true` (platform `intent_required` is on ingress). Why: `intent_required` allows `set_intent` unconditionally so the agent can bootstrap an intent, but a customer default-deny would AND against that and lock the agent out. The closure keeps `set_intent` reachable under the required gate.\n- **Under `enabled: true, required: false`** the ingress closure is NOT armed. No substrate hazard on ingress (writes only happen on egress) and no deadlock hazard (no `intent_required` in the pipeline). Customer ingress policies **can** and **do** govern `set_intent` — authz on scopes, rate-limiting, inspecting the `description` argument for oversized/malformed content. The egress closure remains armed as long as capture is on.\n\nPractical implications for authoring:\n\n- **A \"deny by default\" gate on the Dtwo MCP server** will still fire on `set_intent` **on ingress** as long as `intent.required: false`. If a tenant is debugging why their default-deny appears to let `set_intent` through, check whether the gateway has `intent.required: true` (ingress closure armed) — that IS the platform closure, not a policy-shape issue.\n- **The egress closure is always armed with `enabled: true`.** A tenant redaction transform on `set_intent` responses, or a tenant egress deny on the response body, has no effect on `set_intent` — those calls flow through platform egress alone.\n- **No defensive `not is_platform_set_intent(input)` guard is needed** in a tenant policy in the armed direction. The wrapper handles the skip at the aggregation layer; adding the guard yourself is a no-op.\n- **The closure is anchored** to the platform intent server auto-injected in-container (when `gateway.intent.enabled` is set) — a lookalike `set_intent` tool from a *different* MCP server does **not** trigger the bypass in either direction, so tenant policies enforce on those calls normally. If a tenant needs to block lookalikes, deny by tool name the same way they would for any other MCP server's tool.\n- **`is_platform_set_intent(input)` remains useful for observation.** A non-enforcing egress policy that only writes evidence (say, an audit marker on `set_intent` responses for tenant records) may still identify the call with this helper. The helper is a read, not a lever — in the armed direction, customer enforcement contributions are dropped anyway.\n\n## Handling Parse and Access Failures\n\nRego rules fail **silently** — if any expression in a rule body fails (e.g., `json.unmarshal` on non-JSON text, or accessing a missing key), the entire rule body does not match. No error is raised. This means the policy's behavior on bad data depends on how the rules are structured.\n\n### Fail-open vs fail-closed\n\n- **Fail-open (default for positive checks):** If a rule checks for a specific condition (e.g., `has_confidential_label`) and the parse fails, the condition is `false`, and `not has_confidential_label` is `true` — the response is **allowed**. This is appropriate when the absence of evidence means there's nothing to block.\n\n- **Fail-closed (deny on parse failure):** If you want to **block** when data can't be parsed or verified, structure the `allow` rule so that a successful parse is required for it to fire. If the parse fails, `allow` never becomes `true`, and the default deny takes effect.\n\n### Example: Fail-closed pattern\n\n```rego\n# Only allow if we can parse the response AND it passes the check\nallow if {\n    some text in input.payload.text\n    parsed := json.unmarshal(text)\n    not contains_sensitive_data(parsed)\n}\n```\n\nIf `json.unmarshal` fails here, `allow` never fires, and the default `deny` holds — the response is blocked.\n\n### Example: Fail-open pattern\n\n```rego\n# Block only if we can confirm sensitive data is present\nallow if {\n    not confirmed_sensitive\n}\n\nconfirmed_sensitive if {\n    some text in input.payload.text\n    parsed := json.unmarshal(text)\n    contains_sensitive_data(parsed)\n}\n```\n\nIf `json.unmarshal` fails, `confirmed_sensitive` is `false`, so `allow` fires — the response is allowed through.\n\n### Guidelines\n\n- Use **fail-closed** when the policy protects high-sensitivity data and you'd rather block an unparseable response than risk leaking it\n- Use **fail-open** when the check targets a specific data pattern (e.g., a label) and non-matching formats are safe to pass through\n- Use `object.get(obj, key, default)` instead of direct key access (`obj.key`) to avoid silent failures on missing keys\n- When iterating over `input.payload.text` with `some text in ...`, be aware that if *any* entry matches a blocking condition, the rule fires — but if *none* can be parsed, the rule won't fire at all\n\n## Commonly Used Rego Built-in Functions\n\nThe functions below are frequently used in Dtwo policies. All standard OPA Rego built-ins are also available.\n\n### String Matching & Manipulation\n- `contains(string, search)` — check if string contains substring\n- `startswith(string, prefix)` / `endswith(string, suffix)`\n- `lower(string)` / `upper(string)` — case conversion\n- `concat(delimiter, array)` — join array elements\n- `sprintf(format, values)` — formatted string output\n- `split(string, delimiter)` — split string into array\n- `indexof(string, search)` — find position of substring\n- `trim_space(string)` — trim whitespace\n\n### Regex\n- `regex.match(pattern, value)` — test if value matches pattern\n- `regex.replace(string, pattern, replacement)` — regex replace\n\n### Object & Collection\n- `object.get(obj, key, default)` — safe key access with default\n- `object.keys(obj)` — get object keys\n- `object.union(a, b)` — merge objects\n- `object.remove(obj, keys)` — remove keys from object\n- `count(collection)` — length of string/array/set/object\n- `sort(array)` — sort array\n- `some x in collection` — iteration / membership test\n\n### Encoding\n- `json.marshal(x)` / `json.unmarshal(string)` — JSON encode/decode\n\n### Time\n- `time.now_ns()` — current time in nanoseconds\n- `time.parse_rfc3339_ns(string)` — parse RFC 3339 timestamp\n- `time.weekday(ns)` — day of week as string\n\n## Debugging Policies\n\nWhen a policy isn't behaving as expected, use these techniques to inspect what the gateway is actually sending to OPA.\n\n### Finding the Correct Tool Name\n\nTool names appear in `input.resource.name` (PARC; the legacy alias `input.payload.name` carries the same value) and are constructed as `<server-name>-<tool-name>`, where `<server-name>` is the name given to the MCP server when it was configured on the gateway. For example, if an Atlassian MCP server is named `atlassian-jira-mcp` on the gateway, its `getjiraissue` tool appears as `atlassian-jira-mcp-getjiraissue`. A Slack server named `slack-mcp` would have tools like `slack-mcp-slack-send-message`.\n\nThe client may display a different name (e.g., `mcp__dtwo__atlassian-jira-mcp-getjiraissue` in Claude Code) — the gateway prefix is stripped, but the server name prefix is preserved.\n\n> Note: this is the gateway-to-OPA name (what `input.resource.name` contains inside a Rego policy), **not** the MCP client invocation name you call as a tool. The latter is covered in the companion `dtwo-gateway-config` and `dtwo-gateway-policy` instructions.\n\n**Do not guess tool names.** The server name is configured by the gateway admin and is not standardized. Use a debug policy to discover the exact name the gateway passes, or follow the tool-discovery guidance in the companion `dtwo-gateway-policy` instructions to discover tool names and argument schemas via the Dtwo MCP server when available.\n\n### Debug Policy: Dump Tool Name and Arguments\n\nTemporarily add rules that force a deny and include the full input in the reason. This lets you see the exact tool name and argument keys/values:\n\n```rego\n# --- TEMPORARY DEBUG RULES — remove after debugging ---\nallow := false if {\n    true\n}\n\nreasons contains sprintf(\"Debug - name: %s, args: %v\", [input.resource.name, input.payload.args]) if {\n    true\n}\n# --- END DEBUG RULES ---\n```\n\nThis blocks all tool calls and returns the tool name and arguments in the denial message. (`input.resource.name` is the PARC field; the legacy alias `input.payload.name` holds the same value if you see it in older policies. Arguments stay at `input.payload.args`.)\n\nTo inspect **identity** (the `subject` block and the JWT-derived claims), add:\n\n```rego\nreasons contains sprintf(\"Debug - user: %s, subject.sub: %s, claims: %v\", [\n    object.get(input, \"user\", \"<not set>\"),\n    object.get(object.get(input, \"subject\", {}), \"sub\", \"<not set>\"),\n    object.get(object.get(input, \"subject\", {}), \"claims\", \"<not set>\"),\n]) if { true }\n```\n\nUse this to confirm what specific claim *values* are present in `input.subject.claims` for the current caller. To enumerate just the *names* the tenant has observed (across all callers, without attaching a policy), prefer `dtwo-list-claims` from the Dtwo MCP server — tenant-wide by default, optionally scoped with `gatewayUid`.\n\n> **Self-lock warning.** An always-deny dump policy blocks **every** call on that gateway — including the `dtwo-*` management tools if your client routes through it — so you can lock yourself out. Attach it to a gateway you are *not* managing through, or be ready to detach it in the Dtwo Hub (**Gateways** in the left sidebar, open the gateway, then its **Policies** tab). Full mechanism and the management-bypass pattern: see Common Pitfalls → \"Self-locking with an always-deny ingress policy\".\n\nTo scope the debug to a specific tool pattern (e.g., only Atlassian tools):\n\n```rego\n# --- TEMPORARY DEBUG RULES — remove after debugging ---\nallow := false if {\n    startswith(lower(input.resource.name), \"atlassian-\")\n}\n\nreasons contains sprintf(\"Debug - name: %s, args: %v\", [input.resource.name, input.payload.args]) if {\n    startswith(lower(input.resource.name), \"atlassian-\")\n}\n# --- END DEBUG RULES ---\n```\n\nFor **egress** policies the tool output is in `input.payload.text`; the tool name is still `input.resource.name` (PARC populates it on egress too — the legacy `input.tool_metadata.name` holds the same value):\n\n```rego\n# --- TEMPORARY EGRESS DEBUG RULES — remove after debugging ---\nallow := false if {\n    true\n}\n\nreasons contains sprintf(\"Debug - tool: %s, text: %v\", [input.resource.name, input.payload.text]) if {\n    true\n}\n# --- END EGRESS DEBUG RULES ---\n```\n\n### Diagnosing Blanket Denies\n\nIf all tool calls are being denied (including tools on unrelated MCP servers), the most common causes are:\n\n1. **Syntax errors in any `.rego` file:** A Rego compilation error in one file can cause the entire policy bundle to fail to load, causing the gateway to fall back to a default deny. Check for incomplete rules (e.g., `reasons contains sprintf()` with no arguments or body).\n\n2. **Package path mismatch:** If the ingress/egress aggregator policy references a package path that doesn't match the step policy's `package` declaration, the aggregator can't find the step policy's `allow` value. With `default allow := false` in the aggregator, this results in a blanket deny. Verify the `package` declaration in each step policy matches the `data.<path>.allow` reference in the aggregator.\n\n3. **Empty `.rego` files:** OPA fails with `rego_parse_error: empty module` if a `.rego` file has no content.\n\n4. **OPA stuck on a failed compilation after deployment:** During deployment, the gateway writes policy files by first deleting all existing files (`rm -f *`) and then writing new ones sequentially. OPA's file watcher may pick up intermediate states during this process — empty files, stale files before deletion, or partially written files — and fail to compile. Even after all files are correctly in place, OPA may remain stuck on the failed compilation and never successfully reload. **Fix:** Restart OPA after deployment (e.g., `pm2 restart opa`) to force a clean load of the current files.\n\n5. **Transient log errors during deployment are expected:** Errors like `rego_parse_error: empty module` or `multiple default rules` in OPA logs during a deployment are typically transient — they reflect OPA's file watcher reacting to intermediate file states, not actual policy problems. Compare the error timestamps against the deployment time. If the errors only appear during the deployment window and the files on disk are correct afterward, an OPA restart resolves the issue.\n\n### Debugging Checklist\n\n1. **Verify tool names:** Use the debug policy above to confirm `input.resource.name`\n2. **Verify argument keys:** Check the exact keys in `input.payload.args` (e.g., `issueIdOrKey` vs `issueKey`)\n3. **Check compilation:** Ensure every `.rego` file has valid syntax and a `package` declaration\n4. **Check package paths:** Ensure step policy packages match the aggregator's `data.*` references\n5. **Test incrementally:** Start with a permissive policy (`default allow := true`) and add deny rules one at a time\n\n## Valid Rego Patterns (Not Bugs)\n\nThe following patterns are valid Rego and should **not** be flagged as issues when reviewing policies.\n\n### `default allow := true` with `allow := false if { ... }`\n\nThis is valid. The `default` only applies when no rule body matches. When the condition in `allow := false if { ... }` matches, `allow` is `false`. When it doesn't match, the default `true` takes effect. There is no complete rule conflict — this is a standard pattern for policies that allow by default and deny specific conditions.\n\n```rego\ndefault allow := true\n\n# This is NOT a conflict — the default only fires when the condition below doesn't match\nallow := false if {\n    input.resource.name == \"some-tool\"\n    some_blocking_condition\n}\n```\n\n### Silent failure on missing keys in deny conditions\n\nWhen a rule accesses a key that doesn't exist (e.g., `input.payload.args.transition.id`), the rule body silently fails and doesn't match. In a deny-specific-condition policy with `default allow := true`, this is **correct behavior** — if the key doesn't exist, the request isn't the one being blocked, so it should be allowed. Only flag this as a bug if the policy uses `default allow := false` and the missing key would prevent an `allow` rule from firing when it should.\n\n### Hardcoded IDs and values\n\nPolicies often contain hardcoded values like transition IDs, project keys, or tool names. These are **implementation details, not bugs** — they reflect the specific environment the policy targets. At most, suggest adding a comment documenting what the value represents, but do not flag them as issues.\n\n## Common Pitfalls\n\n- **Identifying the tool in egress policies:** For `tool_post_invoke`, the tool name is available in three places — `input.tool_metadata.name`, `input.resource.name` (with PARC), and `input.payload.name`. All three carry the same value. Prefer `input.tool_metadata.name` or `input.resource.name` for direction-agnostic policies; treat `input.payload.name` as ingress-canonical and verify with the dump-input technique before relying on it for non-tool egress hooks (`prompt_post_fetch`, `resource_post_fetch`).\n- **Assuming fields are always present:** External APIs don't always return the same fields. For example, Jira may expose `emailAddress` for some users but not others depending on privacy settings. Always use `object.get(obj, key, default)` and consider fallback checks (e.g., matching on `displayName` when `emailAddress` is missing).\n- **Forgetting the `default allow` declaration:** Without a default, `allow` is `undefined` when no rule matches, which OPA treats differently than `false`. Always include `default allow := false` (for deny policies) or `default allow := true` (for transform-only policies).\n- **Direct key access on optional fields:** `input.payload.args.someField` will cause the rule to silently fail if `someField` doesn't exist. Use `object.get(input.payload.args, \"someField\", \"\")` instead.\n- **Guessing tool names:** Tool names in `input.resource.name` (legacy alias `input.payload.name`) are prefixed with the MCP server name as configured on the gateway (e.g., `atlassian-jira-mcp-getjiraissue`, not just `atlassian-getjiraissue`). Examples in this skill use shortened names for readability, but real policies must match the exact name the gateway sends. Use the debug policy technique to confirm.\n- **Case-sensitive tool name comparisons:** By default, compare tool names case-insensitively using `lower(input.resource.name) == \"...\"` (works for both ingress and egress). Tool names are strings configured on the gateway, and a case mismatch will silently cause the policy to not match — which is a hard bug to debug. Use case-sensitive comparisons only when the user has an explicit reason to do so.\n- **Direct access on `subject.claims`:** `input.subject.claims.org_id` silently fails if the claim isn't present, making the entire rule body fail to match — easy to mistake for a different bug. Always use `object.get(input.subject.claims, \"<claim>\", \"<default>\")`. Choose the default carefully so a missing claim produces a clean deny (e.g., `\"\"` for string compares, `[]` for `some x in ...`).\n- **Assuming standard JWT claims are in `subject.claims`:** `aud`, `exp`, `iat`, `nbf`, `jti`, `azp`, `nonce`, and other validation-layer/OIDC claims are stripped before they reach the policy — Rego is not meant to be a parallel JWT validator. `iss` is the documented exception. See Identity (Subject and Claims) for the full strip set.\n- **Using `is_admin`, `teams`, or `user` from `subject.claims` for authorization:** These claims are stripped because they are ContextForge-internal RBAC plumbing minted by CF's own JWT issuer, not upstream IdP assertions. A policy that does `input.subject.claims.is_admin == true` is *always* false. For role-based authorization, use IdP-supplied claims like `groups`, `roles`, or namespaced custom claims.\n- **Treating `input.subject.sub` as an email address:** For tokens issued by ContextForge itself, `sub` is the user's email. For external IdP tokens, `sub` is whatever the IdP put in the `sub` claim — typically an IdP-prefixed identifier like `google-apps|paul@dtwo.ai`, not a clean email. On **Microsoft Entra** tokens (v1 and v2) `sub` is worse still: a **pairwise pseudonym** that is opaque *and* differs across app registrations, so it is useless for correlating identity outside the single app the token was minted for — read `upn` / `unique_name` (v1) or `preferred_username` (v2) for the human identifier, or `oid` + `tid` for a cross-app durable key. If you need a stable user identifier, compare against the full `sub` value; if you need an email, prefer `input.subject.claims.email` (when the IdP emits it) and fall back to `sub` only when you've confirmed the IdP issues email-shaped subs.\n- **Comparing `email` without checking `email_verified`:** `email` is provider-*claimed*, not provider-*verified*, unless the IdP also sends `email_verified: true`. A policy that authorizes on `input.subject.claims.email` alone can be spoofed by a token carrying an unverified `email`. Pair every identity comparison on `email` with `object.get(input.subject.claims, \"email_verified\", false) == true`, or key on a provider-asserted claim (`sub`, `upn`) instead. See **Asserted vs. verified claims** under Notes on common claims.\n- **Self-locking with an always-deny ingress policy:** Attaching a `default allow := false` policy (or one that denies broadly during debugging, like a dump-input policy) to a gateway will block *every* tool call on that gateway — including any Dtwo MCP management tools your client routes through it. **This only applies when the Dtwo MCP server itself is configured behind that gateway** (a common but not universal setup); if your Dtwo MCP server runs outside the gateway, calls to it bypass the gateway's policies and self-locking does not happen. When in doubt, check the gateway config: if `mcp_servers` includes a Dtwo entry that your client connects through, you are at risk.\n\n  **Mitigation: management-tool passthrough.** Add a single `allow if` rule that exempts `dtwo-*` tools from the deny:\n\n  ```rego\n  # Management bypass — keep Dtwo MCP management tools usable while this policy is attached\n  allow if {\n      startswith(lower(input.resource.name), \"dtwo-\")\n  }\n  ```\n\n  Place this near the top of your policy, before the deny conditions. If your gateway also fronts a different management surface, add similar passthroughs for that prefix. Recovery if you skip the bypass and lock yourself out: detach the policy in the Dtwo Hub (**Gateways** in the left sidebar, open the gateway, then its **Policies** tab), or via an MCP client that goes through a different gateway.\n\n## Policy Store Catalog Contributions\n\nContributing reusable policies to the **`dtwoai/policy-store`** repo (repository layout, `policy.md`/`tests.yaml`\nfrontmatter, landing-page links, manifest generation, and the registration flow) is a separate, lower-frequency\nworkflow. To keep this skill lean it lives in a reference file: before doing any policy-store contribution work,\nread [`references/policy-store-catalog.md`](references/policy-store-catalog.md) (bundled alongside this skill; if the\nrelative path doesn't resolve, read `${CLAUDE_SKILL_DIR}/references/policy-store-catalog.md`). Rego correctness for those catalog\npolicies still follows the rules in this skill (use PARC fields, compare tool names with `lower(input.resource.name)`, etc.).\n\n## Limitations\n\n- This skill cannot version, revert, or deploy policies — see the companion `dtwo-gateway-policy` instructions for lifecycle operations\n- This skill does not know what specific tools are available on an MCP server or what arguments they accept — follow the tool-discovery guidance in the companion `dtwo-gateway-policy` instructions or the debug policy technique (see Debugging Policies) to discover tool names and argument shapes\n- This skill does not have access to runtime policy evaluation results\n"
}

SHA-256 of public snapshot: 0de089ce59a3d1de448108e0624905aacd20c888930bd16975eab3acc69038a1