CommunityCodierung & Entwicklunggithub.com

governance-agent

Use when defining, implementing or reviewing the governance rules of a product or AI agent - which actions with an effect outside the system need a gate, at which approval bands, who approves, who is informed, where each client approves and gets notified, and how to prove the rule was checked before the action; also to review a spec or pull request against those rules. Works in English and Portuguese (for Portuguese, read guia-pt.md). Trigger phrases (English) "governance", "approval rules", "who approves above", "nothing sent without confirmation", "human in the loop", "CEO approval", "approval gate", "approval audit trail", "review this PR against the approval rules". Trigger phrases (Portuguese) "governança", "alçada", "alçadas de aprovação", "quem aprova acima de", "nada enviado sem confirmação", "aprovação do CEO", "fluxo de aprovação", "aprovação humana", "limite de aprovação", "trilha de auditoria", "revisar spec contra a governança", "quem aprova isso?".

Was ist governance-agent?

governance-agent is a Claude Code agent skill that use when defining, implementing or reviewing the governance rules of a product or AI agent - which actions with an effect outside the system need a gate, at which approval bands, who approves, who is informed, where each client approves and gets notified, and how to prove the rule was checked before the action; also to review a spec or pull request against those rules. Works in English and Portuguese (for Portuguese, read guia-pt.md). Trigger phrases (English) "governance", "approval rules", "who approves above", "nothing sent without confirmation", "human in the loop", "CEO approval", "approval gate", "approval audit trail", "review this PR against the approval rules". Trigger phrases (Portuguese) "governança", "alçada", "alçadas de aprovação", "quem aprova acima de", "nada enviado sem confirmação", "aprovação do CEO", "fluxo de aprovação", "aprovação humana", "limite de aprovação", "trilha de auditoria", "revisar spec contra a governança", "quem aprova isso?".

Funktioniert mit✓Claude Code✓Codex CLI~Cursor✓Gemini CLI
npx skills add https://github.com/leandromaiam-code/governance-agent/tree/HEAD/governance-agent

Installed? Explore more Codierung & Entwicklung skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

governance-agent: define the rules, then build the gate

The real work is the definition. The gate code is small and always the same. So the order is fixed: first the onboarding produces the rules, then the implementation reads them. A spec or code without a rule doesn't pass.

The skill has three parts: the onboarding (Part 1), the gate in the code (Part 2) and the review of a spec or pull request against the rules (Part 3).

The definition has two layers:

LayerWho answersWhat it definesWhere it lives
Productthe product owner, oncecatalog of actions, default approval bands, the floor no client can loosengovernance/rules.json in the repo, by pull request
Clientthe admin of each client (tenant), at the start and whenever they want to changetheir bands (amounts and approvers), where they approve, which channel reaches each role, where and when each role is informedtable governance_config (one version per client, insert only)

A client with no configuration of its own uses the product defaults. No client configuration can go below the product floor.

Language

  • Talk and write the documents in the language the person writes in: English or Portuguese. If you can't tell, ask once: "English or Portuguese? / Inglês ou português?"
  • English: follow this file and write docs/GOVERNANCE.md.
  • Portuguese: read guia-pt.md (same folder, the same method in Portuguese), follow it and write docs/GOVERNANCA.md.
  • Code, JSON keys, table names and level codes are always in English, in both languages, so there is a single implementation. The code blocks live only in this file.

When to use

  • A new product or agent that will send, charge, pay, publish, delete or call a paid service.
  • A spec or PR rejected because it acts without confirmation, ignores a limit, mixes clients' data or sends something automatically.
  • Requests like "this needs approval", "it can't send on its own", "above $X the CEO approves".
  • A new client joining a product that already has rules.json (client layer only).

Part 1 — Onboarding

1.1 Inventory before asking

Don't ask what the code can answer. Scan the product repository and list every action with an effect outside the system:

# in the product repository
rg -n --no-heading -i \
  -e 'sendMessage|sendText|whatsapp|twilio' \
  -e 'sendEmail|resend|smtp|nodemailer|mailgun' \
  -e 'stripe\.(charges|paymentIntents|refunds|subscriptions|transfers|payouts)' \
  -e 'fetch\(|axios\.|got\(' \
  -e '\.delete\(|DELETE FROM|TRUNCATE|DROP ' \
  -e 'instagram|graph\.facebook|tiktok|publish' \
  -e 'openai|anthropic|gemini|elevenlabs' \
  src app lib api functions 2>/dev/null

No rg (ripgrep) installed? Use Claude's own search with the same patterns. Adjust the patterns and folders to the project's stack. For each finding, note: the action name (verb + object, e.g. pay_supplier), where it is (file:line), who triggers it (user, scheduled job, agent), what changes outside (message, money, public data, deleted data, cost) and what can be measured (amount in cents, quantity, number of recipients). The measure is what becomes the approval band.

Also read the rules and assumptions the project already has (CLAUDE.md, docs/, any rules file) so you don't contradict what was already decided.

1.2 The 4 levels

Every band falls into one of these levels:

LevelCodeWhat the gate does
Do without noticedoexecutes and records; nobody is notified
Do and informdo_and_informexecutes, records and notifies the informed roles afterwards
Ask for approval, then doapprove_then_dodoesn't execute; opens a request for the band's approvers; executes only after the approvals are recorded
Never donever_doalways refuses, even with approval, and records the refusal

1.3 Approval bands

An action doesn't have just one level: it has bands, ranges in increasing order of the measure. Each band defines:

FieldWhat it isExample
up_tothe band's ceiling in the measure (cents, quantity), inclusive. The last band has no ceiling, and only the last one500000 ($5,000.00)
levelone of the 4 levelsapprove_then_do
approversroles that can approve (any of them); a role is written role:<name> and comes from the product's own roles table["role:manager", "role:ceo"]
required_rolesroles that must be among the people who approved["role:ceo"]
min_approvalshow many different people must approve2
informroles notified after execution (also in approve_then_do)["role:finance"]
on_expirewhat happens if nobody approves in time: deny (default) or escalate to the next band's approvers. Escalating may change who approves (e.g. manager → CEO) but the next band can't ask for fewer approvals or drop a required roleescalate

The measure and the period belong to the action:

  • measure: amount_cents, quantity, recipients or none. An action with no measure has exactly one band. The measure is never assumed: it must be in data. For recipients, set measure_from to the list being sent to (e.g. "to") so the gate counts it instead of trusting a number; for amount_cents, set currency, since the bands are in one currency, and the gate refuses a request in another.
  • per: request (only the current request) or day / week / month (sum of the requests opened in the period that are allowed, executed or still waiting for approval, + the current one, read from the log). With per: month, ten payments of $1,000 count as $10,000, even while they wait for approval.

Example bands for pay_supplier:

BandLevelApprovesMinimumInformed
up to $1,000do and inform——finance (immediately)
up to $10,000approve, then domanager or CEO1finance
up to $100,000approve, then doCEO1finance, partners
aboveapprove, then doCEO + one partner (CEO required)2finance, partners

Product floor (in rules.json, per action), what no client can loosen:

  • min_level: no band of any client below this level. Order from loosest to strictest: do < do_and_inform < approve_then_do < never_do.
  • floor: a floor by value. Each entry { "from", "min_level", "min_approvals", "required_roles" } says that from that measured value up, every band of every client must be at least that level and, if it asks for approval, at least that many approvals with those roles required. Example: from $100,000.01 on, always two approvers including the CEO; more than 50 recipients, never.
  • The product's bands are only defaults: a client can replace them. Whatever must hold for every client goes in min_level, floor or never_global.
  • never_global (for the whole product): actions that are always never_do; no client can enable them. Only names of actions go here (e.g. delete_customer_data). Principles that aren't actions, like "no secrets in git" or "AI never calculates amounts", go in the project's rules and in Part 2, not here.

1.4 Where to approve and where to be informed (per client)

Fixed separation: approval happens on an authenticated screen; channels only call the person there.

  • Approval is a click on a screen with the approver's own session and role checked on the server, which records an approved row. A "YES" replied by WhatsApp or email never counts, and neither does a link that approves by itself: the link only opens the screen.
  • A notice never asks for an action; if it does, it's an approval.

Each client picks its own options. The product only defines which options it offers (client_defaults.options in rules.json) and the default.

Where to approve (the client picks one; can change per action):

OptionCodeNotes
The product's Approvals screenproductdefault for a product with clients; queue of requests showing what will be done, amount, who asked, band and deadline
The owner's internal panelinternalonly when the product is used just by the owner's own team, and decisions already go to a back-office or internal tool they use; the card there calls the product's approval endpoint as the approver. A product used only internally lists internal in options.approval; a product with outside clients leaves it out, so it doesn't appear in question C4
The client's own systemexternalwhen the client approves in its own system (ERP, portal): the product exposes an authenticated POST /governance/approve for that system to call with the approver's own token (per-user sign-in or delegated OAuth), never a service credential that approves on someone's behalf; the role check stays on the product's server

