HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 45“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Human Approval, Audit Trails and Reversible Actions
The connector from Lesson 44 stopped billing.refund.create with needsapproval and zero upstream calls.
Course progress0%
Focus
24 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
AI-Powered Full Stack Development · Lesson 45 · AI Agents, Workflow Automation and Integrations
Lesson Overview
The connector from Lesson 44 stopped billing.refund.create with needs_approval and zero upstream calls. That refusal is only useful if the next step is a ticket a person can accept, an audit row that names who accepted it, and a way to undo the effect when the undo is real. A banner that says "AI-generated" is a disclosure. It is not approval. Approval is a second identity, a required role, and a write that uses the same idempotency key the proposal already carried.
TechLearningPro's case is Priya's invoice at Northwind. The operations assistant proposes a refund. Sam, who asked for the draft, cannot approve it. A support lead approves that ticket id. The executor calls the billing adapter once. A second click on Approve returns the stored effect and does not create a second refund. If the refund succeeded and the product policy allows reversal, a lead can compensate with a compensating operation, and the audit grows by append. If the mail transport already delivered a message, compensation does not pretend to unsend it.
This lesson implements proposeAction, decideApproval, executeApproved, and compensate. The model may be the drafter recorded on the ticket. The model is never the approver. Policy version is ops-approval-v1. Lesson 46 will wrap these calls with budgets and retries. The capstone will pause a workflow on awaiting_approval and resume it with the ticket id.
Planning assumptions:
The lab stores tickets and audit events in memory. Production uses PostgreSQL with an append-only audit table.
Illustrative approval TTL is 24 hours. Refund and queued-email cancel are reversible. Delivered mail and certificate.issue are not silently reversed.
The executor calls a port named commit. It does not reimplement HTTP. The commit port is the write half that Lesson 44 deliberately omitted.
Audit snapshots store argument ids and a hash. They do not store secret handles, email bodies, or raw prompts.
Fixtures use synthetic invoice and learner ids.
Lesson 20 introduced the risk tier and the review ticket. This lesson is that ticket attached to a business operation the agent actually proposed.
Learning Objectives
By the end of this lesson you will be able to:
Turn a needs_approval connector result into a durable ticket.
Separate the drafter, the approver, and the executor.
Refuse self-approval and refuse a model identity as approver.
Require support_lead or admin for refund and email tickets.
Bind the ticket to tenant, operation, canonical args, and idempotency key.
Expire a ticket that sits past the TTL without calling upstream.
Execute an approved ticket once through the commit port.
Replay the same approval decision without a second effect.
Append an audit event for propose, approve, reject, execute, and compensate.
Compensate a reversible effect with a registered inverse operation.
Refuse compensation when the effect is delivered mail or an irreversible class.
Hash arguments so the audit can detect a swapped payload.
Keep the approver's reason code in a closed set so free text is not an instruction to the executor.
Test separation of duties, replay, expiry, and a failed compensate without a vendor key.
Explain why a rejected ticket leaves the system of record unchanged.
You can read a TypeScript discriminated union. You do not need a billing or email vendor key.
What is Human Approval with an Audit Trail?
Human approval is a workflow state in which a named person with a required role accepts a specific proposed effect. The proposal already passed the connector's schema. Approval adds identity and intent. Until that transition, the product has a row in pending and no row in the billing system.
An audit trail is the append-only history of those transitions. Each event names the tenant, the ticket, the actor, the role, the action, the policy version, and the argument hash. Events are inserted. They are not updated in place. A correction is a new event.
A reversible action is an effect the catalog marked write_reversible and for which you implemented an inverse: refund to credit reversal, or cancel of a message that is still queued. Reversible does not mean "delete the row and forget." It means a second operation, itself audited, that the system of record understands. An effect that has already left your boundary, such as a delivered email, is operationally irreversible even if the catalog class was write_reversible.
These controls predate agents. Banks separate the person who prepares a payment from the person who releases it. The agent made the preparer cheap and fluent, which is why the release step has to be code.
Term
Meaning in this lesson
Ticket
The durable proposal waiting for a decision
Drafter
The staff user or the assistant run that proposed the action
Approver
A different staff user holding support_lead or admin
Policy version
ops-approval-v1
Argument hash
SHA-256 of canonical JSON args
Effect id
The id the commit port returns after a successful write
Compensate
A second commit that inverts a reversible effect
Replay
The same decision id returns the stored outcome
Why Do We Need It?
text
Connector returns needs_approval
|
v
A route treats the staff click as enough and calls billing
|
v
The drafter approves their own refund, twice
|
v
Ticket + separation of duties + one commit + append-only audit
|
v
One effect, a named approver, and a compensation path when the inverse exists
Benefits:
The system of record changes only after a person who did not draft the action says so.
A double-click cannot double-refund, because the idempotency key is the ticket id.
Support can reconstruct who proposed, who approved, and which effect id came back.
Compensation is an explicit operation, so "undo" is visible in the same audit.
Lesson 46 can retry a commit only when this layer reports an unknown outcome, not when it reports success.
Real World Example
The assistant proposes billing.refund.create for inv_priya_1 with idempotency key idem_refund_01. proposeAction stores a ticket in pending, writes an audit event proposed, and returns the ticket id. Sam's user id is the drafter, so Sam's approve call returns separation_of_duties. A support lead approves. executeApproved calls commit once and stores effectId: "re_01". The lead approves again with the same decision id. The second call does not call commit. Later the lead compensates. The inverse is billing.refund.reverse in this lesson's commit port, audited as compensated. A parallel email ticket whose adapter reports delivered returns not_reversible on compensate. The message is already in the learner's inbox. The honest follow-up is a new ticket, not a delete.
A bank wires payment with the same split: maker, checker, immutable journal, and a reversal entry rather than a vanished row. A hospital order is signed by a clinician and cancelled with a new order, not by editing history. Amazon-style refunds and Microsoft commerce refunds record the approver and the processor id. Google-style admin actions in Workspace write an admin audit log the actor cannot edit. TechLearningPro's version is the support lead, the ticket, and the effect id.
Internal Working
proposeAction requires a connector result of needs_approval for this tenant. A read result is not_a_write.
Canonicalize args (sorted keys, no undefined) and hash them. Store the hash and the args. The hash is what executeApproved rechecks.
Insert the ticket as pending with expiresAt = now + 24h, drafter user id, operation id, effect class, and idempotency key. Append audit proposed.
decideApproval loads the ticket in the approver's tenant. A missing ticket is not_found (do not reveal other tenants).
If now > expiresAt and status is pending, mark expired, audit expired, and return expired without commit.
If the approver user id equals the drafter user id, return separation_of_duties.
If the approver id is model or the role is not support_lead or admin, return forbidden.
Reject decision reasons outside customer_request, policy_exception, duplicate_charge. Free text is stored only as an optional note capped at 200 characters and is never sent to the vendor.
On reject, set rejected, audit rejected, and do not call commit.
On approve, set approved only if still pending. Replay of the same decisionId returns the current ticket.
executeApproved runs only for approved with an empty effectId. It calls commit with the ticket's idempotency key. Success stores the effect id and audits executed. A timeout stores execution_unknown and does not automatically retry.
compensate requires executed, effect class write_reversible, and a port that reports the effect still reversible. It commits the inverse once, stores compensationEffectId, sets compensated, and audits compensated.
Architecture
sequenceDiagram
participant Panel as Operations panel
participant Prop as proposeAction
participant Dec as decideApproval
participant Ex as executeApproved
participant Commit as Commit port
participant Audit as Audit log
Panel->>Prop: needs_approval payload
Prop->>Audit: proposed
Panel->>Dec: support lead approves
Dec->>Audit: approved
Panel->>Ex: ticket id
Ex->>Commit: idempotency key = ticket key
Commit-->>Ex: effect id
Ex->>Audit: executed
text
needs_approval (Lesson 44)
|
v
proposeAction --> ticket pending + audit proposed
|
+--> drafter approves --> separation_of_duties
+--> TTL elapsed --> expired
|
v
support_lead approves --> status approved
|
v
executeApproved --> commit once
|
+--> timeout --> execution_unknown, no blind retry
|
v
effect id stored + audit executed
|
+--> compensate if still reversible
|
v
audit compensated, original events kept
The browser never receives a secret handle. The commit port receives the ticket's stored args, not a fresh model payload, so a prompt cannot change the invoice id between proposal and execution.
Deep Dive
One ticket, one payload
The ticket freezes the operation and the args at propose time. executeApproved does not accept a new args object from the client. If support needs a different invoice, they reject this ticket and propose another. That rule stops a race where the panel shows invoice A and the executor sends invoice B because the model streamed a correction.
The argument hash is SHA-256 over canonical JSON. Canonical means object keys sorted alphabetically, no whitespace significance, arrays kept in order. The lab uses JSON.stringify on a sorted copy. Production can use the same bytes. If the hash stored on the ticket ever differs from a rehash of stored args, execution returns payload_tamper and does not commit. That check matters when a bug writes the args column and the hash column through different paths.
Separation of duties
The drafter is input.drafterUserId, a staff id from the session that created the proposal. The assistant run id is recorded as drafterRunId for the audit and is not an account that can approve. Comparing approver to drafter is a string inequality on user ids. A support lead who also chatted with the model can approve only when their user id is not the drafter id. If your process requires the lead to be the one who clicked "propose," pick a different lead for approval or split the roles in the roster. The code will not special-case a hero account.
role comes from the session, not from the body. A client field named role: "admin" is ignored.
Decision ids and idempotency
decisionId is a UUID the panel creates for the approve click. The unique key is tenant, ticket id, and decision id. Replaying it returns the stored decision. A new decision id against an already approved ticket returns already_decided and does not change the approver. Execution idempotency is the ticket's original idempotencyKey, passed to the vendor. Two layers, two bugs prevented: double decisions, and double effects if the vendor times out after commit.
When commit returns unknown, status becomes execution_unknown. A person can call executeApproved again. The port must send the same idempotency key. The vendor then returns the original effect or creates it once. The lab's fake records the key and returns the same effect id. Lesson 46 is not allowed to clear that key and mint a new one.
What compensation is allowed to do
Effect
Inverse in this lesson
Refusal
Refund committed
billing.refund.reverse
Vendor says already settled to a payout
Email still queued
messaging.email.cancel
Status delivered
Certificate issued
none in v1
not_reversible
Compensation is itself a commit. It requires support_lead or admin, and it requires the actor to differ from the original drafter. It does not require a second ticket, because the inverse is determined by the catalog, not by the model. The actor still gets an audit event. If you later decide certificate reversal needs its own proposal, register it as a new operation and send it through proposeAction. Do not hide it inside compensate.
Delivered email is the teaching case. The transport status is authoritative. Your database flag sent: true is not, if the worker crashed before updating it. compensate asks the port describe(effectId) and trusts that response. If describe fails, return unknown_effect_state and do not cancel.
There is no update method on the audit port. Tests fail if a ticket's past event changes when a later event is appended. Notes, when present, are the capped reason note. They are not the model transcript. The transcript, if you retain it, lives in the agent run store from Lesson 38 under its own retention rule, not in the financial audit.
Clocks and expiry
Use the server clock passed as now: Date. Tests inject time. A ticket approved one minute before expiry may still execute. A pending ticket past expiry cannot be approved. An approved ticket past the original TTL can still execute in this policy, because a person already decided. Document that. If your risk team wants execution TTL as well, add executeBefore at approve time and enforce it in executeApproved. The lab keeps one TTL on the pending state so the story stays testable.
What the model still cannot do
The model cannot set status, cannot supply the approver id, and cannot call commit. A tool named approve_refund is a defect. The panel buttons call your routes, and the routes call these functions with the session. Streaming UI from Lesson 42 may show "Waiting for approval." It may not render a control that posts the drafter's own user id as the approver.
Code Examples
Place the package in packages/approvals/src/. The composition root injects commit and describe.
The first test is the separation-of-duties and replay contract. The second test is the delivered-mail contract: describe says not reversible, and compensate does not append a fake unsend. The commit fake keys off idempotencyKey, which is how a repeated execute stays at one vendor call.
executeApproved --> commit port (write credential)
|
+--> executed + effect id
+--> execution_unknown (same idempotency key on retry)
|
v
compensate --> describe, then inverse commit
|
v
audit compensated (prior events unchanged)
Trust split:
text
Model run id --> drafterRunId on the ticket
Session user --> drafter or approver
Session role --> support_lead gate
Frozen args --> the only payload commit sees
Real-Time Enterprise Example
In production, tickets and audit events are PostgreSQL tables. audit_events has no UPDATE grant for the application role. Northwind's support lead approves Priya's refund during the TTL. The commit adapter uses the write handle billing-write/northwind, which the read path from Lesson 44 never loaded. The vendor returns re_01. Finance joins effect ids to the processor report. A replayed approve click hits the decision id unique index and returns the same ticket.
A synthetic probe proposes a refund as usr_sam and attempts approval as usr_sam with role support_lead. It expects separation_of_duties and an empty commit log. A second probe marks an email effect delivered and expects not_reversible.
Challenge: two leads click Approve, the vendor times out after charging once, and the tenant's privacy review forbids storing the learner's email on the ticket. The decision id unique key keeps a single approver. execution_unknown plus the original idempotency key recovers the effect without a second charge. The ticket stores learnerIds and invoiceId, not an email address, so the privacy review does not require a new column. You do not "fix" the timeout by minting a new idempotency key. You do not let the model approve because the lead is offline. The ticket expires, and a person proposes again tomorrow.
Performance Optimization
Propose and decide are point writes. They should not call the model and should not call the vendor. The expensive call is commit, and it happens once per ticket on the success path. Index tickets by tenant and status so the queue page does not scan the audit table. The queue reads tickets. The investigation screen reads audit for one ticket id.
Do not put the audit insert in a background queue that can lag behind the commit. The event and the status change belong in one database transaction. A worker that "writes audit later" will lose the approver during a crash. Compensation is rare. It does not need a cache.
Expiry can be lazy, as the lab does on decide, plus a periodic sweep that marks pending rows expired so the queue count is honest. The sweep does not call commit.
The panel polls ticket status. It does not hold a transaction open while a person reads the invoice in another system. Long-lived locks on the ticket row will make the second lead's click time out. Use a short transaction that re-reads status and updates if still pending.
Security
Authentication. Actors come from the session. userId: "model" cannot be minted by the client.
Authorization. Propose is staff. Approve and compensate require support_lead or admin. Drafter and approver differ.
Tenant isolation.findTicket includes tenantId. Another tenant's ticket id is not_found.
Payload integrity. Execute rehashes args. Client execute routes do not accept args.
Replay. Decision id and commit idempotency key stop double effects.
Audit integrity. Append-only. Application role cannot update events.
Secrets. Commit credentials stay in the write adapter. Audit has no handle column.
Notes. Reason codes are an enum. Free text never becomes a vendor field.
Injection. The model cannot transition status through a tool argument.
OWASP. This path is broken access control, repudation (missing audit), and integrity failures. The controls are the role gate, the append-only log, and the hash.
Common Mistakes
Letting the drafter approve. Symptom: one person moves money. Cause: the same session called propose and decide. Fix: separation_of_duties.
Sending fresh args into execute. Symptom: the invoice id changes after the lead read the ticket. Cause: the route trusted the body. Fix: load args from the ticket.
Updating audit rows. Symptom: the approver name changes after a complaint. Cause: an UPDATE on the event. Fix: append a correction event. Revoke UPDATE.
Deleting a sent email in your database and calling it undo. Symptom: the learner still has the mail, your UI says cancelled. Cause: compensate skipped describe. Fix: trust transport status. Delivered means not_reversible.
Minting a new idempotency key on timeout. Symptom: two refunds. Cause: the retry looked like a new operation. Fix: reuse the ticket key. Status execution_unknown is the signal.
Storing the prompt on the financial audit. Symptom: learner questions sit in the finance warehouse. Cause: "we might need context." Fix: store hashes, ids, and reason codes. Keep transcripts in the run store.
Using the model as approver when the queue is long. Symptom: a tool approve_refund exists. Cause: latency pressure. Fix: expire and staff the queue. There is no model role that passes LEAD_ROLES.
Approving a read. Symptom: lookup tickets clutter the queue. Cause: propose accepted every connector result. Fix: only needs_approval proposals.
Ignoring expiry until execute. Symptom: a week-old pending ticket still approves. Cause: TTL was display-only. Fix: decideApproval writes expired and skips commit.
One commit credential shared with the read connector. Symptom: the Lesson 44 process can refund if a bug skips the ticket. Cause: a single token. Fix: write handles load only in the approval executor.
Returning another tenant's ticket on id match. Symptom: a guessed UUID shows Contoso's invoice id. Cause: findTicket used the id alone. Fix: tenant plus id, and not_found either way.
Treating compensation as a silent delete. Symptom: the original executed event disappears. Cause: status was overwritten in the log. Fix: append compensated and keep executed.
Best Practices
Freeze args at propose time.
Hash canonical JSON and verify it before commit.
Require a human approver who is not the drafter.
Take role from the session.
Keep reason codes in a closed set.
Append audit in the same transaction as the status change.
Grant the app insert on audit and not update.
Use the ticket idempotency key for the vendor call.
Use a separate decision id for the button click.
Map vendor timeout to execution_unknown.
Retry unknown execution only with the same key.
Ask the system of record whether an effect is still reversible.
Refuse to unsend delivered mail.
Keep irreversible operations out of compensate.
Store ids, not email bodies or prompts.
Expire pending tickets on a server clock tests can set.
Do not call the model inside decide or execute.
Load write credentials only on this path.
Return not_found for cross-tenant ticket ids.
Show "Waiting for approval" in the UI without an auto-approve control.
Test self-approval, replay, expiry, tamper, and delivered mail.
Document ops-approval-v1 beside the policy constant.
Leave a runbook: who can approve, how long the TTL is, and how to replay execution_unknown.
Interview Questions & Answers
Beginner
What is the difference between a disclosure and an approval?
A disclosure tells the learner or the staff user that a model drafted something. An approval is a different person, with a role, accepting a specific ticket. The refund does not run between those two events.
Why can't Sam approve Sam's proposal?
Separation of duties. The person who prepared the change should not be the person who releases it. The check is on user id, even if Sam's role was updated to support lead before the click.
What does the audit store?
Who did what, to which ticket, under which policy version, with an argument hash and an optional effect id. It does not store the vendor token or the model transcript.
Intermediate
What happens if the vendor times out?
The ticket becomes execution_unknown. A later executeApproved sends the same idempotency key. The vendor returns the original effect if it committed, or commits once if it did not. A new key would risk a second refund.
Why is delivered email not reversible?
The message has left your boundary. Deleting your outbox row does not remove it from the inbox. describe reports reversible: false, and compensate returns not_reversible. A correction is a new proposed message.
Why does execute ignore client arguments?
The lead approved a frozen payload. Accepting new args would let the invoice id change after the decision. The hash check catches tampering of the stored row. The route shape prevents tampering from the client.
Senior
How do you test this without billing?
Fake commit and describe. Assert the drafter's approve does not call commit. Assert two executes share one idempotency key and one call. Assert a non-reversible describe does not call the inverse. Assert audit actions accumulate and old events stay put.
Where should the model transcript live?
On the agent run record, with the retention rule from your privacy lesson. The financial audit should still make sense if the transcript is deleted. Hashes and effect ids are enough to show what was committed.
Architect
How do you add a two-person rule for certificates?
Register certificate.issue as write_irreversible. Extend the ticket with secondApproverUserId and require two distinct leads before approved. Do not overload compensate to revoke certificates. A revoke is a new operation with its own proposal if product and policy allow it.
What do you do when approve volume exceeds the lead roster?
Shorten what needs approval. Reads stay on Lesson 44. Low-risk drafts can publish without a ticket. Refunds and mail stay in this queue. You staff or delegate the lead role. You do not add a model approver to drain the queue. Expiry keeps stale proposals from becoming a surprise on Monday.
How does this interact with the connector's read credential?
It must not. The commit port uses a write handle loaded in this process path. A bug in executeBusinessCall still cannot refund if that process lacks the write token. Defense in depth is the effect-class check plus the credential split.
How do you prove the audit later?
Periodically hash the audit chain or ship events to an immutable store. The application proof is the missing UPDATE grant and tests that append. External proof is a warehouse or ledger your app role cannot rewrite. Policy version on each row tells you which rules applied when the lead clicked.
Knowledge Check
1. What problem does this capability solve?
It turns a refused write into a single, attributable effect: a person who did not draft the action approves a frozen payload, the vendor is called once, and a reversal is a new audited operation when the effect is still reversible.
2. What alternatives exist, and when would you choose each?
A synchronous confirm dialog is enough for a human clicking Refund in a form you rendered, and it should still write an audit row. A ticket queue is what you want when a model proposed the action. Auto-approval fits nothing in the refund and outbound-mail set. Chatty "the model decided it was fine" is a log line, not a control.
3. Which data, identity, and trust boundaries matter?
Session identity and role, drafter versus approver, tenant on the ticket, frozen args, and the write credential. The model run is a drafter label. The vendor is called only by commit. Audit is append-only and payload-light.
4. What can fail, and how should the system respond?
Self-approval, wrong role, bad reason codes, expiry, and cross-tenant ids stop before commit. Vendor timeout becomes execution_unknown with the same key. Delivered mail and irreversible classes refuse compensation. Tampered hashes refuse execution.
5. How would you test quality, security, performance, and cost?
Tests cover separation of duties, single commit, replay, expiry, tamper, and non-reversible describe. Security tests assert cross-tenant not_found and no secrets in audit JSON. Performance tests assert propose and decide do not call the vendor. Cost tests assert a double approve click does not create two billable effects.
Practical Exercise
Implement packages/approvals/src/ and run the tests. Add an expiry case: propose, move now past 24 hours, and assert expired with zero commits. Write three sentences on how the route will load the lead's role from the session and ignore a role field in the JSON body.
Deliverable and Rubric
Submit the state diagram, the approvals package, the test output, a sample audit list for one refund, and a note on which effects you refuse to reverse.
Area
Weight
Conceptual accuracy and architecture
20%
Working implementation and code quality
25%
Security, privacy, and responsible AI
20%
Testing, reliability, and observability
20%
Documentation and decision rationale
15%
Production checklist:
Only needs_approval payloads become tickets.
Args are frozen and hashed.
Drafter and approver are different user ids.
Role comes from the session.
Pending tickets expire on the server clock.
Commit runs at most once per idempotency key.
Timeout uses execution_unknown and the same key.
Audit is append-only and free of secrets and prompts.
Delivered mail returns not_reversible.
Write credentials are absent from the read connector.
The model has no approve tool.
Key Takeaways
Approval is a second person and a role, not a disclosure banner.
Policy version ops-approval-v1 is stored on every audit event.
The ticket freezes operation, args, hash, and idempotency key.
The drafter cannot approve.
The model cannot approve.
Execute sends stored args only.
One idempotency key means one vendor effect.
Timeout is execution_unknown, not a new key.
Audit is append-only.
Compensation asks the system of record if the effect is still reversible.
Delivered mail is not reversible.
Irreversible classes do not use compensate.
Reason codes are an enum.
Cross-tenant ticket ids are not_found.
Lesson 46 may retry only within this idempotency contract.
Summary
Lesson 45 is the release step Lesson 44 refused to improvise. Proposals become tickets, leads decide, the commit port performs one write, and the audit keeps every transition. Reversal is a second operation when the vendor still allows it. When the vendor does not, the product says so. The assistant can prepare work. It cannot be the name on the approval line.
Next Lesson Preview
Next is Agent Reliability, Guardrails and Failure Recovery. You will put budgets, schema checks, and recovery around the connector and this approval flow: when a read may be retried, when a commit must keep its idempotency key, and when the workflow should checkpoint and wait instead of looping. The ticket rules you just wrote stay the source of truth for whether a write happened.