Delegation Policy
Approve the same low-risk request three times in a row and you will naturally tell your agent, "Stop asking me about these." The trouble with saying that in a chat message is that tomorrow's replacement agent never saw the chat, while today's worker stretches your casual "yes" to cover something risky you never meant to hand over.
Delegation Policy turns a requester's standing instructions into durable,
role-bound hub records with explicit scope, exceptions, and an automatic expiry date. Before
executing a guarded action, the hub verifies facts from its own records, honors reservations
above all permissive rules, and commits an immutable Policy use
receipt in the exact same transaction. Reach for it whenever you keep giving the same answer
to a recurring class of actions or decisions.
Policy, Policy use
Why "just stop asking me" breaks both ways
Whether agents are approving routine vendor invoices, publishing reviewed documentation, triaging support credits, or merging bug fixes before a release, asking the requester every single time wastes her attention. Yet waving permission away in a chat message fails in two opposite directions at once:
First, it evaporates across sessions. When a lead agent is replaced the next day, the new session never saw yesterday's conversation and resumes asking the exact same questions. Second, it quietly overreaches. Without stated exceptions or an end date, an agent that did see the message applies it to edge cases — a schema migration, a recurring contract, a production billing change — that the requester would never have pre-approved, leaving no structured log of what happened in her name.
Delegation Policy fixes both failures with four structural guarantees enforced by the hub:
-
Policies bind to roles, not individual sessions. Granting a rule to
lead_agentorworkermeans tomorrow's replacement agent inherits the exact same boundary automatically. -
Every permissive rule carries explicit conditions, exceptions, and an expiry date.
Standing permissions (
allow) and delegated judgment scopes (decide) expire automatically unless renewed, while reservations (reserve) can hold indefinitely. - The hub gathers the facts and enforces fail-closed precedence. A reserving policy always overrides any permissive policy, and a missing fact always falls back to asking the requester.
-
Every covered act writes an immutable
Policy usein the same transaction, linking the action back to the requester's exact words and the facts matched at that moment.
Why require an expiry date on allow and
decide policies, but allow reserve
policies to last forever? Because forgetting to renew a temporary permission merely
produces one extra question — whereas an expiring reservation would silently hand a
high-stakes decision back to a broader standing permission without warning.
Architecture and participants
Only the human Requester may grant, replace, or revoke a
Policy. Whenever an agent attempts a guarded action — or
the lead agent exercises judgment inside its decision scope — the Hub
gathers facts from its own records (such as checker findings or changed resources), runs the
pure PolicyCheck function, and either executes and logs
atomically or holds the action pending for human input.
covered verdict executes the action and commits a
Policy use; reserved, unknown, and uncovered attempts stay
pending.
Policy rows, gathers verifiable facts
from its own records, runs PolicyCheck, commits covered
actions alongside a Policy use, and blocks uncovered
or reserved actions.
decide scope. Because policies target the role, any
replacement lead agent inherits the same boundaries.
checker_approved: true).
Policy captures who granted authority, the role, effect
(allow, decide,
reserve, or gate),
scope, words, and expiry. Policy use is the immutable
log of one authorized act and the exact facts matched.
Execution flow
Toggle between the normal path — where a standing policy covers an action and executes it with an atomic receipt — and the exception and expiry path — where an excluded change and an expired policy both safely fall back to asking the requester.
The requester grants the policy once and confirms how the hub parsed its conditions.
The next day, the hub verifies facts from its own records, executes the covered action,
and writes one Policy use in the same transaction.
Uses the same active policy (approved bug fixes on acme/api,
excluding schema changes, ending Friday 5:00 p.m.).
When PR 415 modifies a schema file, the exception matches and the hub returns
not_covered with no action and no
Policy use. After Friday 5:00 p.m., the policy expires
automatically so Saturday's PR 421 also asks the requester and offers renewal.
Missing reservation facts: If an in-force
reserve policy names a fact (such as
payment_code) that the hub cannot verify from its records,
PolicyCheck returns unknown
and blocks any broader allow policy from firing.
Concrete examples
Delegation Policy governs any recurring operational, financial, editorial, or engineering decision where a hub sits between an agent and the action.
Example 1 — Vendor procurement & marketing invoices
No code or unit tests- Policy granted
- "Until December 31, the lead agent may approve freelance copywriting invoices under $250 that passed finance verification, unless they create a recurring subscription. Reserve all legal contract signatures for me indefinitely."
- Covered use
-
A verified $180 one-off copywriting invoice matches every condition and triggers no
exception. The hub approves payment and commits a
Policy usecapturing the invoice ID, amount, and verification record. - Boundary caught
-
A $190 invoice marked
recurring: truehits the exception; the hub holds payment and routes a question to the marketing director. On January 1, the policy expires automatically and all invoices ask again until renewed.
Example 2 — Pre-release bug-fix merges & decision scope
Software engineering- Policies granted
-
Allow policy: "In
acme/api, the lead agent may merge any bug fix a checker approved unless it changes the database schema. Ends Friday 5:00 p.m."
Decide policy: "For 'Retry failed webhooks', the lead agent may settle internal implementation choices invisible to customers until November 30."
Reserve policy: "Always ask me about customer data retention or changes touching payment code." - Covered use
-
On Thursday morning, PR 412 (checker-approved bug fix, no schema file) merges
automatically and logs
Policy useuse_1— even though a fresh lead agent started that day. - Exceptions & expiry
-
PR 415 adds a column to
orders→ schema exception fires → held for requester. Saturday's PR 421 arrives after Friday 5:00 p.m. → expired → held for requester with a renewal prompt.
What this pattern is NOT — Irreversible high-damage acts or uncheckable prompts
Negative example- Situation
- Pre-approving permanent deletion of customer databases or wire transfers, or writing a policy whose condition is "merge if the diff looks low-risk to the agent."
- Why skip it
- When one mistake is expensive and cannot be undone, asking every time is far cheaper than one mistaken pre-approval — keep those actions reserved and guard them with Policy Gate. And never create a policy whose conditions the hub cannot verify from its own durable records.
When to use and when to skip
Use Delegation Policy when
- The requester repeatedly receives the same class of ask and keeps giving the same approval.
- Agents restart or rotate across sessions, so standing rules must outlive any single chat.
- The hub sits in the execution path (holding credentials or performing the merge, payment, or publish itself).
- Every condition and exception in the rule can be checked from facts stored in the hub.
Skip it when
- One person watches one agent live in a single session — a one-click session allow is enough.
- A single mistaken action is irreversible and high-cost (deleting customer data, large payouts).
- The hub cannot independently verify the policy's facts and would have to trust the agent's word.
- You need to accept a finished request on the requester's behalf — keep final acceptance separate and reserved by default.
Data model and hub invariants
Delegation Policy defines two immutable tables — policies
and policy_uses — and links to
Party and Request
(Orchestrator-Workers),
Job (Durable Job), and
Question (Self-Contained Question).
The action, resource,
conditions, and exceptions
columns together define a policy's scope.
Party grants each immutable
Policy. Replacing a policy inserts a new row pointing to
the old one via replaces_id. Every authorized action
writes one Policy use capturing the matched facts.
Table: policies
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Unique policy identifier. |
| granted_by_id | uuid | NOT NULL, FK | References parties(id); must be a human party. |
| request_id | uuid | NULLABLE, FK | References requests(id); NULL means all requests of the grantor. |
| grantee_kind | text | NOT NULL | CHECK (grantee_kind IN ('lead_agent', 'worker', 'any_agent')). |
| effect | text | NOT NULL | CHECK (effect IN ('allow', 'decide', 'reserve', 'gate')). |
| action | text | NOT NULL | Short fixed code such as merge_pull_request or choose_implementation. |
| resource | text | NOT NULL | Target resource (e.g. acme/api) or any. |
| conditions | jsonb | NOT NULL | Fact key-value map that must all hold; defaults to '{}'. |
| exceptions | jsonb | NOT NULL | JSON array of condition maps; if any holds, policy does not apply; defaults to '[]'. |
| gate_rules | jsonb | NULLABLE | Ordered Policy Gate rules; non-null iff effect = 'gate'. |
| statement | text | NOT NULL | The requester's own plain-English words. |
| source_question_id | uuid | NULLABLE, FK | References questions(id) when created from a recurring answer. |
| replaces_id | uuid | NULLABLE, FK | References policies(id); forms an immutable replacement chain. |
| granted_at | timestamptz | NOT NULL | Time when the policy takes effect. |
| expires_at | timestamptz | NULLABLE | Required when effect IN ('allow', 'decide'); optional for reserve/gate. |
| revoked_at | timestamptz | NULLABLE | Set atomically when withdrawn or replaced. |
Table: policy_uses
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Unique policy use identifier. |
| policy_id | uuid | NOT NULL, FK | References policies(id); must be an in-force allow or decide policy. |
| request_id | uuid | NOT NULL, FK | References requests(id); request the action belongs to. |
| job_id | uuid | NULLABLE, FK | References jobs(id); when set, must belong to request_id. |
| actor_id | uuid | NOT NULL, FK | References parties(id); the agent that acted. |
| question_id | uuid | NULLABLE, FK | References questions(id); set when the use settled an open question. |
| resource | text | NOT NULL | Exact resource acted on (for example, acme/api). |
| facts | jsonb | NOT NULL | Snapshot of hub-gathered facts matched at used_at for later replay. |
| summary | text | NOT NULL | One-sentence human-readable summary of what was done or decided. |
| used_at | timestamptz | NOT NULL | Timestamp of the authorized action. |
Nine hub invariants
-
01Permissive policies require an expiry date Database constraint
CHECK (effect IN ('reserve', 'gate') OR expires_at IS NOT NULL)enforcesexpiry_requiredso no standing permission lasts indefinitely by accident. -
02Decision-scope policies target only the lead agent Database constraint
CHECK (effect <> 'decide' OR grantee_kind = 'lead_agent')enforcesdecide_requires_lead_agent, keeping judgment calls with the accountable lead. -
03Gate rules present if and only if effect is gate Database constraint
CHECK ((effect = 'gate') = (gate_rules IS NOT NULL))enforcesgate_rules_mismatch; gate policies store rules for Policy Gate and never authorize an action viapolicy_uses. -
04Job reference on a policy use belongs to the same request Database constraint
A composite foreign key
(request_id, job_id)referencingjobs(request_id, id)ensures a policy use cannot attach to a job from an unrelated request. -
05Only a human requester may grant, replace, or revoke a policy Hub guard
grantverifiesgrantor_kind == humanand rejects agents withonly_requester_may_grant. An agent may suggest wording, never authorize itself. -
06Policies are never edited in place Hub guard
Updating a policy inserts a new row with
replaces_idand setsrevoked_aton the prior row in the same transaction, preserving historical audit integrity for past uses. -
07Reserving policies always win over permissive policies Hub guard
PolicyCheck.checkevaluates activereservepolicies first. If one applies (reserved) or cannot be ruled out due to a missing fact (unknown), noallowordecidepolicy may cover the attempt. -
08Every covered act commits its Policy use atomically Hub guard
When
PolicyCheckreturnscovered, the hub writes thePolicy use(pointing to the active policy and matching facts) in the exact same transaction as the action or lead decision. -
09Policy uses are append-only and never edited or deleted Hub guard
Once committed, a
Policy useis immutable so Decision Audit can always trace a verdict of "should have asked me" back to the exact policy and facts.
Reference implementation
The pure PolicyCheck evaluator and hub guard wrapper in
Lean, TypeScript, Python, and Elixir. Notice how missing facts automatically fail closed for both
permissive and reserving policies.
-- Pure PolicyCheck and Hub guards for Delegation Policy
inductive GranteeKind where
| leadAgent | worker | anyAgent
deriving Repr, BEq, DecidableEq
inductive ActorKind where
| leadAgent | worker
deriving Repr, BEq, DecidableEq
inductive GrantorKind where
| human | agent
deriving Repr, BEq, DecidableEq
inductive PolicyEffect where
| allow | decide | reserve | gate
deriving Repr, BEq, DecidableEq
inductive HubError where
| onlyRequesterMayGrant | expiryRequired | decideRequiresLeadAgent | gateRulesMismatch
deriving Repr, BEq
-- Facts and conditions are key/value pairs; values are strings here for simplicity.
abbrev Facts := List (String × String)
-- Timestamps are Unix seconds, passed in by the caller.
structure Policy where
id : String
grantedById : String
requestId : Option String := none
granteeKind : GranteeKind
effect : PolicyEffect
action : String
resource : String
conditions : Facts := []
exceptions : List Facts := []
gateRules : Option Facts := none
statement : String
grantedAt : Nat
expiresAt : Option Nat := none
revokedAt : Option Nat := none
deriving Repr
structure Attempt where
id : String
actorId : String
actorKind : ActorKind
requestId : String
jobId : Option String := none
action : String
resource : String
facts : Facts
summary : String
deriving Repr
structure PolicyUse where
id : String
policyId : String
requestId : String
jobId : Option String
actorId : String
resource : String
facts : Facts
summary : String
usedAt : Nat
deriving Repr
inductive CheckResult where
| covered (policy : Policy)
| reserved (policy : Policy)
| unknown (policy : Policy)
| notCovered
deriving Repr
namespace PolicyCheck
def inForce (p : Policy) (now : Nat) : Bool :=
p.grantedAt <= now && p.revokedAt.isNone && p.expiresAt.all (now < ·)
def granteeMatches : GranteeKind → ActorKind → Bool
| .anyAgent, _ => true
| .leadAgent, .leadAgent => true
| .worker, .worker => true
| _, _ => false
def fits (p : Policy) (a : Attempt) : Bool :=
granteeMatches p.granteeKind a.actorKind &&
p.requestId.all (· == a.requestId) &&
p.action == a.action &&
(p.resource == a.resource || p.resource == "any")
-- Every key a condition or exception mentions is present in the facts.
def known (p : Policy) (facts : Facts) : Bool :=
(p.conditions :: p.exceptions).flatMap (·.map Prod.fst)
|>.all fun k => (facts.lookup k).isSome
def holds (wanted facts : Facts) : Bool :=
wanted.all fun (k, v) => facts.lookup k == some v
def applies (p : Policy) (facts : Facts) : Bool :=
known p facts && holds p.conditions facts && !p.exceptions.any (holds · facts)
def check (policies : List Policy) (a : Attempt) (now : Nat) : CheckResult :=
let fitting := policies.filter fun p => inForce p now && fits p a
let reserving := fitting.filter (·.effect == .reserve)
let permitting := fitting.filter fun p => p.effect == .allow || p.effect == .decide
if let some p := reserving.find? (applies · a.facts) then .reserved p
else if let some p := reserving.find? (!known · a.facts) then .unknown p
else if let some p := permitting.find? (applies · a.facts) then .covered p
else .notCovered
end PolicyCheck
structure Hub where
policies : List Policy := []
uses : List PolicyUse := []
deriving Repr
inductive AttemptResult (α : Type) where
| ok (useId : String) (result : α)
| askRequester (grantorId : String)
-- reason is "unknown" or "not_covered"; policyId names the reserve rule that lacked facts.
| ask (reason : String) (policyId : Option String)
deriving Repr
namespace PolicyHub
def grant (hub : Hub) (p : Policy) (grantorKind : GrantorKind) : Except HubError Hub := do
unless grantorKind == .human do throw .onlyRequesterMayGrant
if (p.effect == .allow || p.effect == .decide) && p.expiresAt.isNone then
throw .expiryRequired
if p.effect == .decide && p.granteeKind != .leadAgent then throw .decideRequiresLeadAgent
if (p.effect == .gate) != p.gateRules.isSome then throw .gateRulesMismatch
return { hub with policies := p :: hub.policies }
def attempt {α : Type} (hub : Hub) (a : Attempt) (now : Nat) (act : PolicyUse → α) :
AttemptResult α × Hub :=
match PolicyCheck.check hub.policies a now with
| .covered policy =>
let use : PolicyUse :=
{ id := a.id, policyId := policy.id, requestId := a.requestId, jobId := a.jobId,
actorId := a.actorId, resource := a.resource, facts := a.facts,
summary := a.summary, usedAt := now }
-- In a real hub, action execution and PolicyUse insert share one DB transaction.
(.ok use.id (act use), { hub with uses := use :: hub.uses })
| .reserved policy => (.askRequester policy.grantedById, hub)
| .unknown policy => (.ask "unknown" (some policy.id), hub)
| .notCovered => (.ask "not_covered" none, hub)
end PolicyHub
-- An agent can never grant a policy, whatever the policy says.
theorem agent_cannot_grant (hub : Hub) (p : Policy) :
PolicyHub.grant hub p .agent = .error .onlyRequesterMayGrant := by
rfl
// Pure PolicyCheck and Hub guards for Delegation Policy
type GranteeKind = "lead_agent" | "worker" | "any_agent";
type PolicyEffect = "allow" | "decide" | "reserve" | "gate";
interface Policy {
id: string;
grantedById: string;
requestId: string | null;
granteeKind: GranteeKind;
effect: PolicyEffect;
action: string;
resource: string;
conditions: Record<string, unknown>;
exceptions: Array<Record<string, unknown>>;
gateRules: Record<string, unknown> | null;
statement: string;
grantedAt: Date;
expiresAt: Date | null;
revokedAt: Date | null;
}
interface Attempt {
id: string;
actorId: string;
actorKind: "lead_agent" | "worker";
requestId: string;
jobId?: string;
action: string;
resource: string;
facts: Record<string, unknown>;
summary: string;
}
interface PolicyUse {
id: string;
policyId: string;
requestId: string;
jobId: string | null;
actorId: string;
resource: string;
facts: Record<string, unknown>;
summary: string;
usedAt: Date;
}
type CheckResult =
| { kind: "covered"; policy: Policy }
| { kind: "reserved"; policy: Policy }
| { kind: "unknown"; policy: Policy }
| { kind: "not_covered" };
function inForce(p: Policy, now: Date): boolean {
const t = now.getTime();
return (
p.grantedAt.getTime() <= t &&
p.revokedAt === null &&
(p.expiresAt === null || t < p.expiresAt.getTime())
);
}
function fits(p: Policy, a: Attempt): boolean {
return (
(p.granteeKind === a.actorKind || p.granteeKind === "any_agent") &&
(p.requestId === null || p.requestId === a.requestId) &&
p.action === a.action &&
(p.resource === a.resource || p.resource === "any")
);
}
function known(p: Policy, facts: Record<string, unknown>): boolean {
const keys = [
...Object.keys(p.conditions),
...p.exceptions.flatMap((ex) => Object.keys(ex)),
];
return keys.every((k) => Object.prototype.hasOwnProperty.call(facts, k));
}
function holds(wanted: Record<string, unknown>, facts: Record<string, unknown>): boolean {
return Object.entries(wanted).every(([k, v]) => facts[k] === v);
}
function applies(p: Policy, facts: Record<string, unknown>): boolean {
return (
known(p, facts) &&
holds(p.conditions, facts) &&
!p.exceptions.some((ex) => holds(ex, facts))
);
}
function checkPolicies(policies: Policy[], attempt: Attempt, now: Date): CheckResult {
const fitting = policies.filter((p) => inForce(p, now) && fits(p, attempt));
const reserving = fitting.filter((p) => p.effect === "reserve");
const permitting = fitting.filter((p) => p.effect === "allow" || p.effect === "decide");
const reserved = reserving.find((p) => applies(p, attempt.facts));
if (reserved) return { kind: "reserved", policy: reserved };
const unchecked = reserving.find((p) => !known(p, attempt.facts));
if (unchecked) return { kind: "unknown", policy: unchecked };
const covered = permitting.find((p) => applies(p, attempt.facts));
if (covered) return { kind: "covered", policy: covered };
return { kind: "not_covered" };
}
class PolicyHub {
policies: Policy[] = [];
uses: PolicyUse[] = [];
grant(policy: Policy, grantorKind: "human" | "agent"): void {
if (grantorKind !== "human") throw new Error("only_requester_may_grant");
if ((policy.effect === "allow" || policy.effect === "decide") && policy.expiresAt === null) {
throw new Error("expiry_required");
}
if (policy.effect === "decide" && policy.granteeKind !== "lead_agent") {
throw new Error("decide_requires_lead_agent");
}
if ((policy.effect === "gate") !== (policy.gateRules !== null)) {
throw new Error("gate_rules_mismatch");
}
this.policies.push(policy);
}
attempt<T>(attempt: Attempt, now: Date, act: (use: PolicyUse) => T) {
const res = checkPolicies(this.policies, attempt, now);
if (res.kind === "covered") {
const use: PolicyUse = {
id: attempt.id,
policyId: res.policy.id,
requestId: attempt.requestId,
jobId: attempt.jobId ?? null,
actorId: attempt.actorId,
resource: attempt.resource,
facts: attempt.facts,
summary: attempt.summary,
usedAt: now,
};
// In a real hub, action execution and PolicyUse insert share one DB transaction.
const result = act(use);
this.uses.push(use);
return { status: "ok" as const, useId: use.id, result };
}
if (res.kind === "reserved") {
return { status: "ask_requester" as const, grantorId: res.policy.grantedById };
}
const policyId = res.kind === "unknown" ? res.policy.id : null;
return { status: "ask" as const, reason: res.kind, policyId };
}
}
# Pure PolicyCheck and Hub guards for Delegation Policy
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Callable, Literal, Optional
GranteeKind = Literal["lead_agent", "worker", "any_agent"]
PolicyEffect = Literal["allow", "decide", "reserve", "gate"]
@dataclass(frozen=True)
class Policy:
id: str
granted_by_id: str
grantee_kind: GranteeKind
effect: PolicyEffect
action: str
resource: str
statement: str
granted_at: datetime
request_id: Optional[str] = None
conditions: dict[str, Any] = field(default_factory=dict)
exceptions: list[dict[str, Any]] = field(default_factory=list)
gate_rules: Optional[dict[str, Any]] = None
expires_at: Optional[datetime] = None
revoked_at: Optional[datetime] = None
@dataclass(frozen=True)
class Attempt:
id: str
actor_id: str
actor_kind: Literal["lead_agent", "worker"]
request_id: str
action: str
resource: str
facts: dict[str, Any]
summary: str
job_id: Optional[str] = None
@dataclass(frozen=True)
class PolicyUse:
id: str
policy_id: str
request_id: str
actor_id: str
resource: str
facts: dict[str, Any]
summary: str
used_at: datetime
job_id: Optional[str] = None
class PolicyError(Exception):
pass
class PolicyCheck:
@staticmethod
def in_force(p: Policy, now: datetime) -> bool:
return (
p.granted_at <= now
and p.revoked_at is None
and (p.expires_at is None or now < p.expires_at)
)
@staticmethod
def fits(p: Policy, a: Attempt) -> bool:
return (
p.grantee_kind in (a.actor_kind, "any_agent")
and p.request_id in (None, a.request_id)
and p.action == a.action
and p.resource in (a.resource, "any")
)
@staticmethod
def known(p: Policy, facts: dict[str, Any]) -> bool:
keys = list(p.conditions.keys()) + [k for ex in p.exceptions for k in ex.keys()]
return all(k in facts for k in keys)
@staticmethod
def holds(wanted: dict[str, Any], facts: dict[str, Any]) -> bool:
return all(facts.get(k) == v and k in facts for k, v in wanted.items())
@classmethod
def applies(cls, p: Policy, facts: dict[str, Any]) -> bool:
return (
cls.known(p, facts)
and cls.holds(p.conditions, facts)
and not any(cls.holds(ex, facts) for ex in p.exceptions)
)
@classmethod
def check(
cls, policies: list[Policy], attempt: Attempt, now: datetime
) -> tuple[str, Optional[Policy]]:
fitting = [p for p in policies if cls.in_force(p, now) and cls.fits(p, attempt)]
reserving = [p for p in fitting if p.effect == "reserve"]
permitting = [p for p in fitting if p.effect in ("allow", "decide")]
for p in reserving:
if cls.applies(p, attempt.facts):
return ("reserved", p)
for p in reserving:
if not cls.known(p, attempt.facts):
return ("unknown", p)
for p in permitting:
if cls.applies(p, attempt.facts):
return ("covered", p)
return ("not_covered", None)
class PolicyHub:
def __init__(self) -> None:
self.policies: list[Policy] = []
self.uses: list[PolicyUse] = []
def grant(self, policy: Policy, grantor_kind: Literal["human", "agent"]) -> None:
if grantor_kind != "human":
raise PolicyError("only_requester_may_grant")
if policy.effect in ("allow", "decide") and policy.expires_at is None:
raise PolicyError("expiry_required")
if policy.effect == "decide" and policy.grantee_kind != "lead_agent":
raise PolicyError("decide_requires_lead_agent")
if (policy.effect == "gate") != (policy.gate_rules is not None):
raise PolicyError("gate_rules_mismatch")
self.policies.append(policy)
def attempt(
self, attempt: Attempt, now: datetime, act: Callable[[PolicyUse], Any]
) -> tuple[str, Any]:
verdict, policy = PolicyCheck.check(self.policies, attempt, now)
if verdict == "covered" and policy is not None:
use = PolicyUse(
id=attempt.id,
policy_id=policy.id,
request_id=attempt.request_id,
job_id=attempt.job_id,
actor_id=attempt.actor_id,
resource=attempt.resource,
facts=attempt.facts,
summary=attempt.summary,
used_at=now,
)
# In a real hub, action execution and PolicyUse insert share one DB transaction.
result = act(use)
self.uses.append(use)
return ("ok", result)
if verdict == "reserved" and policy is not None:
return ("ask_requester", policy.granted_by_id)
return ("ask", (verdict, policy.id if policy else None))
# Pure PolicyCheck and Hub guards for Delegation Policy
defmodule Policy do
@enforce_keys [:id, :granted_by_id, :grantee_kind, :effect, :action, :resource,
:statement, :granted_at]
defstruct [:id, :granted_by_id, :request_id, :grantee_kind, :effect, :action, :resource,
:statement, :source_question_id, :replaces_id, :granted_at, :expires_at,
:revoked_at, :gate_rules, conditions: %{}, exceptions: []]
end
defmodule PolicyUse do
@enforce_keys [:id, :policy_id, :request_id, :actor_id, :resource, :facts, :summary, :used_at]
defstruct [:id, :policy_id, :request_id, :job_id, :actor_id, :question_id, :resource,
:facts, :summary, :used_at]
end
defmodule PolicyCheck do
def check(policies, attempt, now) do
fitting = Enum.filter(policies, &(in_force?(&1, now) and fits?(&1, attempt)))
reserving = Enum.filter(fitting, &(&1.effect == :reserve))
permitting = Enum.filter(fitting, &(&1.effect in [:allow, :decide]))
cond do
reserved = Enum.find(reserving, &applies?(&1, attempt.facts)) -> {:reserved, reserved}
unchecked = Enum.find(reserving, &(not known?(&1, attempt.facts))) -> {:unknown, unchecked}
policy = Enum.find(permitting, &applies?(&1, attempt.facts)) -> {:covered, policy}
true -> :not_covered
end
end
def in_force?(p, now) do
DateTime.compare(p.granted_at, now) != :gt and
is_nil(p.revoked_at) and
(is_nil(p.expires_at) or DateTime.compare(now, p.expires_at) == :lt)
end
defp fits?(p, a) do
p.grantee_kind in [a.actor_kind, :any_agent] and
p.request_id in [nil, a.request_id] and
p.action == a.action and
p.resource in [a.resource, "any"]
end
defp applies?(p, facts) do
known?(p, facts) and holds?(p.conditions, facts) and
not Enum.any?(p.exceptions, &holds?(&1, facts))
end
defp known?(p, facts) do
[p.conditions | p.exceptions]
|> Enum.flat_map(&Map.keys/1)
|> Enum.all?(&Map.has_key?(facts, &1))
end
defp holds?(wanted, facts),
do: Enum.all?(wanted, fn {k, v} -> Map.fetch(facts, k) == {:ok, v} end)
end
defmodule PolicyHub do
def grant(state, %Policy{} = p, grantor_kind) do
cond do
grantor_kind != :human ->
{:error, :only_requester_may_grant}
p.effect in [:allow, :decide] and is_nil(p.expires_at) ->
{:error, :expiry_required}
p.effect == :decide and p.grantee_kind != :lead_agent ->
{:error, :decide_requires_lead_agent}
(p.effect == :gate) != not is_nil(p.gate_rules) ->
{:error, :gate_rules_mismatch}
true ->
{:ok, %{state | policies: [p | state.policies]}}
end
end
def attempt(state, attempt, now, act) do
case PolicyCheck.check(state.policies, attempt, now) do
{:covered, policy} ->
use = %PolicyUse{
id: attempt.id, policy_id: policy.id, request_id: attempt.request_id,
job_id: attempt[:job_id], actor_id: attempt.actor_id,
question_id: attempt[:question_id], resource: attempt.resource,
facts: attempt.facts, summary: attempt.summary, used_at: now
}
{:ok, act.(use), %{state | uses: [use | state.uses]}}
{:reserved, policy} -> {:ask_requester, policy.granted_by_id, state}
{:unknown, _policy} -> {:ask, state}
:not_covered -> {:ask, state}
end
end
end
Execution trace
Walking Example 2 (Acme API pre-release bug-fix merges) through these
guards shows grant validation, a covered merge writing use_1,
a schema exception, post-expiry rejection, and a reservation blocking an
allow policy when a fact is missing:
1. hub.grant(pol_merge_api, grantorKind: "agent")
-> error: only_requester_may_grant (agents can propose policies, never grant them)
2. hub.grant({ ...pol_merge_api, effect: "allow", expiresAt: null }, grantorKind: "human")
-> error: expiry_required (every allow or decide policy must have an end date)
3. hub.grant(pol_merge_api, grantorKind: "human")
-> ok (allow merge_pull_request on "acme/api" if bug_fix & checker_approved, except changes_schema, ends Fri 17:00Z)
4. # Thursday 10:20Z — PR 412 (bug_fix, checker_approved=true, changes_schema=false)
hub.attempt(attempt_pr_412, new Date("2026-11-19T10:20:00Z"), mergeFn)
-> { status: "ok", useId: "use_1", result: "merged PR 412 under pol_merge_api" }
5. # Thursday 14:00Z — PR 415 (changes_schema=true hits exception)
hub.attempt(attempt_pr_415_schema, new Date("2026-11-19T14:00:00Z"), mergeFn)
-> { status: "ask", reason: "not_covered", policyId: null } (no merge executed; no Policy use written)
6. # Saturday 09:30Z — PR 421 after Friday 17:00Z expiry
hub.attempt(attempt_pr_421, new Date("2026-11-21T09:30:00Z"), mergeFn)
-> { status: "ask", reason: "not_covered", policyId: null } (policy expired; requester asked & offered renewal)
7. # Reserving policy on payment_code=true with fact missing from hub records:
hub.grant(pol_reserve_payment, grantorKind: "human")
hub.attempt(attempt_pr_412_no_payment_fact, new Date("2026-11-19T10:30:00Z"), mergeFn)
-> { status: "ask", reason: "unknown", policyId: "pol_reserve_payment" } (missing reservation fact blocks allow)
Tradeoffs and practical guidance
Delegation Policy removes repetitive interruptions and outlives disposable agent sessions, but it shifts risk from interruption fatigue to rule design:
- Broad policies hide unexpected edge cases: one overly permissive rule can authorize a costly mistake that outweighs dozens of saved questions. Keep scopes narrow, require explicit expiry dates, and always pair with Decision Audit.
- Policy sprawl takes tending: overlapping, expired, or stale policies add cognitive load. Show the requester a concise list of active policies with usage counts and flag overlaps at grant time.
- Fewer questions prove nothing on their own: a quiet inbox could reflect healthy delegation or silent misbehavior; only auditing sampled uses tells the two apart.
Practical implementation notes
-
Keep the action vocabulary short and fixed: tie each
actioncode directly to one hub tool call where possible. Fordecidepolicies where the lead agent classifies its own judgment, review those uses more closely in Decision Audit. - Show parsed conditions back in one sentence: when the requester states a policy in plain language, display the exact structured scope, exceptions, and expiry back to her before activating it.
- Treat missing facts as "ask": if the hub cannot verify a condition from its own durable state, never let the agent fill in the fact on its own behalf.
- Separate step permission from final acceptance: letting a lead agent merge or publish an intermediate step does not mean it may accept the whole finished request for the requester — keep final acceptance reserved unless explicitly delegated.
Known uses and related patterns
- Claude Code permission rules: stores durable allow, ask, and deny rules for tool calls across sessions so choosing "Yes, and don't ask again" scopes future runs in that repository.
-
Unix
sudo(sudoers): scopes delegated commands to specific users and hosts, supports time-bounded credentials and password waivers, and logs every authorized and denied attempt. - Open Policy Agent (OPA): evaluates declarative policies against structured input facts and emits decision logs recording the policy bundle revision, inputs, and outcome for later replay.
- LangChain human-in-the-loop middleware: inspects tool-call arguments to either execute automatically or pause for human approval based on configured rules.
- Volgenic: enforces repository-level merge and shipping rules and time-bounded approval grants in the hub so agents act within explicit standing boundaries.
-
Contrast with XACML PDP/PEP:
PolicyCheckacts as the Policy Decision Point and the hub's atomic executor acts as the Policy Enforcement Point, adding human-authored plain-language statements, mandatory expiry on permissive rules, and immutablePolicy usereceipts.
Related patterns
- Escalation Chain — checks reserving policies first, applies
allowpolicies at stop 2, and usesdecidepolicies to define the lead agent's scope at stop 3. - Decision Audit — samples logged policy uses so the requester can widen, narrow, or revoke policies based on real verdicts.
- Policy Gate — enforces guarded transitions using the ordered rules stored in a policy with
effect = 'gate', writing aGate decisionrather than aPolicy use. - Orchestrator-Workers — defines the
PartyandRequestrecords referenced by policies and policy uses. - Tracked Answer — turns a recurring human reply ("do this every time") into a durable
Policyviasource_question_id. - Durable Job & Self-Contained Question — define the
JobandQuestionrecords linked by aPolicy use.