How to call each role (the client picks per role; each person can narrow it in their own settings, within what the client allowed):

ChannelCodeNotes
Push notificationpushthe product's web push
Badge on screenbadgepending counter in the menu; always on (the code adds it)
Emailemailsummary + link to the screen only
WhatsAppwhatsappsummary + link only
Slack / Teamsslack, teamsthe client's webhook; summary + link only

Reminder and deadline (per client, can change per action): reminder at remind_hours (default: half the deadline), through the same channels; after expire_hours (default 48 h), apply the band's on_expire and notify the requester. Expiry never approves anything.

Where and when to be informed (per client, per action or per role):

WhenCodeUse
Immediatelyimmediatelya relevant single action (payment, message to a customer)
Daily digestdaily_digesthigh volume, low risk
Weekly digestweekly_digestroutine

Where: the same channels as the call table (push, email, whatsapp, slack, teams) plus product (activity screen).

To call a role: the client's rule for the role, the client's default, the product's rule for the role, the product's default; the badge is always added.

To inform, precedence from first to last: the client's rule for the action, the client's rule for the role, the product's rule for the action, the product's rule for the role, the client's default, the product's default. So a client who only changes their default doesn't lose a per-action rule of the product (e.g. payments notified immediately) without noticing.

A failure to execute or to notify is not a notice: it goes to the error log / alerts, never to the approval queue.

