Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Approval binding: unchanged intent, current authority and one operation

Review a frozen refund intent, then test changed arguments, permission revocation, expiry, resource changes and duplicate workers.

Learning objectives: Bind approval to exact action semantics and demonstrate why current authorization and duplicate-effect control remain separate execution obligations.

Content checked: 2026-10-11 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Design · Explain the trade-offs. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Engineers choosing guarantees across services, time and failure boundaries.

Proposal envelope
Trusted tenant/actor, operation identity, tool version and normalized action arguments captured for review.
Approval digest
A hash identifying exactly which proposal was reviewed; integrity comparison alone does not authenticate an approver.
Permission epoch
A trusted authorization generation that changes when a permission is revoked or regranted.
Receipt replay
An authorized lookup of an already committed operation result; it does not dispatch a second effect.

How does the mechanism work?

Approval: intent identity and current authority at the effect boundary
  1. 1
    Requester

    Propose typed arguments under authenticated context.

  2. 2
    Intent store

    Freeze normalized semantics and a durable operation ID.

  3. 3
    Reviewer

    Approve the exact digest with current review authority.

  4. 4
    Executor

    Check digest, permission/epoch, expiry and resource preconditions.

  5. 5
    Business authority

    Commit one effect and receipt, or reconcile an existing receipt.

Digest identity, authorization and deduplication are separate predicates. The lab shares one SQLite authority; the design layer changes this constraint.

Step-by-step explanation
  1. Freeze

    Normalize units, targets and resource preconditions before review.

  2. Approve

    A separately authorized reviewer acknowledges that digest before expiry.

  3. Recheck

    Compare submitted semantics, current permissions, epoch and resource version.

  4. Commit or reconcile

    Write one local effect and receipt, or preserve unknown for external reconciliation.

Design · Explain the trade-offs

Move approval across independent services and tool upgrades

Objectives of this level: Define the meaning of revocation and approval validity when permissions, targets and effects do not share a transaction.

Visual guide · Approval binds a fixed intent

Approval binds a fixed intent

A digest identifies reviewed semantics, not an approver credential. The local transaction covers authority checks and effect commit, not a remote service. Select the figure to open it at full size.

Replace local SQLite execution with a remote transfer service. The authorization service is separate and the tool version can change defaults while a human review is waiting. A recheck in the orchestrator reduces stale decisions but cannot eliminate the interval before remote commit.

One design is an execution-side capability scoped to tenant, actor, tool/version, resolved destination, payload digest, operation ID, permission epoch and expiry. The resource service validates it and enforces deduplication. This adds issuer/key rotation, revocation propagation and retention obligations. If revocation must take effect immediately at commit, the resource authority needs access to sufficiently current authorization state or a shared ordering mechanism. If bounded leases are acceptable, state the maximum validity window; do not call it immediate revocation.

Resolve routing before review and constrain redirects. A stable digest over an abstract hostname is insufficient if the adapter can silently send to a different resource or account. Likewise, adding a default recipient or changing currency normalization in v3 changes semantics unless the old intent pins and expands those values. Re-review migrations that affect targets or amounts.

Compare synchronous approval for each write with scoped batch approval. Individual review improves intent visibility but adds latency; batching is useful only if approved bounds, target set, expiry and per-operation accounting are explicit. For a provider with no idempotency or reliable status query, an unknown outcome may need manual reconciliation. No local approval mechanism can prove that provider executed only once. Framework interrupts offer a pause point; resumable node code may run again, so place side effects behind the operation authority. Interrupt semantics.

A worked tradeoff under explicit numbers

Assume permission and transfer are independent services, review may wait two hours, and network partitions last up to 60 seconds. Design A requires current resource-side authorization at commit: it can enforce immediate revocation only with an adequately current shared ordering/authority, so a partition may block sends. Design B grants a scoped capability valid for 30 seconds: it can remain available within that lease but accepts a revocation window of at most the specified validity, subject to clock/validation assumptions.

Choose one contract explicitly. Both bind resolved recipients, exact content, tool version, requester/reviewer generations and one operation. Neither a two-hour-old orchestrator cache nor a matching digest supplies immediate revocation. If the remote response is missing, retain unknown and reconcile that same operation before another send.

Run experiments and observe counterexamples

Authored approval schedules and real local SQLite state transitions; no login, signed capability, network or external refund provider.

