Policy Gate
When an agent reviewer replies "Approved," it is tempting to treat that word as a green light to merge code, send a customer announcement, or trigger a payout. Yet "Approved" quietly blurs two very different things: what the reviewer actually checked, and whether the team's rules permit taking an irreversible step.
Policy Gate separates inspection from permission. Each checker records a structured finding — naming the exact version it examined, the method it used, what it left out, and any problems found — while a separate policy reads those findings and decides whether a guarded step may proceed, must go back for repair, needs another kind of evidence, or requires the requester's approval. Reach for it whenever a step is hard to undo and different checks prove different things.
Finding, Gate decision
Why "Approved" from two reviewers isn't enough
Across engineering, operations, finance, and publishing, teams routinely place a reviewer agent in front of high-stakes actions — merging a pull request, publishing pricing copy, issuing refunds, or shipping a configuration change. When two reviewers inspect the work and both reply "Approved," the lead agent naturally concludes the change is safe.
Two quiet failures hide behind that single word. First, observation and permission get tangled together: a checker meant "I read the draft and noticed no flaws," while the lead heard "you are cleared to ship." Second, duplicate checks create a false sense of rigor: two checkers who both merely read a draft or diff share the exact same blind spot — neither actually exercised the live behavior, reconciled the source numbers, or checked edge-case timing.
Policy Gate untangles the two halves with three system-enforced rules:
-
Checkers report facts, never permission. Every check writes an immutable
Findingnaming the exact version examined, the method used (read,tested, orobserved), what was left out, and any problems found. -
A stored policy decides what happens next. An ordered list of rules
evaluates the active findings for that version — counting distinct methods once — and
produces one of four outcomes:
proceed,repair,more_evidence, orneeds_approval. -
The Hub executes the guarded step itself. Only the hub runs the
irreversible action, and only when the latest decision is
proceedfor the exact version currently on offer.
Why evaluate rules as data instead of editing checker prompts? When risk changes — say a team tightens rules for billing changes or external customer emails — updating one ordered policy immediately governs every job without rewriting a single checker's instructions, and every past decision remains replayable from its stored inputs.
Architecture and participants
In a Policy Gate, the Hub acts as both the policy
decision point and the enforcement point. Checkers write typed
Finding records, the requester maintains the ordered
Policy, and the hub writes an immutable
Gate decision each time a guarded step is requested or new
evidence arrives. The requester is asked last — only after all automated and checker
findings for that version are clean — so human attention is never wasted reviewing broken
work.
proceed decision for the exact version allows the hub to
execute the guarded step; all other outcomes route back to workers, checkers, or the
requester.
Policy rules for high-stakes steps
and supplies explicit approval when a rule returns
needs_approval.
Finding and
Gate decision records, evaluates policies
deterministically, holds credentials for guarded steps, and blocks stale versions.
more_evidence rulings to
dispatch the missing kind of check, and routes repair
findings back to the worker.
repair decision. Never checks its own output or runs
guarded steps directly.
must
or should problems.
Execution flow
Toggle between the normal progression — where the policy evaluates three times as missing
evidence and requester approval arrive for version v1 —
and the stale-version path — where a late edit supersedes v1
while approval is waiting, invalidating the old approval automatically.
Each evaluation writes a new immutable decision. Decision 1 catches the missing
tested method, Decision 2 asks the requester only once
findings are clean, and Decision 3 permits the hub to run the guarded step on
v1.
Begins after Gate decision 2 opens an approval question for version v1.
When the worker pushes version v2 while approval is
pending, the requester's approval of v1 permits
nothing. The hub refuses execution with stale_version,
requires fresh checks on v2, and routes any
must problem back for repair.
Concrete examples
Policy Gate applies to any irreversible transition — publishing communications, disbursing funds, releasing infrastructure, or merging code — wherever different verification methods catch different classes of mistakes.
Example 1 — Sending a quarterly customer pricing update
No code or unit tests- Guarded step
- Send the Q4 pricing announcement email to 10,000 active accounts (revision
draft-4). - Policy rules
-
(1) Any
mustproblem →repair; (2) Missingtestedfinding (numbers reconciled against live billing rates) →more_evidence; (3) External customer send without requester sign-off →needs_approval; (4) Default →proceed. - What the gate catches
-
Two editorial checkers both proofread
draft-4(method: "read") and find zero typos. Because both usedread, Rule 2 firesmore_evidence: ["tested"]. A finance checker then reconciles the draft against the live billing table, catches an outdated annual discount figure, and logs amustproblem — routing the draft back to the writer before the requester is ever bothered.
Example 2 — Payment webhook retry fix
Payments & merges- Guarded step
- Merge a fix stopping duplicate payment webhook notices when a customer's server times out (commit
4f2a). - Policy rules
-
(1)
must_fix >= 1→repair; (2)methodslackstested→more_evidence; (3)payment_code == trueand not approved →needs_approval; (4) Default →proceed. - What the gate catches
-
Checkers A and B both read commit
4f2aand find no issues, noting they did not run a timeout delivery. Rule 2 blocks the merge and asks for atestedfinding. Once Checker B runs a simulated timeout and passes, Rule 3 opens one approval question for the requester with both findings attached. If the worker pushes a tidy-up commit9c1ebefore merge, the hub rejects merging9c1eunder4f2a's decision withstale_version.
What this pattern is NOT — Internal scratch drafts
Negative example- Action
- Saving internal meeting notes to a team scratchpad or renaming a private draft file.
- Why skip it
- The step is cheap to undo, reaches nobody outside the team, and has no independent checkers examining it first. Placing a Policy Gate with nothing to read only inserts bureaucracy without reducing risk.
When to use and when to skip
Use Policy Gate when
- A transition is hard to undo or externally visible — merging code, deploying to production, spending funds, or messaging customers.
- Multiple checks (reading, live execution, production observation, or human review) prove different properties and cannot substitute for one another.
- The requester wants to tighten or relax rules for a specific risk class without rewriting checker prompts.
- Auditability matters: anyone inspecting a shipped action later must see which rule and which exact findings allowed it.
Skip it when
- The action is cheap and reversible and nobody inspects the work before taking it.
- One person inspects every artifact themselves and immediately executes the step — their inspection and decision are already unified.
- The system cannot hold credentials at the hub, leaving agents free to bypass the gate anyway.
- Work products have no stable version identifier to bind findings and approvals against.
Data model and hub invariants
Policy Gate defines two append-only tables — findings and
gate_decisions — referencing
jobs, parties,
policies (whose gate_rules
hold the ordered rules with effect = 'gate'), and
questions.
Finding and Gate decision
anchor every check and ruling to an exact version and
job_id. Cardinality markers follow catalog convention
(1, 1?,
n).
Table: findings
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Immutable finding identifier. |
| job_id | uuid | NOT NULL, FK | References jobs(id); job whose deliverable was examined. |
| checker_id | uuid | NOT NULL, FK | References parties(id); never the worker that produced the version. |
| version | text | NOT NULL | Exact version examined (commit SHA, artifact digest, or document revision). |
| method | text | NOT NULL | CHECK (method IN ('read', 'tested', 'observed')). |
| examined | text | NOT NULL | One sentence naming what the checker inspected or executed. |
| not_examined | text | NULLABLE | Explicit blind spots left out of this examination. |
| problems | jsonb | NOT NULL | Array of {severity: "must"|"should", where, text}; [] when clean. |
| recorded_at | timestamptz | NOT NULL | Defaults to now(). |
| voided_at | timestamptz | NULLABLE | Set once when an upstream change invalidates the finding; NULL while active. |
Table: gate_decisions
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Immutable decision identifier. |
| job_id | uuid | NOT NULL, FK | References jobs(id). |
| step | text | NOT NULL | Guarded step kind, e.g., merge, release, send. |
| version | text | NOT NULL | Exact version evaluated by this decision. |
| policy_id | uuid | NOT NULL, FK | References policies(id) with effect = 'gate'. |
| rule | text | NOT NULL | Name of the first rule whose conditions matched (e.g., merge.untested). |
| outcome | text | NOT NULL | CHECK (outcome IN ('proceed', 'repair', 'more_evidence', 'needs_approval')). |
| missing | jsonb | NOT NULL | Methods still required (e.g., ["tested"]); empty unless more_evidence. |
| inputs | jsonb | NOT NULL | Exact snapshot of named values read by the policy so decisions replay deterministically. |
| decided_at | timestamptz | NOT NULL | Defaults to now(). |
| question_id | uuid | NULLABLE, FK | References questions(id); set for needs_approval and the follow-up decision reading its answer. |
| finding_ids | jsonb | NOT NULL | Array of active Finding IDs read during evaluation. |
Six hub invariants
-
01Finding content is immutable; voiding occurs at most once Database constraint
Once inserted, finding fields never change and hold no permission verdict. An upstream change may transition
voided_atfromNULLto a timestamp once (a repeat attempt fails withfinding_already_voided). -
02Methods, outcomes, and conditional columns are closed Database constraint
CHECKconstraints restrictfindings.methodtoread | tested | observed,gate_decisions.outcometo the four valid outcomes, and requirequestion_id IS NOT NULLwhenoutcome = 'needs_approval'andmissing = '[]'unlessoutcome = 'more_evidence'. -
03Checkers cannot examine their own produced work Hub guard
record_findingverifieschecker_id != job.assignee_id, rejecting self-reviews withchecker_cannot_be_producer. -
04Decisions read only active findings and approvals for the exact version Hub guard
evaluate_gatefilters findings strictly byjob_id,version, andvoided_at IS NULL(deduplicatingmethods), and derivesapprovedsolely from requester approvals recorded for that exact(job_id, step, version)viarecord_approval(which rejects non-requesters withonly_requester_may_approve). -
05Policy must be a gate policy with deterministic first-match rules Hub guard
evaluate_gaterejects non-gate policies withinvalid_gate_policyand incomplete rule sets withno_matching_rule. Storinginputsensures the same rules and inputs always reproduce the same outcome. -
06Guarded steps run only under the latest proceed decision for the live version Hub guard
run_guarded_stepverifies atomically that a decision exists (no_gate_decision), matches the current version (stale_version), and has outcomeproceed(gate_not_proceed).
Reference implementation
The same minimal hub guards in Lean, TypeScript, Python, and Elixir. Notice that checkers only submit findings, policies remain pure first-match rules over deduplicated methods, and the hub enforces version pinning right where the guarded step runs.
-- Hub guards for Policy Gate (findings and version-bound approvals stay separate from policy)
import Std.Data.HashMap
open Std
inductive Method where
| read | tested | observed
deriving Repr, BEq, DecidableEq
inductive Outcome where
| proceed | repair | moreEvidence | needsApproval
deriving Repr, BEq, DecidableEq
inductive Severity where
| must | should
deriving Repr, BEq
inductive Effect where
| gate | delegate
deriving Repr, BEq
structure Problem where
severity : Severity
«where» : String -- «» lets a keyword be a field name
text : String
deriving Repr
structure Job where
id : String
assigneeId : String
requesterId : String
deriving Repr
structure Finding where
id : String
jobId : String
checkerId : String
version : String
method : Method
problems : List Problem := []
voidedAt : Option String := none
deriving Repr
structure Approval where
jobId : String
step : String
version : String
approvedById : String
deriving Repr
-- What a rule sees: the caller's facts plus what the hub derived from findings and approvals.
structure GateInputs where
facts : HashMap String Bool
methods : List Method
mustFix : Nat
approved : Bool
structure GateRule where
id : String
«when» : GateInputs → Bool
«then» : Outcome
missing : List Method := []
structure Policy where
id : String
effect : Effect
rules : List GateRule
structure GateDecision where
id : String
jobId : String
step : String
version : String
policyId : String
rule : String
outcome : Outcome
missing : List Method
findingIds : List String
deriving Repr
inductive HubError where
| unknownJob | checkerCannotBeProducer | onlyRequesterMayApprove | unknownFinding
| findingAlreadyVoided | invalidGatePolicy | noMatchingRule | noGateDecision
| staleVersion | gateNotProceed
deriving Repr, BEq
structure PolicyGateHub where
jobs : HashMap String Job := {}
findings : List Finding := []
approvals : List Approval := []
decisions : List GateDecision := [] -- newest first
namespace PolicyGateHub
def getJob (hub : PolicyGateHub) (jobId : String) : Except HubError Job :=
match hub.jobs[jobId]? with
| some job => pure job
| none => throw .unknownJob
def recordFinding (hub : PolicyGateHub) (f : Finding) :
Except HubError (Finding × PolicyGateHub) := do
let job ← hub.getJob f.jobId
if f.checkerId == job.assigneeId then throw .checkerCannotBeProducer
let stored := { f with voidedAt := none }
pure (stored, { hub with findings := stored :: hub.findings })
def recordApproval (hub : PolicyGateHub) (jobId step version actorId : String) :
Except HubError (Approval × PolicyGateHub) := do
let job ← hub.getJob jobId
unless actorId == job.requesterId do throw .onlyRequesterMayApprove
let approval : Approval := { jobId, step, version, approvedById := actorId }
pure (approval, { hub with approvals := approval :: hub.approvals })
-- (`at` is a Lean keyword, so the timestamp parameter is named voidedAt)
def voidFinding (hub : PolicyGateHub) (findingId voidedAt : String) :
Except HubError PolicyGateHub := do
let some f := hub.findings.find? (·.id == findingId) | throw .unknownFinding
if f.voidedAt.isSome then throw .findingAlreadyVoided
let voided := hub.findings.map fun row =>
if row.id == findingId then { row with voidedAt := some voidedAt } else row
pure { hub with findings := voided }
def evaluateGate (hub : PolicyGateHub) (jobId step version : String) (policy : Policy)
(facts : HashMap String Bool) : Except HubError (GateDecision × PolicyGateHub) := do
unless hub.jobs.contains jobId do throw .unknownJob
unless policy.effect == .gate do throw .invalidGatePolicy
let active := hub.findings.filter fun f =>
f.jobId == jobId && f.version == version && f.voidedAt.isNone
let methods := (active.map (·.method)).eraseDups
let mustFix := active.countP fun f => f.problems.any (·.severity == .must)
let approved := hub.approvals.any fun a =>
a.jobId == jobId && a.step == step && a.version == version
let inputs : GateInputs := { facts, methods, mustFix, approved }
let some rule := policy.rules.find? (·.when inputs) | throw .noMatchingRule
let decision : GateDecision := {
id := s!"dec_{hub.decisions.length + 1}"
jobId, step, version, policyId := policy.id
rule := rule.id, outcome := rule.then, missing := rule.missing
findingIds := active.map (·.id)
}
pure (decision, { hub with decisions := decision :: hub.decisions })
def runGuardedStep (hub : PolicyGateHub) (jobId step currentVersion : String) :
Except HubError GateDecision := do
-- decisions are newest first, so find? returns the latest one for this step
let some latest := hub.decisions.find? (fun d => d.jobId == jobId && d.step == step)
| throw .noGateDecision
if latest.version != currentVersion then throw .staleVersion
unless latest.outcome == .proceed do throw .gateNotProceed
pure latest
end PolicyGateHub
// Hub guards for Policy Gate (findings and version-bound approvals stay separate from policy)
type Method = "read" | "tested" | "observed";
type Outcome = "proceed" | "repair" | "more_evidence" | "needs_approval";
type Problem = { severity: "must" | "should"; where: string; text: string };
interface Finding {
id: string;
jobId: string;
checkerId: string;
version: string;
method: Method;
problems: Problem[];
voidedAt: string | null;
}
interface Approval {
jobId: string;
step: string;
version: string;
approvedById: string;
}
interface GateRule {
id: string;
when: (inputs: Record<string, unknown>) => boolean;
then: Outcome;
missing?: Method[];
}
interface Policy {
id: string;
effect: "gate" | "delegate";
rules: GateRule[];
}
interface GateDecision {
id: string;
jobId: string;
step: string;
version: string;
policyId: string;
rule: string;
outcome: Outcome;
missing: Method[];
findingIds: string[];
}
class PolicyGateHub {
private jobs = new Map<string, { id: string; assigneeId: string; requesterId: string }>();
private findings: Finding[] = [];
private approvals: Approval[] = [];
private decisions: GateDecision[] = [];
recordFinding(f: Omit<Finding, "voidedAt">): Finding {
const job = this.jobs.get(f.jobId);
if (!job) throw new Error("unknown_job");
if (f.checkerId === job.assigneeId) throw new Error("checker_cannot_be_producer");
const stored: Finding = { ...f, voidedAt: null };
this.findings.push(stored);
return stored;
}
recordApproval(jobId: string, step: string, version: string, actorId: string): Approval {
const job = this.jobs.get(jobId);
if (!job) throw new Error("unknown_job");
if (actorId !== job.requesterId) throw new Error("only_requester_may_approve");
const approval: Approval = { jobId, step, version, approvedById: actorId };
this.approvals.push(approval);
return approval;
}
voidFinding(findingId: string, at: string): void {
const f = this.findings.find((row) => row.id === findingId);
if (!f) throw new Error("unknown_finding");
if (f.voidedAt !== null) throw new Error("finding_already_voided");
f.voidedAt = at;
}
evaluateGate(
jobId: string,
step: string,
version: string,
policy: Policy,
facts: Record<string, unknown>
): GateDecision {
if (!this.jobs.has(jobId)) throw new Error("unknown_job");
if (policy.effect !== "gate") throw new Error("invalid_gate_policy");
const active = this.findings.filter(
(f) => f.jobId === jobId && f.version === version && f.voidedAt === null
);
const methods = [...new Set(active.map((f) => f.method))];
const mustFix = active.filter((f) => f.problems.some((p) => p.severity === "must")).length;
const approved = this.approvals.some(
(a) => a.jobId === jobId && a.step === step && a.version === version
);
const inputs = { ...facts, methods, mustFix, approved };
const match = policy.rules.find((r) => r.when(inputs));
if (!match) throw new Error("no_matching_rule");
const decision: GateDecision = {
id: `dec_${this.decisions.length + 1}`,
jobId, step, version, policyId: policy.id,
rule: match.id, outcome: match.then,
missing: match.missing ?? [],
findingIds: active.map((f) => f.id)
};
this.decisions.push(decision);
return decision;
}
runGuardedStep(jobId: string, step: string, currentVersion: string): GateDecision {
const latest = [...this.decisions].reverse().find((d) => d.jobId === jobId && d.step === step);
if (!latest) throw new Error("no_gate_decision");
if (latest.version !== currentVersion) throw new Error("stale_version");
if (latest.outcome !== "proceed") throw new Error("gate_not_proceed");
return latest;
}
}
# Hub guards for Policy Gate (findings and version-bound approvals stay separate from policy)
from dataclasses import dataclass, field
from typing import Any, Callable, Literal, Optional
Method = Literal["read", "tested", "observed"]
Outcome = Literal["proceed", "repair", "more_evidence", "needs_approval"]
@dataclass
class Job:
id: str
assignee_id: str
requester_id: str
@dataclass
class Finding:
id: str
job_id: str
checker_id: str
version: str
method: Method
problems: list[dict[str, str]] = field(default_factory=list)
voided_at: Optional[str] = None
@dataclass
class Approval:
job_id: str
step: str
version: str
approved_by_id: str
@dataclass
class GateRule:
id: str
when: Callable[[dict[str, Any]], bool]
then: Outcome
missing: list[Method] = field(default_factory=list)
@dataclass
class Policy:
id: str
effect: Literal["gate", "delegate"]
rules: list[GateRule]
@dataclass
class GateDecision:
id: str
job_id: str
step: str
version: str
policy_id: str
rule: str
outcome: Outcome
missing: list[Method]
finding_ids: list[str]
class HubError(Exception):
pass
class PolicyGateHub:
def __init__(self) -> None:
self.jobs: dict[str, Job] = {}
self.findings: list[Finding] = []
self.approvals: list[Approval] = []
self.decisions: list[GateDecision] = []
def record_finding(self, finding: Finding) -> Finding:
job = self.jobs.get(finding.job_id)
if job is None:
raise HubError("unknown_job")
if finding.checker_id == job.assignee_id:
raise HubError("checker_cannot_be_producer")
self.findings.append(finding)
return finding
def record_approval(self, job_id: str, step: str, version: str, actor_id: str) -> Approval:
job = self.jobs.get(job_id)
if job is None:
raise HubError("unknown_job")
if actor_id != job.requester_id:
raise HubError("only_requester_may_approve")
approval = Approval(job_id=job_id, step=step, version=version, approved_by_id=actor_id)
self.approvals.append(approval)
return approval
def void_finding(self, finding_id: str, at: str) -> None:
match = next((f for f in self.findings if f.id == finding_id), None)
if match is None:
raise HubError("unknown_finding")
if match.voided_at is not None:
raise HubError("finding_already_voided")
match.voided_at = at
def evaluate_gate(
self, job_id: str, step: str, version: str, policy: Policy, facts: dict[str, Any]
) -> GateDecision:
if job_id not in self.jobs:
raise HubError("unknown_job")
if policy.effect != "gate":
raise HubError("invalid_gate_policy")
active = [
f for f in self.findings
if f.job_id == job_id and f.version == version and f.voided_at is None
]
methods = list(dict.fromkeys(f.method for f in active))
must_fix = sum(
1 for f in active if any(p["severity"] == "must" for p in f.problems)
)
approved = any(
a.job_id == job_id and a.step == step and a.version == version
for a in self.approvals
)
inputs = {**facts, "methods": methods, "must_fix": must_fix, "approved": approved}
rule = next((r for r in policy.rules if r.when(inputs)), None)
if rule is None:
raise HubError("no_matching_rule")
decision = GateDecision(
id=f"dec_{len(self.decisions) + 1}",
job_id=job_id, step=step, version=version, policy_id=policy.id,
rule=rule.id, outcome=rule.then, missing=list(rule.missing),
finding_ids=[f.id for f in active],
)
self.decisions.append(decision)
return decision
def run_guarded_step(self, job_id: str, step: str, current_version: str) -> GateDecision:
matching = [d for d in self.decisions if d.job_id == job_id and d.step == step]
if not matching:
raise HubError("no_gate_decision")
latest = matching[-1]
if latest.version != current_version:
raise HubError("stale_version")
if latest.outcome != "proceed":
raise HubError("gate_not_proceed")
return latest
# Hub guards for Policy Gate (pure functional core)
defmodule PolicyGateHub do
defstruct jobs: %{}, findings: [], approvals: [], decisions: []
def record_finding(%PolicyGateHub{} = hub, finding) do
with {:ok, job} <- Map.fetch(hub.jobs, finding.job_id) |> or_error(:unknown_job),
true <- finding.checker_id != job.assignee_id || {:error, :checker_cannot_be_producer} do
stored = Map.put(finding, :voided_at, nil)
{:ok, stored, %{hub | findings: [stored | hub.findings]}}
end
end
def record_approval(%PolicyGateHub{} = hub, job_id, step, version, actor_id) do
with {:ok, job} <- Map.fetch(hub.jobs, job_id) |> or_error(:unknown_job),
true <- actor_id == job.requester_id || {:error, :only_requester_may_approve} do
approval = %{job_id: job_id, step: step, version: version, approved_by_id: actor_id}
{:ok, approval, %{hub | approvals: [approval | hub.approvals]}}
end
end
def void_finding(%PolicyGateHub{} = hub, finding_id, at) do
case Enum.find(hub.findings, &(&1.id == finding_id)) do
nil ->
{:error, :unknown_finding}
%{voided_at: prev} when not is_nil(prev) ->
{:error, :finding_already_voided}
_finding ->
updated =
Enum.map(hub.findings, fn
%{id: ^finding_id} = f -> %{f | voided_at: at}
other -> other
end)
{:ok, %{hub | findings: updated}}
end
end
def evaluate_gate(%PolicyGateHub{} = hub, job_id, step, version, policy, facts) do
with true <- Map.has_key?(hub.jobs, job_id) || {:error, :unknown_job},
true <- policy.effect == :gate || {:error, :invalid_gate_policy} do
active =
Enum.filter(hub.findings, fn f ->
f.job_id == job_id and f.version == version and is_nil(f.voided_at)
end)
methods = active |> Enum.map(& &1.method) |> Enum.uniq()
must_fix = Enum.count(active, fn f -> Enum.any?(f.problems, &(&1.severity == :must)) end)
approved = Enum.any?(hub.approvals, &(&1.job_id == job_id and &1.step == step and &1.version == version))
inputs = Map.merge(facts, %{methods: methods, must_fix: must_fix, approved: approved})
case Enum.find(policy.rules, fn r -> r.when.(inputs) end) do
nil ->
{:error, :no_matching_rule}
rule ->
decision = %{
id: "dec_#{length(hub.decisions) + 1}",
job_id: job_id, step: step, version: version, policy_id: policy.id,
rule: rule.id, outcome: rule.then, missing: Map.get(rule, :missing, []),
finding_ids: Enum.map(active, & &1.id)
}
{:ok, decision, %{hub | decisions: [decision | hub.decisions]}}
end
end
end
def run_guarded_step(%PolicyGateHub{} = hub, job_id, step, current_version) do
case Enum.find(hub.decisions, &(&1.job_id == job_id and &1.step == step)) do
nil -> {:error, :no_gate_decision}
%{version: v} when v != current_version -> {:error, :stale_version}
%{outcome: :proceed} = decision -> {:ok, decision}
_other -> {:error, :gate_not_proceed}
end
end
defp or_error({:ok, val}, _err), do: {:ok, val}
defp or_error(:error, err), do: {:error, err}
end
Evaluation and stale-version trace
Walking Example 2 (payment webhook retry fix) through these guards shows
how duplicate read findings trigger
more_evidence and how a late commit triggers
stale_version:
1. hub.recordFinding(f_read_a, job_webhook_fix, checker_a, "4f2a", "read", [])
hub.recordFinding(f_read_b, job_webhook_fix, checker_b, "4f2a", "read", [])
-> ok (two read findings stored; distinct methods = ["read"])
2. hub.evaluateGate(job_webhook_fix, "merge", "4f2a", policy_payment_merge, { paymentCode: true })
-> outcome: "more_evidence" (rule: "merge.untested", missing: ["tested"])
hub.runGuardedStep(job_webhook_fix, "merge", "4f2a")
-> error: gate_not_proceed (hub refuses merge)
3. hub.recordFinding(f_test_c, job_webhook_fix, checker_b, "4f2a", "tested", [])
hub.evaluateGate(job_webhook_fix, "merge", "4f2a", policy_payment_merge, { paymentCode: true })
-> outcome: "needs_approval" (rule: "merge.payment_code"; approved=false, opens question for "4f2a")
4. // Requester approves "4f2a", while Worker pushes tidy commit "9c1e"
hub.recordApproval(job_webhook_fix, "merge", "4f2a", requester_dana)
hub.evaluateGate(job_webhook_fix, "merge", "4f2a", policy_payment_merge, { paymentCode: true })
-> outcome: "proceed" (bound strictly to "4f2a")
hub.runGuardedStep(job_webhook_fix, "merge", "9c1e")
-> error: stale_version ("4f2a" decision cannot merge current commit "9c1e")
5. hub.recordFinding(f_test_d, job_webhook_fix, checker_b, "9c1e", "tested", [])
hub.evaluateGate(job_webhook_fix, "merge", "9c1e", policy_payment_merge, { paymentCode: true })
-> outcome: "needs_approval" (rule: "merge.payment_code"; "4f2a" approval ignored, approved=false for "9c1e")
6. hub.recordApproval(job_webhook_fix, "merge", "9c1e", requester_dana)
hub.evaluateGate(job_webhook_fix, "merge", "9c1e", policy_payment_merge, { paymentCode: true })
-> outcome: "proceed" (rule: "merge.default", approved=true for "9c1e", findingIds: [f_test_d])
hub.runGuardedStep(job_webhook_fix, "merge", "9c1e")
-> ok (hub merges exact commit "9c1e")
Tradeoffs and practical guidance
Policy Gate trades a small amount of policy authoring and wait latency for verifiable, auditable control over irreversible transitions. Weigh three practical costs before adding a gate:
-
Policies become production logic: an overly strict rule stalls every
job, while a buggy catch-all rule lets unverified work straight through. Version policies
and dry-run rule changes against stored historical
inputsbefore activating them. -
Self-reported method honesty: the gate can require a
testedfinding, but if a checker labels a pure reading pass astested, the gate is fooled. Pair method labels with concrete artifacts (execution logs, reconciliation outputs, or replay traces). - Wait time on strict gates: every guarded step pauses until findings arrive, and jobs that loop repeatedly on a strict rule need a clear path to escalate to the requester.
Practical implementation notes
- Hold credentials at the hub: if a worker or lead agent can merge, send, or deploy with its own credentials, the Policy Gate is only polite advice.
- Pass the version into the external action: when calling downstream APIs (for example, GitHub's expected head SHA on merge), pass the evaluated version so the target system also rejects races atomically.
- Keep the rule language small and closed: an ordered first-match list ending in a mandatory default rule stays easy to audit and impossible to fall off the end of. Treat a check that never ran as missing evidence, never as clean.
- Withdraw stale approval questions immediately: the moment a new version replaces the version under review, supersede any open approval question so the requester never wastes time approving obsolete work.
Known uses and related patterns
-
SonarQube quality gates: measures code analysis metrics against a
stored set of pass/fail conditions before permitting merge; Policy Gate extends this with
method-typed findings,
more_evidence, and conditional human approval. - GitHub protected branches: combines required reviews, passing status checks, and automatic dismissal of stale approvals when a new commit pushes to the head of a pull request.
- Azure Pipelines deployment approvals and checks: lets resource owners attach ordered checks and human approvals to production environments before a stage may run.
- LangGraph interrupts & OpenAI Agents SDK: pause runs when a tool call needs human approval; Policy Gate determines from versioned findings whether that approval is required in the first place.
- XACML & Open Policy Agent (PDP / PEP): classic security architecture separating the Policy Decision Point (the gate evaluator) from the Policy Enforcement Point (the hub executing the guarded step).
- Volgenic: evaluates versioned JSON policies before routing asks to humans and binds pull-request merges to the exact reviewed commit.
Related patterns
- Delegation Policy — stores the requester's standing rules in advance; Policy Gate is where
gaterules are applied to checker findings. - Evidence-Backed Completion — uses a
Findingto support acheckedcompletion claim, whereas Policy Gate permits or blocks one specific step. - Decision Audit — reviews past autonomous decisions;
proceedgate decisions made without asking the requester feed directly into audits. - Self-Contained Question & Tracked Answer — package the
needs_approvalquestion with the version and findings, and route the requester's reply back to re-evaluate the gate. - Durable Job, Orchestrator-Workers, & Change Propagation — define
JobandParty, and void findings when upstream changes overtake active work.