Suggested defaults (suggestions only: the owner or the client decides; nothing applies without their answer):

  • Internal use (only the owner's team): approval internal + push; notice daily_digest.
  • Product with clients: approval product; call with push, badge, email; notice immediately for money and messages to third parties, daily_digest for the rest.

1.5 Product-layer questions (with the product owner, one round)

Build one single question with the inventory table already filled in and a proposal on each row. The owner only corrects.

A. Actions

#QuestionExample answer
A1Is the list of actions complete? Is any action the product will have missing?refund_payment is missing
A2What is each action's measure, and over what period does it add up?payment: amount in cents, summed per month
A3What is the floor no client can loosen (min_level, and floor by value)?message to an end customer: at least approval; payments above $100k: always 2 approvers
A4Which actions never happen, for any client (never_global)?delete_customer_data, export_all_tenants

B. Default bands (for each action with a measure)

#QuestionExample answer
B1What are the bands and the level of each?up to $1k do and inform; up to $10k approval; above, approval by two people
B2In each band, which roles approve, which are required and how many must approve?up to $100k: CEO, 1; above: CEO + one partner, 2
B3In each band, who is informed?finance always; partners above $10k
B4If nobody approves in time: deny, or move up to the next band?move up
B5What else must be recorded as proof, beyond requester, band, level, decision, approvers and time?the supplier's id

1.6 Client-layer questions (with each client's admin)

Same rule: one round, with the product defaults already filled in. It can be done by the agent in conversation (the admin confirms) or on the product's Governance settings screen, which records the same thing.

#QuestionExample answer
C1Which actions does this client use? (turning one off = never_do for them)doesn't use WhatsApp messages
C2Do the band amounts work for you? (only within the floor)approval from $5k, not $1k
C3Who holds each role? (people from the client; roles, never names, in the code)CEO = person A; partners = persons A and B; finance = person C
C4Where do you approve? (the options the product offers, e.g. product, external)on the product's screen
C5How should each role be called?CEO by WhatsApp and push; finance by email
C6Where and when is each role informed, per action?payments immediately by push; the rest in the daily digest by email
C7Deadline to approve, and reminder?24 h, reminder at 8 h

When saving, validateClientConfig (Part 2) checks the configuration against the product floor and options; anything below the floor or not offered is refused right away, with the reason.

Rules for the proposals:

  • Bands, amounts, approvers and channels are decisions of the product owner or the client. The agent only suggests; no band goes in without their answer.
  • Limits, approvers and channels are per-client configuration, never a constant in the code. No company name or fixed amount in the code.
  • Money as an integer in the currency's minor unit (cents for USD or BRL; the field is still called amount_cents).
  • When unsure between two levels, propose the stricter one and say so on that row.
  • Calculating amounts and choosing the band is always deterministic code; AI only writes text.

1.7 Onboarding output

Product layer, by pull request in the product repository:

  • docs/GOVERNANCE.md — the final tables, readable, with the date and who approved them.
  • governance/rules.json:
{
  "version": "2026-01-15",
  "approved_by": "product owner",
  "client_defaults": {
    "approval": { "where": "product", "expire_hours": 48 },
    "call": { "default": ["push", "badge", "email"] },
    "notice": {
      "default": { "when": "daily_digest", "where": ["product", "email"] },
      "by_action": { "pay_supplier": { "when": "immediately", "where": ["push"] } }
    },
    "options": {
      "approval": ["product", "external"],
      "channels": ["product", "push", "badge", "email", "whatsapp", "slack", "teams"]
    }
  },
  "actions": {
    "pay_supplier": {
      "measure": "amount_cents", "currency": "USD", "per": "month", "min_level": "do_and_inform",
      "floor": [ { "from": 10000001, "min_level": "approve_then_do", "min_approvals": 2, "required_roles": ["role:ceo"] } ],
      "bands": [
        { "up_to": 100000,   "level": "do_and_inform", "inform": ["role:finance"] },
        { "up_to": 1000000,  "level": "approve_then_do", "approvers": ["role:manager", "role:ceo"], "min_approvals": 1, "inform": ["role:finance"], "on_expire": "escalate" },
        { "up_to": 10000000, "level": "approve_then_do", "approvers": ["role:ceo"], "min_approvals": 1, "inform": ["role:finance", "role:partner"] },
        {                    "level": "approve_then_do", "approvers": ["role:ceo", "role:partner"], "required_roles": ["role:ceo"], "min_approvals": 2, "inform": ["role:finance", "role:partner"] }
      ]
    },
    "send_whatsapp_to_customers": {
      "measure": "recipients", "measure_from": "to", "per": "request", "min_level": "approve_then_do",
      "floor": [ { "from": 51, "min_level": "never_do" } ],
      "bands": [
        { "up_to": 50, "level": "approve_then_do", "approvers": ["role:support_lead"], "min_approvals": 1 },
        {              "level": "never_do" }
      ]
    },
    "draft_report": { "bands": [ { "level": "do" } ] }
  },
  "never_global": ["delete_customer_data", "export_all_tenants"],
  "system_jobs": ["job:monthly-close"]
}
  • Each action becomes a rule with a code (GOV-<ACTION>) and a person responsible for it, in the project's rules (for example in CLAUDE.md or docs/RULES.md), so any agent or reviewer can check against it. Example: GOV-PAY-SUPPLIER: bands by amount summed per month, floor do and inform, two approvers above $100k; approvers and amounts come from the client's governance_config; never executes before the band's approvals.

Client layer: a new row in governance_config (see 2.1), with approved_by = the admin who confirmed. Same format as client_defaults plus bands or disabled per action; only what changes goes in:

{
  "actions": {
    "pay_supplier": { "bands": [
      { "up_to": 500000,  "level": "do_and_inform", "inform": ["role:finance"] },
      { "up_to": 5000000, "level": "approve_then_do", "approvers": ["role:ceo"], "inform": ["role:finance"] },
      {                   "level": "approve_then_do", "approvers": ["role:ceo", "role:partner"], "required_roles": ["role:ceo"], "min_approvals": 2, "inform": ["role:partner"] }
    ] },
    "send_whatsapp_to_customers": { "disabled": true }
  },
  "approval": { "where": "product", "expire_hours": 24, "remind_hours": 8 },
  "call": { "role:ceo": ["whatsapp", "push"], "role:finance": ["email"] },
  "notice": {
    "by_action": { "pay_supplier": { "when": "immediately", "where": ["push"] } },
    "default": { "when": "daily_digest", "where": ["email"] }
  }
}

Who holds each role lives in the product's own users/roles table (per tenant), not in this configuration. After saving, show the admin a readable summary of their configuration (Governance screen or a document).

Part 2 — Implementation: the gate in the code

One single gate, called right before each action in the inventory. No action in rules.json can be called any other way (including do actions, so they stay in the log).

2.1 Database (Postgres), additive migration

-- Example for Supabase (Postgres 15+, auth.jwt(), roles anon/authenticated), with the tenant id in the user's
-- app_metadata.tenant_id. In Supabase, a schema of your own also needs: grant usage on schema <schema> to authenticated.
-- Plain Postgres: in the two policies, replace the auth.jwt() expression with current_setting('app.tenant_id', true)::uuid
-- (set by your server on each connection), replace anon/authenticated with your application's database roles,
-- and grant those roles select on both tables.
-- <schema> is replaced by your migration tool or template with the product's schema name.
create extension if not exists pgcrypto;  -- Supabase installs it in schema "extensions": keep "extensions" in the functions' search_path

-- decision log: insert only
create table if not exists <schema>.governance_decisions (
  id             bigint generated always as identity primary key,
  tenant_id      uuid not null,
  action         text not null,
  request_id     text not null,            -- stable id of the action (e.g. the payment id)
  requester      text not null,            -- user, scheduled job or agent
  rules_version  text not null,            -- version of rules.json
  config_version bigint,                   -- id of the governance_config row used (null = product defaults)
  band           int,                      -- index of the band applied
  level          text not null check (level in ('do','do_and_inform','approve_then_do','never_do')),
  decision       text not null check (decision in ('allowed','awaiting_approval','denied','approved','rejected','expired','escalated','executed','failed','refused')),  -- refused = a call refused without changing the request
  measured_value bigint,                   -- value used to choose the band (this request + the period sum)
  request_value  bigint,                   -- value of this request alone (what the period sum adds up)
  reason         text,
  data           jsonb not null default '{}',
  approver       text,                     -- only on 'approved' / 'rejected' rows, one row per person
  created_at     timestamptz not null default now(),
  seq            bigint,                   -- position in the tenant's chain, set by the trigger below
  prev_hash      text,                     -- set by the trigger below
  hash           text not null             -- set by the trigger below
);
create index if not exists governance_decisions_request on <schema>.governance_decisions (tenant_id, action, request_id, created_at);
create unique index if not exists governance_one_execution on <schema>.governance_decisions (tenant_id, action, request_id) where decision = 'executed';
create unique index if not exists governance_chain_seq on <schema>.governance_decisions (tenant_id, seq);
create unique index if not exists governance_one_vote on <schema>.governance_decisions (tenant_id, action, request_id, band, approver) where decision in ('approved','rejected');

-- per-client configuration: insert only; the tenant's most recent row applies
create table if not exists <schema>.governance_config (
  id          bigint generated always as identity primary key,
  tenant_id   uuid not null,
  config      jsonb not null,
  approved_by text not null,               -- the tenant admin who confirmed
  created_at  timestamptz not null default now()
);
create index if not exists governance_config_tenant on <schema>.governance_config (tenant_id, id desc);

-- read per tenant; there is no insert/update/delete policy, so only the server writes
alter table <schema>.governance_decisions enable row level security;
alter table <schema>.governance_config    enable row level security;
drop policy if exists governance_read_tenant on <schema>.governance_decisions;
create policy governance_read_tenant on <schema>.governance_decisions for select
  using (tenant_id = (select (auth.jwt() -> 'app_metadata' ->> 'tenant_id')::uuid));
drop policy if exists governance_config_read_tenant on <schema>.governance_config;
create policy governance_config_read_tenant on <schema>.governance_config for select
  using (tenant_id = (select (auth.jwt() -> 'app_metadata' ->> 'tenant_id')::uuid));
revoke all on <schema>.governance_decisions, <schema>.governance_config from anon, authenticated;
grant select on <schema>.governance_decisions, <schema>.governance_config to authenticated; -- the policies above filter by tenant

-- protection: blocks updates and deletes on both tables, for every role (only the table owner can disable a trigger)
create or replace function <schema>.governance_insert_only() returns trigger language plpgsql as $$
begin raise exception '% is insert only', tg_table_name; end $$;
create or replace trigger governance_no_update before update or delete on <schema>.governance_decisions
  for each row execute function <schema>.governance_insert_only();
create or replace trigger governance_no_truncate before truncate on <schema>.governance_decisions
  for each statement execute function <schema>.governance_insert_only();
create or replace trigger governance_config_no_update before update or delete on <schema>.governance_config
  for each row execute function <schema>.governance_insert_only();
create or replace trigger governance_config_no_truncate before truncate on <schema>.governance_config
  for each statement execute function <schema>.governance_insert_only();

-- chained hash per tenant, computed in the database (the server doesn't send it)
create or replace function <schema>.governance_row_text(r <schema>.governance_decisions) returns text language sql immutable as $$
  select jsonb_build_object('tenant_id', r.tenant_id, 'action', r.action, 'request_id', r.request_id, 'requester', r.requester,
    'rules_version', r.rules_version, 'config_version', r.config_version, 'band', r.band, 'level', r.level, 'decision', r.decision,
    'measured_value', r.measured_value, 'request_value', r.request_value, 'reason', r.reason, 'data', r.data,
    'approver', r.approver, 'created_at', extract(epoch from r.created_at), 'seq', r.seq)::text $$;

create or replace function <schema>.governance_chain() returns trigger language plpgsql
  set search_path = <schema>, extensions, public as $$
declare last text; lastseq bigint;
begin
  perform pg_advisory_xact_lock(hashtext('governance:' || new.tenant_id::text));
  select hash, seq into last, lastseq from <schema>.governance_decisions where tenant_id = new.tenant_id order by seq desc limit 1;
  new.seq := coalesce(lastseq, 0) + 1;     -- assigned under the lock, so the chain order is the insert order
  new.prev_hash := last;
  new.hash := encode(digest(coalesce(last, '') || <schema>.governance_row_text(new), 'sha256'), 'hex');
  return new;
end $$;
create or replace trigger governance_chain before insert on <schema>.governance_decisions
  for each row execute function <schema>.governance_chain();

-- returns the ids where the chain is broken (empty = intact). It detects a changed or removed row in the middle;
-- a removed tail or a fully recomputed chain is detected only against an anchor kept outside the database (governance_head)
create or replace function <schema>.governance_verify(t uuid) returns table(id bigint) language sql stable
  set search_path = <schema>, extensions, public as $$
  select d.id from (
    select x.id, x.seq, x.prev_hash, x.hash, lag(x.hash) over (order by x.seq) as expected_prev,
           lag(x.seq) over (order by x.seq) as expected_seq, <schema>.governance_row_text(x) as txt
    from <schema>.governance_decisions x where x.tenant_id = t) d
  where d.prev_hash is distinct from d.expected_prev
     or d.seq <> coalesce(d.expected_seq, 0) + 1
     or d.hash <> encode(digest(coalesce(d.prev_hash, '') || d.txt, 'sha256'), 'hex') $$;

-- the tenant's chain head: store (seq, hash) every day somewhere the database owner can't rewrite
-- (another storage, a signed file, an email), and compare it later with governance_verify + this function
create or replace function <schema>.governance_head(t uuid) returns table(seq bigint, hash text) language sql stable as $$
  select x.seq, x.hash from <schema>.governance_decisions x where x.tenant_id = t order by x.seq desc limit 1 $$;
revoke execute on function <schema>.governance_verify(uuid), <schema>.governance_head(uuid) from public, anon, authenticated;

governance_verify finds a changed or removed row in the middle of the chain. A removed tail, or a chain recomputed from scratch by someone who owns the table, is only caught against an anchor kept outside the database: store governance_head(tenant) (last seq and hash) every day somewhere the database owner can't rewrite, and compare. Both functions are for the server only.

<schema> is not read from an environment variable by the migration: your migration tool or template replaces it. The application code reads the same name from its configuration (e.g. <PRODUCT>_DB_SCHEMA), never hardcoded. Changing a client's configuration is always a new row; the history shows who changed what and when.

If your linter or reviewer flags TRUNCATE or DELETE, the triggers above are protection (they block those operations); mark them as an exception.

2.2 The gate (TypeScript, server side)

Written for TypeScript with zod (3 or 4) and Node; with another stack, keep the same steps and checks. It has gate (before each action), vote (the approval endpoint's core) and expire (the scheduled job).

// lib/governance/gate.ts
import { createHash } from "node:crypto";
import { z } from "zod";
import rulesJson from "../../governance/rules.json"; // needs "resolveJsonModule": true; in ESM add: with { type: "json" }

export const LEVELS = ["do", "do_and_inform", "approve_then_do", "never_do"] as const;
export type Level = (typeof LEVELS)[number];
export type Decision = "allowed" | "awaiting_approval" | "denied";
const rank = (l: Level) => LEVELS.indexOf(l);

// ---------- schemas: rules.json and client configs are validated, unknown fields are errors ----------
const LevelZ = z.enum(LEVELS);
const CallChannel = z.enum(["push", "badge", "email", "whatsapp", "slack", "teams"]);     // to call someone to the approval screen
const NoticeChannel = z.enum(["product", "push", "email", "whatsapp", "slack", "teams"]); // to inform after execution
const Where = z.enum(["product", "internal", "external"]);
const Int = z.coerce.number().int().nonnegative().safe(); // database drivers return bigint/sum as text

export const Band = z.object({
  up_to: z.number().int().positive().optional(),          // ceiling, inclusive; the last band has none
  level: LevelZ,
  approvers: z.array(z.string()).default([]),             // roles ("role:<name>") that may approve
  required_roles: z.array(z.string()).default([]),        // roles that must be among the approvers
  min_approvals: z.number().int().min(1).default(1),      // distinct people
  inform: z.array(z.string()).default([]),
  on_expire: z.enum(["deny", "escalate"]).default("deny"),
}).strict();
export type Band = z.infer<typeof Band>;

const Floor = z.object({
  from: z.number().int().nonnegative(),                   // from this measured value up...
  min_level: LevelZ,                                      // ...no client band may be looser than this
  min_approvals: z.number().int().min(1).default(1),
  required_roles: z.array(z.string()).default([]),        // ...and, when it asks for approval, these roles must be required
}).strict();

const Action = z.object({
  measure: z.enum(["amount_cents", "quantity", "recipients"]).optional(),
  per: z.enum(["request", "day", "week", "month"]).default("request"),
  min_level: LevelZ.default("do"),
  floor: z.array(Floor).default([]),
  bands: z.array(Band).min(1),
  measure_from: z.string().optional(),   // recipients: count the items of this field of data (e.g. "to") instead of trusting a number
  currency: z.string().length(3).optional(), // amount_cents: data.currency must be this (bands are in one currency)
}).strict();
type Action = z.infer<typeof Action>;

const Notice = z.object({ when: z.enum(["immediately", "daily_digest", "weekly_digest"]), where: z.array(NoticeChannel).min(1) }).strict();
const Approval = z.object({
  where: Where.optional(),
  remind_hours: z.number().positive().max(24 * 365).optional(),
  expire_hours: z.number().positive().max(24 * 365).optional(),
}).strict();
const Settings = {
  approval: Approval.optional(),
  call: z.record(z.string(), z.array(CallChannel)).optional(),      // key: a role, or "default"
  notice: z.object({
    default: Notice.optional(),
    by_action: z.record(z.string(), Notice).optional(),
    by_role: z.record(z.string(), Notice).optional(),
  }).strict().optional(),
};

const Rules = z.object({
  version: z.string(),
  approved_by: z.string(),
  client_defaults: z.object({
    ...Settings,
    options: z.object({ approval: z.array(Where), channels: z.array(z.union([CallChannel, NoticeChannel])) }).strict(),
  }).strict(),
  actions: z.record(z.string(), Action),
  never_global: z.array(z.string()).default([]),
  system_jobs: z.array(z.string()).default([]), // "job:<name>" that no person starts; any other job needs onBehalfOf
}).strict();

export const ClientConfig = z.object({
  ...Settings,
  actions: z.record(z.string(), z.object({
    bands: z.array(Band).min(1).optional(),
    disabled: z.boolean().optional(),
    approval: Approval.optional(),
  }).strict()).optional(),
}).strict();
export type ClientConfig = z.infer<typeof ClientConfig>;

// ---------- rules ----------
function checkBands(action: string, a: Action, bands: Band[]) {
  if (!a.measure && bands.length !== 1) throw new Error(`${action}: an action with no measure has exactly one band`);
  bands.forEach((b, i) => {
    const last = i === bands.length - 1;
    const nb = bands[i + 1];
    if (b.on_expire === "escalate" && b.level === "approve_then_do" && nb && nb.level !== "never_do") {
      // escalating may change who approves (e.g. manager -> CEO), never lower how many must approve or drop a required role
      const looser = nb.level !== "approve_then_do" || nb.min_approvals < b.min_approvals
        || b.required_roles.some((x) => !nb.required_roles.includes(x));
      if (looser) throw new Error(`${action}: band ${i} escalates to a looser band`);
    }
    if (last && b.up_to !== undefined) throw new Error(`${action}: the last band must have no ceiling`);
    if (!last && b.up_to === undefined) throw new Error(`${action}: only the last band can have no ceiling`);
    const prev = i > 0 ? bands[i - 1]?.up_to : undefined;
    if (prev !== undefined && b.up_to !== undefined && b.up_to <= prev) throw new Error(`${action}: bands out of order`);
    if (rank(b.level) < rank(a.min_level)) throw new Error(`${action}: band ${i} below the product floor (${a.min_level})`);
    if (b.level === "approve_then_do") {
      if (b.approvers.length === 0) throw new Error(`${action}: band ${i} asks for approval with no approver`);
      if (b.required_roles.some((r) => !b.approvers.includes(r))) throw new Error(`${action}: band ${i} requires a role that can't approve`);
      if (b.min_approvals < b.required_roles.length) throw new Error(`${action}: band ${i} needs more approvals than min_approvals`);
    }
    for (const f of a.floor) {                                // the band covers (prev, up_to]
      if (b.up_to !== undefined && b.up_to < f.from) continue;
      if (rank(b.level) < rank(f.min_level)) throw new Error(`${action}: band ${i} below the floor from ${f.from} (${f.min_level})`);
      if (b.level === "approve_then_do" && b.min_approvals < f.min_approvals)
        throw new Error(`${action}: band ${i} needs at least ${f.min_approvals} approvals from ${f.from}`);
      if (b.level === "approve_then_do" && f.required_roles.some((r) => !b.required_roles.includes(r)))
        throw new Error(`${action}: band ${i} must require ${f.required_roles.join(", ")} from ${f.from}`);
    }
  });
}

export type EffectiveRule = { blocked: null | "never_global" | "disabled_by_client"; measure?: Action["measure"]; per: Action["per"]; bands: Band[] };

// merges product + client and checks the floor
export function effectiveRule(action: string, client: ClientConfig | null): EffectiveRule {
  const never = [Band.parse({ level: "never_do" })];
  if (rules.never_global.includes(action)) return { blocked: "never_global", per: "request", bands: never };
  const a = rules.actions[action];
  if (!a) throw new Error(`action without a governance rule: ${action}`); // new action without onboarding = error
  const own = client?.actions?.[action];
  if (own?.disabled) return { blocked: "disabled_by_client", per: "request", bands: never };
  const bands = own?.bands ?? a.bands;
  checkBands(action, a, bands);
  return { blocked: null, measure: a.measure, per: a.per, bands };
}

// client first, then product; the badge is always on; reminder defaults to half the deadline
export function clientChannels(action: string, client: ClientConfig | null) {
  const p = rules.client_defaults;
  const a = { ...p.approval, ...client?.approval, ...client?.actions?.[action]?.approval };
  const expire_hours = a.expire_hours ?? 48;
  return {
    approval: { where: a.where ?? "product", expire_hours, remind_hours: a.remind_hours ?? expire_hours / 2 },
    // call: client's rule for the role, client's default, product's rule for the role, product's default
    call: (role: string) => [...new Set([...(client?.call?.[role] ?? client?.call?.default ?? p.call?.[role] ?? p.call?.default ?? []), "badge" as const])],
    // notice: client per action, client per role, product per action, product per role, client default, product default
    notice: (role: string) =>
      client?.notice?.by_action?.[action] ?? client?.notice?.by_role?.[role] ??
      p.notice?.by_action?.[action] ?? p.notice?.by_role?.[role] ??
      client?.notice?.default ?? p.notice?.default ?? { when: "immediately" as const, where: ["product" as const] },
  };
}

// run before SAVING a client config: refuses unknown fields, unknown actions, bands below the floor, options the product doesn't offer
export function validateClientConfig(raw: unknown): ClientConfig {
  const c = ClientConfig.parse(raw);
  for (const name of Object.keys(c.actions ?? {})) if (!rules.actions[name]) throw new Error(`unknown action: ${name}`);
  for (const name of Object.keys(rules.actions)) {
    effectiveRule(name, c);
    const ap = clientChannels(name, c).approval;
    if (ap.remind_hours >= ap.expire_hours) throw new Error(`${name}: the reminder must come before the deadline`);
  }
  const o = rules.client_defaults.options;
  const wheres = [c.approval?.where, ...Object.values(c.actions ?? {}).map((x) => x.approval?.where)];
  for (const w of wheres) if (w && !o.approval.includes(w)) throw new Error(`approval place not offered: ${w}`);
  const channels = [
    ...Object.values(c.call ?? {}).flat(),
    ...[c.notice?.default, ...Object.values(c.notice?.by_action ?? {}), ...Object.values(c.notice?.by_role ?? {})].flatMap((n) => n?.where ?? []),
  ];
  for (const ch of channels) if (ch !== "badge" && !o.channels.includes(ch)) throw new Error(`channel not offered: ${ch}`);
  return c;
}

// an invalid rules.json fails at startup, not at the first payment
export const rules = Rules.parse(rulesJson);
for (const name of Object.keys(rules.actions)) effectiveRule(name, null);
for (const name of rules.never_global) if (rules.actions[name]) throw new Error(`${name} is in never_global and in actions`);
const d = rules.client_defaults; // the product defaults themselves must be valid and offered
validateClientConfig({ approval: d.approval, call: d.call, notice: d.notice });

// what was asked, so an approved request can't be changed afterwards (data is normalized to plain JSON first: a Date becomes its ISO text)
const canonical = (v: unknown): string => Array.isArray(v) ? `[${v.map(canonical).join(",")}]`
  : v && typeof v === "object" ? `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical((v as Record<string, unknown>)[k])}`).join(",")}}`
  : JSON.stringify(v ?? null);
const fingerprint = (action: string, data: unknown) => createHash("sha256").update(canonical({ action, data })).digest("hex");


// ---------- request state (your database code; reference queries in the skill) ----------
// A request's lifecycle rows: allowed, awaiting_approval, escalated, executed, failed, rejected, expired, denied.
// Its identity (requester, on_behalf_of, fingerprint) comes from its FIRST lifecycle row; its state from the LATEST one.
// 'approved' (votes) and 'refused' (refused calls) never change the state.
const Instant = z.union([z.string(), z.date()]).nullable().transform((v) => (v === null ? null : new Date(v)));
export const RequestState = z.object({
  state: z.enum(["allowed", "awaiting_approval", "escalated", "executed", "failed", "rejected", "expired", "denied"]),
  state_at: Instant,
  requester: z.string(), on_behalf_of: z.string().nullable(), fingerprint: z.string(),
  executed: z.coerce.boolean(),
  // frozen at opening (or at the latest escalation); null when the request never asked for approval
  band: Int.nullable(), snapshot: Band.nullable(), next: z.array(Band).nullable().transform((v) => v ?? []),
  measured: Int.nullable(), expire_at: Instant,
  first_data: z.record(z.string(), z.unknown()).nullable(), request_value: Int.nullable(), // what was asked, for an escalation
});
export type RequestState = z.infer<typeof RequestState>;
const FINAL = ["rejected", "expired", "denied"] as const;
const WAITING = ["awaiting_approval", "escalated"] as const;
export const IN_PROGRESS_MINUTES = 15; // after this, an 'allowed' run with no 'executed'/'failed' is "outcome unknown" until settled

export type Deps = {
  withLock: <T>(tenantId: string, action: string, fn: () => Promise<T>) => Promise<T>; // one READ COMMITTED transaction + a lock per tenant and action, taken first
  clientConfig: (tenantId: string) => Promise<{ id: number | string; config: unknown } | null>; // most recent governance_config row
  requestState: (tenantId: string, action: string, requestId: string) => Promise<unknown>;     // row shaped like RequestState, or null
  periodSum: (tenantId: string, action: string, per: "day" | "week" | "month", exceptRequestId: string) => Promise<unknown>; // the total
  approvals: (tenantId: string, action: string, requestId: string, band: number) => Promise<{ user: string; role: string }[]>;
  openApproval: (p: { tenantId: string; action: string; requestId: string; band: number; snapshot: Band; missing: number;
                      missingRoles: string[]; channels: ReturnType<typeof clientChannels>; data: unknown }) => Promise<void>;
  record: (row: Record<string, unknown>) => Promise<void>; // insert into governance_decisions (seq and hash are set by the database)
};

async function load(tenantId: string, action: string, requestId: string, deps: Pick<Deps, "clientConfig" | "requestState">) {
  const cfg = await deps.clientConfig(tenantId);
  const client = cfg ? validateClientConfig(cfg.config) : null; // a stored config that no longer passes fails closed for the tenant
  const raw = await deps.requestState(tenantId, action, requestId);
  return { cfgId: cfg ? Int.parse(cfg.id) : null, client, st: raw ? RequestState.parse(raw) : null };
}

// waiting = can still receive votes or expire: waiting state, frozen band, not executed
function waiting(st: RequestState | null) {
  if (!st || st.executed || !(WAITING as readonly string[]).includes(st.state) || !st.snapshot || st.band === null) return null;
  return { ...st, snapshot: st.snapshot, band: st.band };
}

// who can't approve: the original requester and the person an agent acts for
function tally(o: { snapshot: Band; requester: string; on_behalf_of: string | null }, votes: { user: string; role: string }[]) {
  const valid = votes.filter((v) => v.user !== o.requester && v.user !== o.on_behalf_of && o.snapshot.approvers.includes(v.role));
  const people = [...new Set(valid.map((v) => v.user))];
  const missingRoles = o.snapshot.required_roles.filter((role) => !valid.some((v) => v.role === role));
  return { people, missingRoles, complete: people.length >= o.snapshot.min_approvals && missingRoles.length === 0 };
}

const deadline = (now: Date, hours: number) => new Date(now.getTime() + hours * 3600_000).toISOString();

// ---------- the gate ----------
const Request = z.object({
  tenantId: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
  action: z.string().min(1),
  requestId: z.string().min(1),            // stable id of the action (e.g. the payment id); also the provider's idempotency key
  requester: z.string().min(1),            // a user id, "job:<name>" or "agent:<name>"
  onBehalfOf: z.string().min(1).optional(),// the person an agent acts for (required for "agent:" requesters); can't approve it
  data: z.record(z.string(), z.unknown()).default({}), // EVERYTHING that defines the effect (amount, payee, account, currency...)
  now: z.date().optional(),
});

type Result = { decision: Decision; level: Level; band: number; reason: string | null; inform: { role: string; notice: unknown }[];
                markExecuted: (r: Record<string, unknown>) => Promise<void>; markFailed: (e: string) => Promise<void> };

export async function gate(input: z.input<typeof Request>, deps: Deps): Promise<Result> {
  const r = Request.parse(input);
  if (r.requester.startsWith("agent:") && !r.onBehalfOf) throw new Error("an agent's request needs onBehalfOf (the person it acts for)");
  const data = JSON.parse(JSON.stringify(r.data)) as Record<string, unknown>; // plain JSON: what is fingerprinted is what is stored
  if (JSON.stringify(data).includes("\\u0000")) throw new Error("data can't contain the NUL character");
  const now = r.now ?? new Date();
  return deps.withLock(r.tenantId, r.action, async () => {
    const { cfgId, client, st } = await load(r.tenantId, r.action, r.requestId, deps);
    if (st?.executed) throw new Error(`action already executed: ${r.action}/${r.requestId}`);
    if (!st && r.requester.startsWith("job:") && !rules.system_jobs.includes(r.requester) && !r.onBehalfOf)
      throw new Error("a job started by a person needs onBehalfOf (who started or scheduled it)");
    const rule = effectiveRule(r.action, client);
    const channels = clientChannels(r.action, client);
    const fp = fingerprint(r.action, data);
    const requester = st?.requester ?? r.requester;              // the first requester, whoever calls again (e.g. a retry job)
    const onBehalfOf = st ? st.on_behalf_of : (r.onBehalfOf ?? null);
    const base = { tenant_id: r.tenantId, action: r.action, request_id: r.requestId, requester,
                   rules_version: rules.version, config_version: cfgId };
    const no = (reason: string) => async () => { throw new Error(`refused: ${reason}`); };
    // a refused call doesn't change the request: it is not a lifecycle row, so the sum and the queue keep the request as it was
    const refuse = async (reason: string): Promise<Result> => {
      const level = st?.snapshot?.level ?? "never_do";
      await deps.record({ ...base, band: st?.band ?? null, level, decision: "refused", reason, data: { attempted_fingerprint: fp } });
      return { decision: "denied", level, band: st?.band ?? 0, reason, inform: [], markExecuted: no(reason), markFailed: no(reason) };
    };

    if (st && st.fingerprint !== fp) return refuse("request changed after it was first made");
    if (st && (FINAL as readonly string[]).includes(st.state)) return refuse(st.state);            // rejected, expired, denied are final
    if (st?.state === "allowed")   // a run was allowed and never settled: running now, or crashed after the provider call
      return refuse(st.state_at && now.getTime() - st.state_at.getTime() < IN_PROGRESS_MINUTES * 60_000
        ? "in progress" : "outcome unknown: check the provider, then call settle()");

    let current: number | null = null, measured: number | null = null;
    if (rule.measure) {
      const a = rules.actions[r.action];
      if (a?.currency && data.currency !== a.currency) throw new Error(`${r.action}: currency must be ${a.currency}`);
      const from = a?.measure_from ? data[a.measure_from] : undefined;
      if (a?.measure_from && !Array.isArray(from)) throw new Error(`${r.action}: ${a.measure_from} must be a list`);
      if (Array.isArray(from) && data[rule.measure] !== undefined && data[rule.measure] !== from.length)
        throw new Error(`${r.action}: ${rule.measure} doesn't match ${a!.measure_from}`);
      const raw = Array.isArray(from) ? from.length : data[rule.measure];                // no default: the measure must be given
      current = z.number().int().nonnegative().safe().parse(raw);                  // money in whole minor units; "", "12" or 1.5 = error
      measured = current + (rule.per === "request" ? 0 : Int.parse(await deps.periodSum(r.tenantId, r.action, rule.per, r.requestId)));
    }

    let idx: number, band: Band, next: Band[], decision: Decision, reason: string | null = null;
    let approvedBy: string[] = [], opening: { missing: number; missingRoles: string[] } | null = null;
    const frozen = st?.snapshot && st.band !== null ? { band: st.band, snapshot: st.snapshot } : null;
    if (rule.blocked) {
      idx = 0; band = rule.bands[0]!; next = []; decision = "denied"; reason = rule.blocked;
    } else {
      // a request that already asked for approval keeps that band; otherwise it is placed by its measure (also on a retry)
      idx = frozen ? frozen.band : rule.bands.findIndex((b) => b.up_to === undefined || (measured ?? 0) <= b.up_to);
      band = frozen ? frozen.snapshot : rule.bands[idx]!;
      next = frozen ? st!.next : rule.bands.slice(idx + 1);
      if (frozen) measured = st!.measured;
      if (band.level === "never_do") { decision = "denied"; reason = `band ${idx}`; }
      else if (band.level !== "approve_then_do") decision = "allowed";
      else {
        const t = tally({ snapshot: band, requester, on_behalf_of: onBehalfOf }, await deps.approvals(r.tenantId, r.action, r.requestId, idx));
        approvedBy = t.people;
        decision = t.complete ? "allowed" : "awaiting_approval";
        if (decision === "awaiting_approval" && !frozen) opening = { missing: Math.max(band.min_approvals - t.people.length, 0), missingRoles: t.missingRoles };
      }
    }

    const inform = decision === "allowed" && band.level !== "do" ? [...new Set(band.inform)] : [];
    const row = { ...base, band: idx, level: band.level, measured_value: measured, request_value: current };
    const deadlines = opening ? { expire_at: deadline(now, channels.approval.expire_hours), remind_at: deadline(now, channels.approval.remind_hours) } : {};
    if (!(decision === "awaiting_approval" && frozen)) // a waiting request is recorded once, when it opens
      await deps.record({ ...row, decision, reason, data: { ...data, fingerprint: fp, on_behalf_of: onBehalfOf, band_snapshot: band,
                                                            next_bands: next, approved_by: approvedBy, ...deadlines } });
    if (opening) // approvers are called once, after the request is recorded; reminders come from the scheduled job
      await deps.openApproval({ tenantId: r.tenantId, action: r.action, requestId: r.requestId, band: idx, snapshot: band, ...opening, channels, data });

    const life = { fingerprint: fp, on_behalf_of: onBehalfOf };
    const clean = (x: unknown) => JSON.parse(JSON.stringify(x ?? {}).split("\\u0000").join("")) as Record<string, unknown>;
    if (decision !== "allowed") return { decision, level: band.level, band: idx, reason, inform: [], markExecuted: no(decision), markFailed: no(decision) };
    return {
      decision, level: band.level, band: idx, reason,
      inform: inform.map((role) => ({ role, notice: channels.notice(role) })),
      markExecuted: async (result: Record<string, unknown>) => deps.record({ ...row, decision: "executed", data: { ...clean(result), ...life, inform } }),
      markFailed: async (error: string) => deps.record({ ...row, decision: "failed", reason: error.split("\u0000").join(""), data: life }),
    };
  });
}