Python 3.10+ · Runs by default using only the standard library · Runs on your computer

  1. Run the isolated mutation, revocation, expiry and resource-version schedules.
  2. Compare stored proposal identity and actual local effect counts.
  3. Run ApprovalTests for replay and duplicate connections.
Download the complete application experiment package (including data and dependent scripts) ↓
python3 -B approval_deep_dive.py
View the entry-point script
"""Immutable approval and local atomic execution; offline teaching fixture.

Permission epoch, resource version, digest, expiry and duplicate dispatch are
checked against a single SQLite authority. No remote service is exercised.
"""
import hashlib
import json
import sqlite3


def normalize(args):
    required = {'order_id', 'amount_minor', 'currency', 'expected_version'}
    if type(args) is not dict or set(args) != required:
        raise ValueError('shape_fields')
    if type(args['amount_minor']) is not int or not 0 < args['amount_minor'] <= 1000:
        raise ValueError('amount_minor')
    if type(args['expected_version']) is not int or args['expected_version'] < 1:
        raise ValueError('expected_version')
    if args['currency'] != 'USD' or type(args['order_id']) is not str or not args['order_id']:
        raise ValueError('business_parameters')
    return dict(args)


def digest(envelope):
    # This profile permits only strings and integers. It is not general RFC 8785.
    return hashlib.sha256(json.dumps(envelope, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()


class ApprovalService:
    def __init__(self, path=':memory:'):
        self.db = sqlite3.connect(path, timeout=5, isolation_level=None)
        self.db.executescript('''
          CREATE TABLE IF NOT EXISTS permissions(tenant TEXT, actor TEXT, role TEXT, enabled INTEGER, epoch INTEGER,
            PRIMARY KEY(tenant,actor,role));
          CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY, tenant TEXT, remaining INTEGER, version INTEGER);
          CREATE TABLE IF NOT EXISTS proposals(tenant TEXT, operation_id TEXT, actor TEXT, envelope TEXT, digest TEXT,
            expires INTEGER, state TEXT, approver TEXT, result TEXT, approver_epoch INTEGER,
            PRIMARY KEY(tenant,operation_id));
          CREATE TABLE IF NOT EXISTS effects(tenant TEXT, operation_id TEXT, amount INTEGER, PRIMARY KEY(tenant,operation_id));
          INSERT OR IGNORE INTO permissions VALUES('tenant-a','user-a','execute',1,1);
          INSERT OR IGNORE INTO permissions VALUES('tenant-a','reviewer-a','approve',1,1);
          INSERT OR IGNORE INTO resources VALUES('order-a','tenant-a',1000,1);
        ''')
        # Existing local lab databases retain their receipts. An old pending
        # approval with no recorded reviewer epoch cannot authorize a new effect.
        if 'approver_epoch' not in {row[1] for row in self.db.execute('PRAGMA table_info(proposals)')}:
            self.db.execute('ALTER TABLE proposals ADD COLUMN approver_epoch INTEGER')

    def close(self):
        self.db.close()

    def permission(self, tenant, actor, role):
        return self.db.execute('SELECT enabled,epoch FROM permissions WHERE tenant=? AND actor=? AND role=?',
                               (tenant, actor, role)).fetchone()

    def prepare(self, tenant, actor, operation_id, args, now=100, expires=200):
        # tenant and actor are provided by server authentication, never model text.
        normalized = normalize(args)
        if type(operation_id) is not str or not 1 <= len(operation_id) <= 80 or expires <= now:
            raise ValueError('proposal_parameters')
        permission = self.permission(tenant, actor, 'execute')
        resource = self.db.execute('SELECT tenant,version FROM resources WHERE id=?', (normalized['order_id'],)).fetchone()
        if not permission or not permission[0] or not resource or resource[0] != tenant:
            raise ValueError('authorization')
        envelope = {'domain': 'refund-approved/v2', 'tenant': tenant, 'actor': actor, 'operation_id': operation_id,
                    'permission_epoch': permission[1], 'args': normalized}
        checksum = digest(envelope)
        prior = self.db.execute('SELECT digest FROM proposals WHERE tenant=? AND operation_id=?', (tenant, operation_id)).fetchone()
        if prior:
            if prior[0] != checksum:
                raise ValueError('operation_identity_conflict')
            return checksum
        self.db.execute('''INSERT INTO proposals
                        (tenant,operation_id,actor,envelope,digest,expires,state,approver,result)
                        VALUES(?,?,?,?,?,?,?,?,?)''',
                        (tenant, operation_id, actor, json.dumps(envelope, sort_keys=True), checksum, expires, 'pending', None, None))
        return checksum

    def approve(self, tenant, operation_id, approver, approved_digest, now=110):
        with self.db:
            self.db.execute('BEGIN IMMEDIATE')
            permission = self.permission(tenant, approver, 'approve')
            if not permission or not permission[0]:
                raise ValueError('approver_denied')
            row = self.db.execute('SELECT actor,digest,expires,state,approver,approver_epoch FROM proposals WHERE tenant=? AND operation_id=?',
                                  (tenant, operation_id)).fetchone()
            if not row or row[1] != approved_digest or now >= row[2] or row[0] == approver:
                raise ValueError('approval_invalid')
            if row[3] == 'pending':
                self.db.execute("UPDATE proposals SET state='approved',approver=?,approver_epoch=? WHERE tenant=? AND operation_id=? AND state='pending'",
                                (approver, permission[1], tenant, operation_id))
            elif row[3] not in ('approved', 'done') or row[4] != approver or row[5] != permission[1]:
                raise ValueError('approval_state')

    def revoke(self, tenant, actor, role='execute'):
        self.db.execute('UPDATE permissions SET enabled=0,epoch=epoch+1 WHERE tenant=? AND actor=? AND role=?', (tenant, actor, role))

    def execute(self, tenant, actor, operation_id, proposed_args, now=120):
        try:
            args = normalize(proposed_args)
        except ValueError as error:
            return {'status': 'denied', 'reason': str(error)}
        with self.db:
            self.db.execute('BEGIN IMMEDIATE')
            row = self.db.execute('SELECT actor,envelope,digest,expires,state,approver,result,approver_epoch FROM proposals WHERE tenant=? AND operation_id=?',
                                  (tenant, operation_id)).fetchone()
            permission = self.permission(tenant, actor, 'execute')
            if not permission or not permission[0]:
                return {'status': 'denied', 'reason': 'permission_revoked'}
            if not row or row[0] != actor:
                return {'status': 'denied', 'reason': 'proposal_missing'}
            original = json.loads(row[1])
            if permission[1] != original['permission_epoch']:
                return {'status': 'denied', 'reason': 'permission_epoch_changed'}
            submitted = dict(original, args=args)
            if digest(submitted) != row[2]:
                return {'status': 'denied', 'reason': 'proposal_changed'}
            if row[4] == 'done':
                return {'status': 'replayed', 'receipt': json.loads(row[6])}
            reviewer = self.permission(tenant, row[5], 'approve')
            if row[4] != 'approved' or not reviewer or not reviewer[0]:
                return {'status': 'denied', 'reason': 'approval_inactive'}
            if reviewer[1] != row[7]:
                return {'status': 'denied', 'reason': 'approver_permission_epoch_changed'}
            if now >= row[3]:
                return {'status': 'denied', 'reason': 'approval_expired'}
            resource = self.db.execute('SELECT tenant,remaining,version FROM resources WHERE id=?', (args['order_id'],)).fetchone()
            if not resource or resource[0] != tenant:
                return {'status': 'denied', 'reason': 'resource_denied'}
            if resource[2] != args['expected_version']:
                return {'status': 'denied', 'reason': 'resource_changed'}
            if resource[1] < args['amount_minor']:
                return {'status': 'denied', 'reason': 'insufficient_remaining'}
            self.db.execute('UPDATE resources SET remaining=remaining-?,version=version+1 WHERE id=? AND version=?',
                            (args['amount_minor'], args['order_id'], args['expected_version']))
            self.db.execute('INSERT INTO effects VALUES(?,?,?)', (tenant, operation_id, args['amount_minor']))
            receipt = {'operation_id': operation_id, 'amount_minor': args['amount_minor'], 'resource_version': resource[2] + 1}
            self.db.execute("UPDATE proposals SET state='done',result=? WHERE tenant=? AND operation_id=? AND state='approved'",
                            (json.dumps(receipt, sort_keys=True), tenant, operation_id))
            return {'status': 'committed', 'receipt': receipt}

    def state(self):
        return {'effect_count': self.db.execute('SELECT COUNT(*) FROM effects').fetchone()[0],
                'remaining_minor': self.db.execute("SELECT remaining FROM resources WHERE id='order-a'").fetchone()[0]}


ARGS = {'order_id': 'order-a', 'amount_minor': 300, 'currency': 'USD', 'expected_version': 1}


def approved_service(path=':memory:'):
    service = ApprovalService(path)
    checksum = service.prepare('tenant-a', 'user-a', 'refund-1', ARGS)
    service.approve('tenant-a', 'refund-1', 'reviewer-a', checksum)
    return service


def demo():
    changed = approved_service()
    revoked = approved_service()
    duplicate = approved_service()
    expired = approved_service()
    stale = approved_service()
    revoked.revoke('tenant-a', 'user-a')
    stale.db.execute("UPDATE resources SET version=2 WHERE id='order-a'")
    scenarios = [
        {'case': 'changed_amount', 'result': changed.execute('tenant-a', 'user-a', 'refund-1', dict(ARGS, amount_minor=800)), 'state': changed.state()},
        {'case': 'revoked_after_approval', 'result': revoked.execute('tenant-a', 'user-a', 'refund-1', ARGS), 'state': revoked.state()},
        {'case': 'expired', 'result': expired.execute('tenant-a', 'user-a', 'refund-1', ARGS, now=200), 'state': expired.state()},
        {'case': 'resource_changed', 'result': stale.execute('tenant-a', 'user-a', 'refund-1', ARGS), 'state': stale.state()},
        {'case': 'first_dispatch', 'result': duplicate.execute('tenant-a', 'user-a', 'refund-1', ARGS)},
        {'case': 'duplicate_dispatch', 'result': duplicate.execute('tenant-a', 'user-a', 'refund-1', ARGS), 'state': duplicate.state()},
    ]
    for service in (changed, revoked, duplicate, expired, stale):
        service.close()
    return {'origin': 'authored_approval_schedule_local_sqlite', 'scenarios': scenarios,
            'boundary': 'Permission check and effect share one authority. Independent remote authorization needs an execution-side capability/version check.'}


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, sort_keys=True))

