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: Foundation · Understand the concepts. 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: Readers who can follow a request and its resulting state.

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.

Foundation · Understand the concepts

Why an approval cannot be a Boolean permission

Objectives of this level: Separate authenticated identity, authorization, reviewed intent and duplicate execution control.

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.

Suppose a reviewer approves refunding 300 minor units to order-a. The model later proposes 800. A stored approved=true answers whether something was approved; it cannot identify the amount and target. Accepting that Boolean would let an altered proposal borrow authority from the old one.

Approval is a statement about a particular normalized intent. Authentication tells who requests or reviews. Business authorization tells whether those actors currently have the relevant resource and role permissions. Approval records what was reviewed and when it expires. Idempotency tells whether the same operation already happened. These predicates protect different failure windows.

The local proposal envelope binds tenant, actor, operation_id, a fixed refund-approved/v2 domain, the requester's permission epoch and all action arguments including currency and expected resource version. The reviewer is stored separately and must have approve authority. A plain digest is not a bearer credential: knowing it cannot approve or execute a proposal without the server's authorization checks.

Review displays significant transaction data and invalidates changed semantics. This applies the transaction authorization guidance to an authored agent workflow. A tool result saying 'the user approved' is still untrusted input to the executor.

The exact reviewed action and three timelines

Use tenant-a/user-a as the requester and reviewer-a as a separately authorized reviewer. The original action is:

{"order_id":"order-a","amount_minor":300,"currency":"USD","expected_version":1}

Initially the resource has 1000 minor units/version 1 and no effects. Keep the three timelines independent.

  1. prepare → approve → propose amount=800 → execute: proposal_changed, remaining=1000/effect_count=0. The approved amount was 300.
  2. prepare → approve → revoke requester → execute: permission_revoked, remaining=1000/effect_count=0. Matching intent cannot grant current permission.
  3. prepare → approve → execute → duplicate execute: committed then replayed, remaining=700/effect_count=1. Revoke after that commit blocks later access; it cannot erase the completed effect.

A proposal envelope is the frozen action data being reviewed. A predicate is one required check. Authentication identifies actors; authorization supplies current permission; an approval digest identifies the reviewed data; operation identity controls duplicate effects. A known hash is not an authenticated review.

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

Expiry after commit is different from expiry before commit

A new action executed at its expires boundary is denied. An unchanged done operation may return its already stored receipt after that boundary if current access and identity remain valid. The latter reads history; it does not reuse expired review to dispatch again.

Acceptance task for this level

Use the three fixed timelines in this body. Label prepare, approve, revoke, dispatch and duplicate delivery with trusted actors and checked conditions. Compare revoke-before-commit with revoke-after-commit; do not combine the independent schedules.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

The digest matches the reviewed proposal, but the requester is no longer authorized. Can dispatch proceed?

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.