// ---------- the approval endpoint's core: POST /governance/approve and /reject ----------
// userRoles come from the server-side session (the product's own roles table, same tenant), never from the request body
export async function vote(v: { tenantId: string; action: string; requestId: string; user: string; userRoles: string[]; vote: "approved" | "rejected"; now?: Date },
                           deps: Pick<Deps, "withLock" | "clientConfig" | "requestState" | "approvals" | "record">) {
  return deps.withLock(v.tenantId, v.action, async () => {
    const { cfgId, st } = await load(v.tenantId, v.action, v.requestId, deps);
    const o = waiting(st);
    if (!o) throw new Error("request is not waiting for approval");          // also after it was allowed or executed
    if (!o.expire_at || (v.now ?? new Date()).getTime() > o.expire_at.getTime()) throw new Error("request expired"); // deadline frozen at opening
    if (v.user === o.requester || v.user === o.on_behalf_of) throw new Error("the requester can't approve their own request");
    const votes = await deps.approvals(v.tenantId, v.action, v.requestId, o.band);
    if (votes.some((x) => x.user === v.user)) throw new Error("user already voted in this band");
    // a person with several roles votes with a required role that is still missing, if they have one
    const role = tally(o, votes).missingRoles.find((x) => v.userRoles.includes(x)) ?? o.snapshot.approvers.find((x) => v.userRoles.includes(x));
    if (!role) throw new Error("user has no role that can approve this band");
    await deps.record({ tenant_id: v.tenantId, action: v.action, request_id: v.requestId, requester: o.requester,
                        rules_version: rules.version, config_version: cfgId, band: o.band, level: o.snapshot.level,
                        decision: v.vote, approver: v.user, data: { role, fingerprint: o.fingerprint, on_behalf_of: o.on_behalf_of } });
    // complete = the caller re-runs the action (same requestId and data), which now passes the gate
    return { complete: v.vote === "approved" && tally(o, [...votes, { user: v.user, role }]).complete, rejected: v.vote === "rejected" };
  });
}