Expected output when running locally

{
  "boundary": "Permission check and effect share one authority. Independent remote authorization needs an execution-side capability/version check.",
  "origin": "authored_approval_schedule_local_sqlite",
  "scenarios": [
    {
      "case": "changed_amount",
      "result": {
        "reason": "proposal_changed",
        "status": "denied"
      },
      "state": {
        "effect_count": 0,
        "remaining_minor": 1000
      }
    },
    {
      "case": "revoked_after_approval",
      "result": {
        "reason": "permission_revoked",
        "status": "denied"
      },
      "state": {
        "effect_count": 0,
        "remaining_minor": 1000
      }
    },
    {
      "case": "expired",
      "result": {
        "reason": "approval_expired",
        "status": "denied"
      },
      "state": {
        "effect_count": 0,
        "remaining_minor": 1000
      }
    },
    {
      "case": "resource_changed",
      "result": {
        "reason": "resource_changed",
        "status": "denied"
      },
      "state": {
        "effect_count": 0,
        "remaining_minor": 1000
      }
    },
    {
      "case": "first_dispatch",
      "result": {
        "receipt": {
          "amount_minor": 300,
          "operation_id": "refund-1",
          "resource_version": 2
        },
        "status": "committed"
      }
    },
    {
      "case": "duplicate_dispatch",
      "result": {
        "receipt": {
          "amount_minor": 300,
          "operation_id": "refund-1",
          "resource_version": 2
        },
        "status": "replayed"
      },
      "state": {
        "effect_count": 1,
        "remaining_minor": 700
      }
    }
  ]
}
  • Changed amount and revoked permission produce zero effects.
  • Expiry at 200 and stale resource version block new execution.
  • First/duplicate dispatch leave effect_count=1 and remaining_minor=700.
View the running environment, output and verification records →

code example

Batch approval needs a bound, not a broad role

A reviewer permits refunds totaling at most 10000 minor units to a fixed order set until a specified expiry. The resource authority must enforce aggregate/per-operation accounting under duplicate delivery. A support role plus approved=True cannot represent those bounds.

Acceptance task for this level

Write an approval contract for a remote send action with mutable DNS/routing, a separate permission service and a tool default upgrade. Choose immediate or bounded revocation and specify a timeout reconciliation path and a review-renewal trigger.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

When a tool changes its default recipient but the old JSON omitted recipient, does the old approval still apply?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.