// ---------- expiry: the scheduled job calls this for each waiting request past its expire_at ----------
export async function expire(req: { tenantId: string; action: string; requestId: string; now?: Date },
                             deps: Pick<Deps, "withLock" | "clientConfig" | "requestState" | "approvals" | "record" | "openApproval">) {
  const now = req.now ?? new Date();
  return deps.withLock(req.tenantId, req.action, async () => {
    const { cfgId, client, st } = await load(req.tenantId, req.action, req.requestId, deps);
    const o = waiting(st);
    if (!o) return "not_waiting" as const;
    if (o.expire_at && now.getTime() <= o.expire_at.getTime()) return "not_due" as const;
    if (tally(o, await deps.approvals(req.tenantId, req.action, req.requestId, o.band)).complete)
      return "complete" as const;                         // fully approved: re-run the action instead of expiring it
    const base = { tenant_id: req.tenantId, action: req.action, request_id: req.requestId, requester: o.requester,
                   rules_version: rules.version, config_version: cfgId, measured_value: o.measured, request_value: o.request_value };
    const life = { fingerprint: o.fingerprint, on_behalf_of: o.on_behalf_of };
    const asked = o.first_data ?? {};                     // what was asked, so the new approvers see it
    const [next, ...rest] = o.next;                       // the bands frozen at opening, not the current config
    if (o.snapshot.on_expire === "escalate" && next?.level === "approve_then_do") {
      const ch = clientChannels(req.action, client);
      await deps.record({ ...base, band: o.band + 1, level: next.level, decision: "escalated",
                          data: { ...asked, ...life, band_snapshot: next, next_bands: rest, approved_by: [],
                                  expire_at: deadline(now, ch.approval.expire_hours), remind_at: deadline(now, ch.approval.remind_hours) } });
      await deps.openApproval({ tenantId: req.tenantId, action: req.action, requestId: req.requestId, band: o.band + 1, snapshot: next,
                                missing: next.min_approvals, missingRoles: next.required_roles, channels: ch, data: asked });
      return "escalated" as const;                        // notify the requester
    }
    await deps.record({ ...base, band: o.band, level: o.snapshot.level, decision: "expired", data: life });
    return "expired" as const;                            // notify the requester
  });
}

// ---------- settle: after an "outcome unknown", someone checks the provider and records what really happened ----------
export async function settle(x: { tenantId: string; action: string; requestId: string; outcome: "executed" | "failed"; by: string; note?: string },
                            deps: Pick<Deps, "withLock" | "clientConfig" | "requestState" | "record">) {
  return deps.withLock(x.tenantId, x.action, async () => {
    const { cfgId, st } = await load(x.tenantId, x.action, x.requestId, deps);
    if (!st || st.executed || st.state !== "allowed") throw new Error("nothing to settle");
    await deps.record({ tenant_id: x.tenantId, action: x.action, request_id: x.requestId, requester: st.requester,
                        rules_version: rules.version, config_version: cfgId, band: st.band, level: st.snapshot?.level ?? "do",
                        measured_value: st.measured, request_value: st.request_value, decision: x.outcome,
                        reason: `settled by ${x.by}${x.note ? ": " + x.note : ""}`,
                        data: { fingerprint: st.fingerprint, on_behalf_of: st.on_behalf_of } });
  });
}

Besides gate, vote and expire, the module has settle, for a run whose outcome is unknown (see below). rules.json is checked when the module loads: an invalid band, an action both in actions and never_global, or a default the product doesn't offer stops the app from starting.

Usage, always on the line before the action (provider, notify, alert and queue are your own functions):

// data holds EVERYTHING that defines the effect: it is fingerprinted, and the provider call is built only from it
const data = { amount_cents: payment.amount_cents, currency: payment.currency, supplier_id: payment.supplier_id, payee_account: payment.payee_account };
const g = await gate({ tenantId, action: "pay_supplier", requestId: payment.id, requester: user.id, data }, deps); // an agent also passes onBehalfOf
if (g.decision !== "allowed") return { status: g.decision, reason: g.reason }; // nothing goes out; if awaiting, the request is already open

let res;
try {
  res = await provider.pay(data, { idempotencyKey: payment.id }); // the provider also refuses a duplicate
} catch (e) {
  await g.markFailed(String(e));          // recorded; doesn't count in the period sum
  await alert({ tenantId, action: "pay_supplier", requestId: payment.id, error: String(e) }); // error log / alerts
  throw e;
}
await g.markExecuted({ ref: res.id }).catch((e) => { if (e.code !== "23505") throw e; }); // unique violation (23505 in Postgres): already recorded
for (const { role, notice } of g.inform)   // after execution, with the result, on the channel and timing the client chose
  await notify({ tenantId, role, notice, action: "pay_supplier", requestId: payment.id, data: { ref: res.id, ...data } })
    .catch((e) => alert({ tenantId, action: "pay_supplier", requestId: payment.id, error: `notice failed: ${e}` })); // a failed notice doesn't undo the action

The approval endpoint, with the approver's session (roles read on the server from the product's roles table):

// POST /governance/approve  (and /reject with vote: "rejected")
const v = await vote({ tenantId: session.tenantId, action, requestId, user: session.userId,
                       userRoles: await rolesOf(session.userId, session.tenantId), vote: "approved" }, deps);
if (v.complete) await queue.rerun(action, requestId); // re-runs the same action with the same requestId and data; now it passes the gate

Reference queries for deps (Postgres):

-- Drivers return bigint and sum() as text: the gate converts them with zod (Int), so return them as they come.
-- A request's lifecycle rows are: allowed, awaiting_approval, escalated, executed, failed, rejected, expired, denied.
-- 'approved' (votes) and 'refused' (refused calls) never change the request's state and are left out below.

-- withLock: run gate, vote, expire and settle inside one READ COMMITTED transaction whose first statement is
select pg_advisory_xact_lock(hashtext($1 || ':' || $2));  -- tenant_id, action

-- requestState: identity from the FIRST lifecycle row, state from the LATEST one, frozen band from the latest opening
-- or escalation (no row = the request was never made)
select l.decision as state, l.created_at as state_at,
       f.requester, f.data ->> 'on_behalf_of' as on_behalf_of, f.data ->> 'fingerprint' as fingerprint,
       exists (select 1 from <schema>.governance_decisions e
                where e.tenant_id = $1 and e.action = $2 and e.request_id = $3 and e.decision = 'executed') as executed,
       o.band, o.data -> 'band_snapshot' as snapshot, o.data -> 'next_bands' as next,
       o.measured_value as measured, o.data ->> 'expire_at' as expire_at,
       f.data as first_data, f.request_value
  from (select decision, created_at from <schema>.governance_decisions
         where tenant_id = $1 and action = $2 and request_id = $3
           and decision in ('allowed', 'awaiting_approval', 'escalated', 'executed', 'failed', 'rejected', 'expired', 'denied')
         order by id desc limit 1) l
 cross join lateral (select requester, data, request_value from <schema>.governance_decisions
         where tenant_id = $1 and action = $2 and request_id = $3
           and decision in ('allowed', 'awaiting_approval', 'escalated', 'executed', 'failed', 'rejected', 'expired', 'denied')
         order by id limit 1) f
  left join lateral (select band, data, measured_value from <schema>.governance_decisions
         where tenant_id = $1 and action = $2 and request_id = $3 and decision in ('awaiting_approval', 'escalated')
         order by id desc limit 1) o on true;

-- periodSum (return the total column): every request opened in the period that was executed, or whose state is
-- allowed, failed (it can be retried) or still waiting for approval, once per request, except the current one.
-- Rejected, expired and denied (never executed) don't count. $3 = 'day' | 'week' | 'month'; use the tenant's time zone if needed.
select coalesce(sum(v), 0)::bigint as total from (
  select distinct on (request_id) request_id, decision, v, first_at, ran from (
    select d.id, d.request_id, d.decision,
           max(d.request_value) over (partition by d.request_id) as v,
           min(d.created_at) over (partition by d.request_id) as first_at,
           bool_or(d.decision = 'executed') over (partition by d.request_id) as ran
      from <schema>.governance_decisions d
     where d.tenant_id = $1 and d.action = $2 and d.request_id <> $4
       and d.decision in ('allowed', 'awaiting_approval', 'escalated', 'executed', 'failed', 'rejected', 'expired', 'denied')) z
   order by request_id, id desc) latest
 where (ran or decision in ('allowed', 'awaiting_approval', 'escalated', 'failed'))
   and first_at >= date_trunc($3, now() at time zone 'UTC') at time zone 'UTC';

-- approvals: one row per person who approved this request in this band (written by vote)
select approver as "user", data ->> 'role' as role from <schema>.governance_decisions
 where tenant_id = $1 and action = $2 and request_id = $3 and band = $4 and decision = 'approved';

-- Approvals screen and the scheduled job: requests whose state is still waiting, with their frozen deadlines.
-- The job sends the reminder after remind_at and calls expire after expire_at.
select * from (
  select distinct on (action, request_id) tenant_id, action, request_id, decision, band, measured_value, data,
         data ->> 'remind_at' as remind_at, data ->> 'expire_at' as expire_at
    from <schema>.governance_decisions
   where tenant_id = $1
     and decision in ('allowed', 'awaiting_approval', 'escalated', 'executed', 'failed', 'rejected', 'expired', 'denied')
   order by action, request_id, id desc) latest
 where decision in ('awaiting_approval', 'escalated');

Mandatory points:

  • Idempotency: a stable requestId, also sent to the provider as its idempotency key. The gate refuses a request that already has an executed row, and the unique index governance_one_execution refuses it in the database. While a run is allowed without executed or failed, a second run of the same request is refused: "in progress" for IN_PROGRESS_MINUTES, then "outcome unknown" until someone checks the provider and calls settle with what really happened. Time alone never lets it run again, so a message or email without an idempotency key isn't sent twice.
  • Result only when allowed: markExecuted and markFailed work only on an allowed result; on any other decision they throw. Results are cleaned of the NUL character before they are stored, and data with one is refused.
  • Lock: gate, vote, expire and settle run inside one READ COMMITTED transaction whose first statement takes a lock per tenant and action (withLock; in Postgres, pg_advisory_xact_lock). In REPEATABLE READ or SERIALIZABLE the snapshot would be taken before the lock is held, and two requests could read the same sum. With the lock, so two requests can't both read the period sum before either is recorded, and a vote can't cross an expiry or an escalation.
  • Bands: the bands are the ones defined in onboarding (product and client); the code only places the request in one of them by its measure. The band applied, the measured value and the request's own value go into the log row. The period sum adds up request_value of the requests opened in the period that were executed, or are allowed, failed (they can be retried) or still waiting, once per request; rejected, expired and denied ones that never ran don't count. Pending requests count so that ten requests just under a ceiling can't each be approved in the low band.
  • One request, one identity: a request's identity comes from its first row in the log: who asked, the person an agent acted for, and a fingerprint of what was asked (action + data, normalized to plain JSON, so a date counts). Every later call with the same requestId, by anyone (a retry job, a re-run after approval), keeps that identity, and a call with a different amount or different data returns denied: nobody can change a request after it was made or approved. Its state comes from its latest row (requestState).
  • Open request: once a request asks for approval (or is escalated), it keeps that band, its approvers, the bands after it and its deadline (band_snapshot, next_bands, expire_at), even if the client changes the configuration or the period sum moves. A request that never asked for approval is placed again by the current sum when retried. A rejected, expired or denied request is final: calling the gate again returns denied; a new attempt needs a new requestId. Votes and expiry only act on a request that is still waiting and was not executed.
  • Refused calls: a call refused because the request changed, is final or is in progress is recorded as refused. It doesn't change the request's state, so it can't take a pending request out of the period sum or the approval queue.
  • Agents and jobs: a request made by an agent (requester: "agent:<name>"), or by a job a person started or scheduled ("job:<name>"), must carry onBehalfOf, the person behind it; neither the requester nor that person can approve it, also when a job retries it. Only the jobs listed in rules.json → system_jobs, which no person starts, go without it.
  • Called once: the approvers are called when the request opens, after it is recorded, not on every new call to the gate; reminders come from the scheduled job.
  • Several approvers: each approval is one approved row with one approver, written by vote. Only distinct people count, with one of the band's roles, from the same tenant, other than the requester; every role in required_roles must be among them. A rejection (rejected) closes the request.
  • Client configuration: read from the tenant's most recent governance_config row. Every read goes through validateClientConfig: a stored configuration that no longer passes (written without validation, or after the product tightened the floor) fails closed, the gate throws and nothing runs for that tenant. When you change rules.json, revalidate every tenant's latest configuration in CI. Saving a new config goes through validateClientConfig (unknown fields, unknown actions, bands below the floor or out of order, approval with no approver, a place or channel the product doesn't offer: all refused).
  • Do and inform / the band's informed roles: the notice goes out after execution, with the result, to each role in inform, through the channel and at the time the client chose. A failed notice doesn't undo the action: it becomes an alert.
  • Approval: awaiting_approval opens the request in the client's approval.where and calls each role in approvers through the channels the client set for that role (see 1.4).
    • product: the Approvals screen = the requests whose latest state is awaiting_approval or escalated (last query above), showing band, amount and how many approvals and which required roles are missing. Approve / Reject buttons.
    • internal: a card in the owner's internal tool showing exactly what will be done; the card calls the approval endpoint as the approver.
    • external: the client's system calls the same endpoint with the approver's own token.
    • A single endpoint POST /governance/approve (and /reject), built on vote: requires the approver's session; checks on the server that the user has one of the band's roles in the same tenant (a person with several roles votes with a required role that is still missing), is not the original requester nor the person an agent acted for, hasn't voted in this band of the request yet, and that the request is still waiting and within its frozen deadline; records approved (or rejected) with the band, the approver and data.role. After an escalation the same person can vote again, in the new band.
    • Email, WhatsApp, Slack and Teams carry only the summary and the link to the screen; the link doesn't approve.
    • When vote returns complete, the endpoint queues a new run of the same action (same requestId and data); that run passes the gate and executes.
  • Reminder and expiry: a scheduled job lists the waiting requests with their frozen remind_at and expire_at (last reference query), resends the call after remind_at and, after expire_at, calls expire: if the request already has enough approvals it returns complete (queue the run instead); deny records expired; escalate records escalated with the next frozen band and what was asked (the first request's data and value), and opens it for that band's approvers, who see the same request. With no next band, or a next band that isn't an approval, escalating = denying. Notify the requester in both cases. Nothing is deleted and expiry never approves.
  • Digests: daily_digest / weekly_digest are read from the log (decision='executed' in the period, per informed role) by whatever builds the digest, with no separate queue.
  • Chained hash: computed by the database trigger (governance_chain), per tenant, under a lock, in the order of seq (assigned under the same lock); governance_verify(tenant) returns the rows where the chain is broken; governance_head(tenant) is the anchor to keep outside the database.
  • AI agents: the agent never calls the provider directly; the tool it receives is the function already behind the gate. AI can write the text; it doesn't decide amount, band or approval.
  • One way out: all provider SDKs are imported in a single module, and a lint rule (e.g. ESLint's no-restricted-imports) forbids importing them anywhere else.

2.3 Tests the pull request must have

Run them against a real Postgres (a test database or an embedded one), not only mocks, so the indexes, triggers and row-level security are tested too.

  1. An action without a rule in rules.json throws; an invalid rules.json (schema or bands) fails at startup.
  2. do → allowed, row recorded, nobody informed.
  3. do_and_inform → allowed, executes and informs each role of the band once, after execution.
  4. approve_then_do without approval → awaiting_approval, request opened, provider not called; a second call doesn't open it or call the approvers again.
  5. approve_then_do with enough approvals → vote returns complete, and the re-run (even by another caller, such as a job) → allowed.
  6. A never_do band, an action in never_global or one disabled by the client → denied, recorded with the reason (not an exception); a denied request stays denied when called again with a smaller value.
  7. Bands and measure: a value at a band's ceiling stays in it; one cent above falls into the next; a non-integer, empty, text or missing value throws; with measure_from, the list is counted and a different number is refused; another currency is refused; a config whose last band has a ceiling, or whose escalation asks for fewer approvals or drops a required role, is refused.
  8. Period: with per: month, the sum of the month's requests (allowed, executed, failed or pending) + the request changes the band; requests still waiting for approval count; a rejected one doesn't; the previous month doesn't; the same request isn't counted twice; a refused call (e.g. the same requestId with other data) doesn't take a pending request out of the sum or the queue; values that come back from the driver as text are added as numbers.
  9. Several approvers: with min_approvals: 2, one approval → still awaiting; the same person can't vote twice in a band; the requester can't vote; two people without a required role → still awaiting; a person who holds the required role and another role counts with the required one; then → allowed.
  10. Client config: with no config, the product defaults apply; an invalid config stored without validation makes the gate refuse to run for that tenant; a deadline longer than a year is refused; with a config, its bands and channels apply; a config below min_level or the value floor (level, number of approvals, required roles, or a never_do floor), out of order, with approval and no approver, with an unknown field, with a place or channel the product doesn't offer, or with the reminder after the deadline is refused when saving.
  11. Channels per client: client A calls the CEO by WhatsApp and client B by email, for the same action; a role with no channel of its own uses the client default and then the product default; the badge is always there; the reminder defaults to half the deadline; a client's default doesn't override the product's per-action notice.
  12. Open request: after the client changes the configuration, an open request keeps its band and its deadline; a new request uses the new one; calling again with another amount, other data or another date → denied; a rejected request returns denied and accepts no more votes; a rejection after the request was allowed or executed is refused, and an executed request keeps counting in the period.
  13. Expiry: before expire_at nothing happens; an escalated request carries the first request's data and value to the new approvers; deny records expired and the gate then returns denied; escalate records escalated from the frozen bands, only the next band's roles can vote, and their approvals make it allowed; a fully approved request isn't expired (complete); a vote after the deadline is refused.
  14. The same requestId executed twice → the second is refused, by the gate and by the unique index; a second run while the first is in progress → refused, and after IN_PROGRESS_MINUTES still refused ("outcome unknown") until settle; markExecuted/markFailed on a result that isn't allowed → error.
  15. Tenant B can't read tenant A's decisions or config, can't insert, and can't call governance_verify (row-level security and grants).
  16. Approving without a session, with a role outside the band, from another tenant, one's own request (or the request an agent made on one's behalf), twice, or an expired request → refused by vote and the endpoint; an agent's request, or a job's that isn't in system_jobs, without onBehalfOf → refused; when a job retries a failed request and it now needs approval, the first requester (and the agent's person) still can't approve it.
  17. UPDATE, DELETE and TRUNCATE on governance_decisions and governance_config fail.
  18. governance_verify returns nothing on an intact log, even with inserts of different actions of the same tenant and ids out of order; it returns the row when one was changed; removing the last row changes governance_head, compared with the stored anchor.
  19. A failure in the provider records failed and alerts; the failed request still counts in the period; a retry with the same requestId goes through the gate again and is placed by the current sum; a failure in the notice doesn't undo the action.
  20. Lint: importing a provider SDK outside the providers module fails the build.

Part 3 — Reviewing a spec or pull request

Used by any agent or human reviewer, for each spec, task or pull request, checking against governance/rules.json:

  • Does every action with an external effect mentioned in the spec exist in rules.json? If not, the spec goes back to onboarding (don't invent the rule inside the spec).
  • Are the never_global actions and the actions a client disabled refused, and recorded?
  • Does the spec use the bands (defined in onboarding; the code only places the request by its measure) instead of a single fixed limit?
  • Do bands, approvers, required roles, number of approvals, channels and informed roles come from the client's governance_config with the product defaults, not from a constant? Is the floor checked when the config is saved?
  • Is the level implemented in each band the one in rules.json / config? A spec that executes on its own something in an approve_then_do band is a violation.
  • Does the spec call the gate before the action, handle awaiting_approval and denied, record executed or failed, and inform the band's roles after executing?
  • Does a new call check that the request is the same one that was approved (fingerprint), and does data hold everything that defines the effect (amount, currency, payee, account), with the provider call built only from it?
  • Does the period sum include requests still waiting, and do refused calls leave the request's state alone?
  • Are the requester (and the person an agent acts for) excluded from approving, with distinct people, required roles, frozen deadlines and escalation from the frozen bands?
  • Do gate, vote, expire and settle run under the same lock per tenant and action, in READ COMMITTED?
  • Is the measure taken from the data itself (measure_from, currency), and is an unsettled run settled instead of re-run?
  • Is what must hold for every client in min_level, floor or never_global, not only in the product's default bands?
  • Is the decision log's head anchored outside the database?
  • Is approval only on an authenticated screen or the approval endpoint, never a reply in a channel or a link that approves? Do notices never ask for an action?
  • Stable requestId and idempotency key sent to the provider? Tenant isolation in every query?
  • Amounts in cents, input validated by a schema (zod or the equivalent in your stack), deterministic calculation?
  • Log and config insert only, no updates to history? Failures go to alerts, not to the approval queue?
  • Does an AI agent reach the provider only through the gate?

Each "no" is a violation, named by the corresponding GOV-* rule.

Don't

  • Don't write a rule the owner hasn't approved; the product onboarding ends with the owner's OK and the client onboarding with the client admin's OK.
  • Don't put a limit, band, company name, schema, approver or channel in the code.
  • Don't let a client configure below the product floor.
  • Don't delete or rewrite rows in the log or the config; a correction is a new row.
  • Don't put secrets in the code or in git, and don't let AI calculate amounts or choose the band.
  • Don't turn on any automatic sending as part of the implementation: start with the levels exactly as approved in onboarding; any automatic sending is turned on only by the owner or the client, after the gate is live.

Verwandte Skills