13A.3 AI UX II: Trust, Transparency, Feedback and Human-in-the-Loop

Ship & get hiredLesson 3 of 818,000 words8 parts
Module 13A · 0 of 8 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8

An LLM feature can be fast, accurate on your eval set and cheap to run, and still fail as a product — because users don't know when to believe it, can't see why it answered, have no way to correct it, and quietly stop checking its work. This lesson is about the layer that decides whether people trust your AI feature enough to use it well: calibrated trust, honest expectation-setting, disclosure, showing evidence, user control and autonomy, feedback design, memory UX, and the dark patterns you must refuse to ship. It also builds the three ai_product modules that turn these ideas into code: an approval gate, a review queue and a feedback store that feeds your eval sets.

What you'll learn

  • What calibrated trust is, why under-trust and over-trust are symmetric failures, what two decades of research plus the Microsoft HAX guidelines and Google PAIR guidebook actually say, and how to measure whether trust is calibrated in production
  • How to set expectations: capability statements, first-run states, limitation notices, and writing an "AI can be wrong" notice that people actually read
  • Disclosure done properly: telling users they're talking to AI, labelling AI content, drawing agent/human boundaries, choosing a persona without manufacturing false accountability
  • How to show evidence: citations, "show your work", explanation patterns that inform rather than persuade, honest uncertainty display, abstention UX and comparison views
  • The autonomy dial (suggest → draft → ask-before-acting → act-and-notify → act silently), the human-in-the-loop patterns that keep people effectively in the loop, standing approvals that reduce approval fatigue without removing the gate, and the ApprovalGate and ReviewQueue code
  • How to repair trust after a visible failure: say what happened, scope it, fix it in place, show the class of error is handled
  • How to design feedback — explicit and implicit signals, reason taxonomies, consent, and the pipeline that turns feedback into eval cases (ai_product/feedback.py)
  • Memory and personalisation UX: showing what is remembered and giving users real control over it
  • The dark patterns specific to AI UX — sycophancy, fake urgency, hidden AI, nudged acceptance — and how to audit your own UI against them
  • The pattern catalogue, the pre-launch trust checklist, and where every idea maps to code

What you don't need

  • API keys. Every code sample runs on fixtures with the standard library; the FastAPI sketch is labelled illustrative and is never executed.
  • Design-tool experience. Wireframes are ASCII and Mermaid; "design" here means decisions and copy, which you can write in a text file.
  • Module 13A's earlier lessons to follow the code — each ai_product file is self-contained. Links point forward to 13A.2, 13A.4 and the capstone builds where the same modules get used at scale.

Setup

This lesson's three modules are pure standard library — no installs, no keys, no services. To try them:

bash
uv init ai-product --bare --python 3.13 && cd ai-product
mkdir -p ai_product

Save each code block below as the file named in its heading (ai_product/approval.py, ai_product/review_queue.py, ai_product/feedback.py), then run the demo at the end of each section with uv run python ai_product/<file>.py. The FastAPI sketch in Part 8 needs uv add fastapi "uvicorn[standard]" (checked against FastAPI 0.162.0 and uvicorn 0.54.0, as of November 2026) and is illustrative — read it, don't run it.


What you must be able to do after this lesson#

  • Explain calibrated trust and the two symmetric failures
  • Write a limitation notice and disclose AI use where users see it
  • Show evidence with citations and honest uncertainty
  • Choose a level on the autonomy dial and add human-in-the-loop checks
  • Audit a UI for AI dark patterns such as sycophancy and fake urgency
  • Turn feedback signals into eval cases

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Users keep approving everything without reading." 4.5 Keeping the human effectively in the loop
"Legal says we need an AI disclosure — where does it go?" 2.4 Telling users they're talking to AI
"Should we show the model's confidence score?" 3.5 Uncertainty display
"The model explains its answer, so users will trust it appropriately." 1.3 What the research actually says — the evidence says otherwise
"Let's add a thumbs-down button and call it feedback." 5.1 Explicit signals and 5.6 Anti-patterns
"The agent should just handle it — approvals slow everything down." 4.1 The autonomy dial
"Users said the bot feels cold; let's give it a name and a backstory." 2.7 Persona and anthropomorphism
"We're an AI company, why hide that it's AI?" 7.3 Auditing your own UI — hidden AI is a dark pattern, not a growth hack
"The review queue is backed up — let's auto-approve the low-risk ones." 4.2 HITL patterns and when each applies and 4.4 Review queues and confidence routing
"Can we make the assistant nicer by never disagreeing with the user?" 7.1 The landscape — that's sycophancy by design
"What does the bot actually remember about me?" 6.2 Showing what is remembered

Part 1: Calibrated trust#

1.1 What "trust" means for an AI feature#

Trust is not a single dial you turn up or down. For an AI feature, trust is a per-task judgement: "for this kind of request, on this kind of data, is this output likely to be right enough that I can act on it?" A user can trust your invoice extractor on clean PDFs and distrust it on handwritten scans — simultaneously, correctly.

Three distinctions matter before any design work:

  • Trust vs reliance. Reliance is behavioural: did the user act on the output? Trust is the attitude behind it. A user can rely on an output they don't trust (because policy forced them to) and trust an output they don't rely on (because they checked it anyway). Measure both; they diverge in interesting ways.
  • Appropriate reliance is the goal, not maximum trust. The failure isn't "users don't trust us" or "users trust us too much" in the abstract — it's the mismatch between how much users trust the system and how much they should. A system that is 95% accurate but makes confident, silent errors on the other 5% needs users who verify the risky 5%. Perfect trust in a 95% system is a liability; calibrated trust is the asset.
  • Trust is built from evidence, not adjectives. "Powered by advanced AI" builds no calibrated trust. Citations, visible limits, honest failure messages and correctable outputs do. Every later part of this lesson is, at bottom, an evidence-delivery mechanism.

1.2 The two symmetric failures#

The automation literature — starting with Parasuraman and Riley's 1997 review "Humans and Automation: Use, Misuse, Disuse, Abuse" (Human Factors 39(2):230–253) — names the four ways humans relate to automation. For AI products, two of them are your UX problem:

Failure What it looks like Who pays
Misuse / over-trust (complacency, automation bias) Users accept fluent, confident output without checking; errors propagate into real actions (wrong refund issued, wrong figure in a report, bad code shipped) The user, the business, sometimes a third party
Disuse / under-trust (algorithm aversion) Users ignore the feature, re-do the work manually, or only use it for trivia. The feature's value never materialises You — the feature is dead on arrival

Both are calibration failures, and they are symmetric in cost: an unused feature costs its build cost; an over-trusted feature costs whatever its worst confident error costs. Dietvorst, Simmons and Massey's "Algorithm Aversion" study (Journal of Experimental Psychology: General 144(1):114–126, 2015) showed the asymmetry that makes this urgent: people lose confidence in an algorithm faster than in a human after seeing it make the same mistake — and abandon it even when it outperformed the human. One visible confident error can poison a feature permanently. Conversely, users who never see a failure may inflate trust until the first one lands catastrophically.

1.3 What the research actually says#

Before designing, know what the evidence supports — because intuition here is often wrong.

The guidelines. Microsoft's Guidelines for Human-AI Interaction (Amershi et al., CHI 2019; the HAX Toolkit at microsoft.com/en-us/haxtoolkit) synthesised 20+ years of HCI research into 18 guidelines organised across a product's life: Initially (make clear what the system can do, and how well), During interaction (time services to context, show relevant information, match social norms, mitigate social biases), When wrong (support efficient invocation, dismissal and correction; scope services when in doubt; make clear why the system did what it did), and Over time (remember recent interactions, learn cautiously, update and adapt cautiously, encourage granular feedback, convey the consequences of user actions, provide global controls, notify users about changes). They were validated with 49 design practitioners testing 20 popular AI products. Google's People + AI Guidebook (pair.withgoogle.com/guidebook, first published May 2019, updated since) covers the same ground through six chapters — user needs, data, mental models, explainability and trust, feedback and control, errors — with a practical pattern library. Apple's Human Interface Guidelines now include a Generative AI page whose guidance (read 12 November 2026) includes communicating where your app uses AI and keeping people in control of AI output (dismiss, revert, retry).

Explanations don't calibrate trust — they raise acceptance. This is the most-cited, most-misunderstood result in the field. Bansal et al., "Does the Whole Exceed its Parts?" (CHI 2021, >1,500 participants, three tasks) found that AI explanations increased the chance humans accepted the AI's recommendation regardless of its correctness, and did not improve complementary team performance over simply showing the AI's confidence. Zhang, Liao and Bellamy (IBM, FAT* 2020) found confidence scores help calibrate trust but calibration alone doesn't improve outcomes — the human still has to bring knowledge the model lacks. Buçinca, Malaya and Gajos (CSCW 2021, N=199) found that cognitive forcing functions — designs that make people engage analytically before seeing the AI's answer — significantly reduced over-reliance, but users rated those designs least favourably. The lesson for you: explanations are necessary but not sufficient, and the most effective debiasing designs are the ones users like least. Design for the trade-off knowingly.

Confidence numbers are weak signals. Models' verbalised confidence ("I'm 90% sure") is poorly calibrated — see 02.10, Part 12, which shows stated confidence near-identical for right and wrong answers. What can be shown honestly is covered in 3.5.

Escalation beats blind trust. Jung, Brahman and Choi, "Trust or Escalate" (ICLR 2025), showed that selectively trusting an LLM judge only where its confidence proxy is reliable — and escalating the rest to humans — can guarantee a target human-agreement level. The same shape works for user-facing features: route by measurable signals, not by the model's self-report.

Misleading evidence is a real attack — on your users. Lakkaraju and Bastani, "'How Do I Fool You?': Manipulating User Trust via Misleading Black Box Explanations" (AIES 2020), showed explanations can be crafted to inflate trust in a flawed model. In your product the equivalent is UX theatre: progress spinners that imply verification, "verified" badges that mean nothing, confidence bars driven by vibes. Users who catch one fake signal discount all your real ones.

1.4 The design goal: a trust budget#

Calibrated trust has a practical formulation. For each feature, decide:

  1. What must the user know? Capability, limits, cost of error, what to check — stated once, honestly, where decisions happen.
  2. What evidence will they see per task? Citations, source regions, tool calls, confidence proxies, abstention — whatever the output type supports.
  3. What control do they have? Correct, undo, escalate, adjust autonomy — proportional to the error cost.
  4. What happens over time? Changes are announced, feedback visibly improves things, memory is inspectable.

Think of it as a trust budget: every dishonest or confusing element spends it; every verifiable element earns it back. You can't buy trust with adjectives; you can only stop spending it.

flowchart LR
    subgraph failures ["The two calibration failures"]
        A["Under-trust<br/>(disuse, algorithm aversion)"] --- B["Calibrated trust<br/>(reliance matches real reliability)"] --- C["Over-trust<br/>(misuse, complacency, automation bias)"]
    end
    A -.->|"feature ignored,<br/>value never realised"| D((cost))
    C -.->|"confident errors<br/>act silently"| D
    B -.->|"users verify<br/>exactly what needs it"| E((value))

What this means for you as an engineer: before any UX pixel, write down your feature's error cost and your abstention/verification story. If you can't say "the user should check X because Y", you haven't designed trust — you've designed a black box with a chat bubble. The rest of this lesson is the toolkit for fixing that.

1.5 Measuring calibrated trust#

"Calibrated" is a claim you can test, and the test has two sides: what users do with the output (reliance) and what they check before relying on it (verification). Neither alone is enough — and neither means anything unsegmented, because calibration is per-task (1.1). Slice every metric by the dimensions where errors concentrate — risk tier, query type, document quality, user segment — before drawing conclusions.

Behavioural metrics — log these at the event level. They belong in the 13A.2 event contract; you cannot reconstruct them later:

Metric Definition What it diagnoses
Reliance rate Outputs acted on (sent, applied, exported) ÷ outputs shown Under-trust when low on slices where the feature should help; the adoption ceiling
Verification rate Outputs inspected before use — citation opened, source previewed, diff expanded, fields checked ÷ outputs shown Whether checking happens at all, and whether it tracks risk
Edit-before-accept rate Drafts modified before sending ÷ drafts shown The middle path between blind accept and reject — but rising edits can mean worse output, not worse trust
Appropriate-escalation rate Handoffs to a human on slices where the system should abstain or defer ÷ eligible interactions Zero escalation on known-hard slices is a red flag; 4.2 owns the patterns
Post-hoc correction rate Undo usage, edits after send, reports, reversals of AI actions The expensive kind of verification — errors that shipped
Review quality (where humans review) Reviewer edit/reject rates, seeded-item catch rate Whether oversight is real or rubber-stamping — 4.5

The diagnostic rule. Compare reliance and verification within each slice:

  • Relying without verifying, on a slice with known errors → over-trust. Users are acting on outputs they should be checking. Fix it with better evidence (Part 3), cognitive forcing (1.3) or a higher minimum autonomy rung — not with a bigger disclaimer.
  • Not relying at all → under-trust. The feature is dead whatever its benchmark scores. Fix it with capability statements, real examples and visible evidence; accuracy work alone won't move the number.
  • Verifying roughly in proportion to error cost → calibrated. Perfect calibration doesn't mean zero verification — it means verification effort tracks the slice's error rate. Checking everything is the mirror-image failure: verification theatre that trains users to click through.

Attitudinal metrics — surveys fill the gap behaviour can't. Behaviour shows what users did; periodic in-product surveys show what they believe. Short pulse surveys ("how confident are you in answers about billing?") segmented by the same slices beat one annual questionnaire. For a validated instrument, the trust-in-automation literature offers established scales — Jian, Bisantz and Drury's empirically derived scale (International Journal of Cognitive Ergonomics 4(1):53–71, 2000) is the standard reference. Caveats: stated trust and behavioural reliance diverge (people over-report both), timing matters (a survey right after a success inflates scores), and respondents self-select — treat survey deltas as directional, not precise.

Where this lands. 13A.6 owns the metric hierarchy: these signals become the guardrail metrics (reliance/verification divergence, escalation rate, review quality, feedback-derived eval pass rate) around whatever north-star metric your product picks, and 10A.9's bias corrections apply to both feedback and survey data. The system-side complement — checking whether your confidence proxies match reality — is 10A.5's judge-calibration work, which the review queue's audit sampling feeds.

1.6 Repairing trust after a visible failure#

Part 1 said one confident error can poison a feature. Failure will still happen, so design the recovery as deliberately as the launch. A repair has four parts, in this order:

  1. Say what happened, in plain words, once. "That answer cited a policy that has since been replaced." Not "an error occurred", and not a paragraph of apology (2.2 on apology framing).
  2. Scope it. Tell the user what else is affected: "I rechecked the other four answers in this conversation; one used the same policy and is corrected below." Users who cannot tell whether the error was isolated assume it was systemic.
  3. Fix it where they are. Correct the output in place and keep the original visible as struck-through or in the history, so the change is verifiable (3.7).
  4. Show that the class of error is handled. Internally this means turning the failure into an eval case (5.5); in the UI it can be as small as "thanks, this is now checked automatically" only if that is true.

What not to do: silently patch the output (the user who copied the first answer never learns it was wrong), blame the user's wording, or send a mass "we've improved!" announcement that does not say what was wrong. For failures with real consequences (money moved, a wrong message sent), the repair is an incident response with a named human, and 13A.4 covers the failure-state copy.


Part 2: Expectation setting, onboarding and disclosure#

Part 1 established why calibrated trust matters. This part is how you set it before the first real task: what the feature says it can do, what it admits it can't, and when it tells the truth about being a machine.

2.1 Capability statements and first-run states#

HAX guideline G1/G2 — "make clear what the system can do" and "make clear how well the system can do what it can do" — is where every AI feature starts and where most fail. Users arrive with the mental model of every AI they've ever used, which is usually a general chatbot. Your support copilot is not that.

A capability statement is one honest paragraph (or three bullets) that answers:

  • What inputs it accepts ("paste a ticket", "drop a PDF up to 10 MB", "ask about your orders")
  • What outputs it produces ("a grounded answer with citations", "a draft reply you can edit")
  • What it explicitly does not do ("it cannot issue refunds itself — it prepares them for approval", "it doesn't know about orders placed in the last hour")
  • What good looks like ("answers cite handbook sections; if nothing matches, it says so")

Where it goes: the empty state of the feature, the first-run tooltip, the "?" or "About" affordance, and — for consequential features — repeated at the point of action, not just onboarding. Onboarding is forgotten in a week; the capability statement must live where the work happens.

First-run states deserve more than a welcome modal. The pattern that works:

  1. Show, don't tell. Three to five real example prompts the feature actually handles well — drawn from your golden set (10A.2), not invented marketing examples. A user who tries one good example calibrates faster than one who reads ten sentences.
  2. Let them try before they commit. The first interaction should be low-stakes and reversible: a read-only question, a draft, a preview. Never open on an action ("send", "charge", "delete") — that's an autonomy decision dressed as onboarding.
  3. Seed the mental model of failure. One sentence early beats ten apologies later: "It can be wrong — check anything that matters." See 2.2 for how to write it so it's read, not wallpaper.

2.2 The "AI can be wrong" notice: what works, what doesn't#

Every AI feature needs a visible statement that output can be wrong. The failure mode isn't the notice's existence — it's that users learn to ignore it. Research on warning design (and plain common sense) gives a few rules:

What doesn't work:

  • Boilerplate in fine print. "AI-generated content may contain errors" in 8-point grey text at the bottom of a settings page is legally present and functionally absent. Users have learned to scroll past it.
  • The same notice everywhere, always. A banner that never changes becomes furniture. Notices lose power through repetition without variation.
  • Apology framing. "We're so sorry, but the AI might mess up!" trains users to expect incompetence — the opposite of calibrated trust. State the fact, not the feelings.
  • Vague scope. "Results may be inaccurate" tells the user nothing about what to check. The useful version names the failure: "It can invent citations", "totals can be wrong", "it may misunderstand refund policy edge cases".

What works:

  • Specific, located, actionable. "Answers cite handbook sections. If a claim isn't backed by a citation, verify it before quoting." — placed next to the answer, not in a footer.
  • Matched to the risk. A poetry generator doesn't need "verify before acting"; a refund-drafting agent does. The notice's tone and prominence should scale with the cost of a wrong answer — the same risk-tiering logic as 13A.1's quality bar and 12.9's high-stakes patterns.
  • Repeated at the moment of consequence. The notice that matters is the one next to the "Approve refund" button, not the one in onboarding. HAX's "when wrong" and "over time" guidelines both push toward contextual, just-in-time disclosure.
  • Paired with a check affordance. "AI can be wrong" is a dead end; "AI can be wrong — [see sources] [edit] [report]" is a workflow.

Copy that works, in three registers (this is also an exercise in the exercises):

Register Copy When
Minimal "AI-generated. Check before relying on it." Low-stakes, high-frequency surfaces (autocomplete, summaries)
Standard "This answer is generated from your handbook. Citations show the source — verify anything you'll act on." RAG answers, drafts, classifications
High-stakes "This draft prepares a refund. The AI can misread policy edge cases — review the amount and reason before approving." Actions with financial, legal or safety consequences

The pattern: name the capability, name the failure mode, name the check. Three clauses, no adjectives.

2.3 User-facing limitation notices#

11C.4's governance section owns the policy side: where outputs can mislead, the product must say so, and governance's job is to require that the notice exists. This lesson owns the UX side — where it goes and what it says.

The limitation notice is a specific kind of "AI can be wrong" message: it names a known, bounded limitation rather than the general possibility of error. Examples:

  • "Answers only cover the handbook as of March 2026 — newer policies aren't included."
  • "It works best on single-page invoices; multi-page tables may extract incorrectly."
  • "Voice input is English-only; other languages fall back to text."
  • "It can't see images in this conversation — describe what you need instead."

Design rules for limitation notices:

  1. Tie them to capability, not apology. "English-only" is information; "sorry, we don't support your language yet" is a support ticket.
  2. Place them where the limitation bites, not in a global banner. A limitation about PDFs belongs on the upload screen; a limitation about refunds belongs on the refund draft.
  3. Keep a register. Maintain a list of known limitations with their trigger conditions (which user actions, which inputs, which account tiers). When a limitation is fixed, remove its notice — stale warnings are their own credibility leak.
  4. Link to the workaround. Every limitation notice should answer "what do I do instead?" — "for handwritten invoices, upload a photo and a human will transcribe it" beats "handwriting isn't supported".

2.4 Telling users they're talking to AI#

This is the disclosure obligation in its most basic form: users must know they're interacting with an AI system, not a person. Three layers:

The legal floor. 12.9's Part 3 owns the compliance treatment — EU AI Act Article 50 transparency obligations (applicable from August 2026), sector rules, contractual duties. The engineering-relevant point: disclosure is not just good UX, it's a legal requirement in growing jurisdictions, and who carries it depends on your role: for an assistant you build and put in front of users you are usually the provider of that chat system, while a team that only deploys a vendor's finished chatbot may owe less (12.9 has the provider-versus-deployer table). Read 12.9 before shipping; this section is the UX pattern, not the legal advice.

The design floor. Even where no law requires it, disclosure is a trust primitive:

  • Name the thing. "AI assistant", "automated draft", "bot" — a label that survives translation and doesn't require the user to infer from tone. Apple's HIG generative-AI page (read 12 November 2026) likewise says to communicate where your app uses AI and never to trick someone into thinking AI-generated content was authored by a human — the operative idea is where: per-surface, not just in terms of service.
  • Don't hide it in plain sight. A tiny "AI" glyph in the corner that users must hover to decode is disclosure theatre. The label should be visible at the point of interaction — in the header of the chat, on the generated image, on the drafted email.
  • Don't over-disclose into noise. Every element labelled "AI" becomes meaningless. Disclose at the boundary where the user might reasonably think they're talking to a person or relying on human judgement — the chat window, the auto-published post, the voice call — not on every button.

The conversational floor. In chat interfaces, disclosure has a rhythm:

  • First message: the system identifies itself ("Hi, I'm the support assistant — I can help with orders and refunds, or connect you to a person").
  • On persona shifts: if the tone changes (empathetic mode, formal mode), a brief marker helps — not mandatory, but it prevents the "wait, is this a different bot?" confusion.
  • On handoff to human: the transition must be explicit in both directions — "I'm connecting you to Sarah from support" and, when the human takes over, the user knows who's who. 08D.3's human-agent teaming covers the engineering side; the UX side is making the boundary visible in the conversation itself.
  • Never pretend. The worst disclosure violation isn't omitting the label — it's simulating humanity: fake typing delays, "let me think about that" when nothing is being thought about, human names on obviously automated messages. Deceptive anthropomorphism is both a trust violation and, in some jurisdictions, a regulatory one.

2.5 Labelling AI-generated content and provenance awareness#

When your product produces content that leaves your UI — a generated image, a drafted email, a social post, a voice note — the disclosure question shifts from "is this AI?" to "is this AI-generated?" and "can it be detected as such?"

The layers, from lightest to strongest:

Layer What it is When you need it
Visible label "AI-generated" text/badge on the output Any content the user might share or publish
Provenance metadata C2PA-style content credentials, embedded metadata, watermarking Images, video, audio — anything that can be screenshotted or re-shared
Machine-readable marking Metadata that downstream systems can detect Regulatory requirements (EU AI Act Art 50(2) requires providers of generative AI to mark synthetic outputs machine-readably from August 2026, with a transition to 2 December 2026 for systems placed on the market before 2 August 2026, set by Article 111(4); wording checked on the European Commission's AI Act Service Desk, 12 November 2026 — see 12.9)
Deepfake disclosure Explicit "this is AI-generated" on realistic synthetic media of real people/events Any synthetic audio/video/image depicting real persons or events (EU AI Act Art 50(4); 12.9)

For text, the bar is lower but the principle is the same: if your product generates a publishable artefact (a marketing email, a report, a social post), the export should carry a label or footer identifying it as AI-assisted. The user can remove it; you can't add it after the fact.

09.3's image generation lesson covers the generation side; 09.10's product lesson covers the product-level provenance patterns. This lesson's job is the UX rule: the label is part of the output, not a settings toggle.

2.6 Agent/human boundaries#

When your feature can act — call tools, delegate to sub-agents, escalate to a person — the user needs a visible map of who is doing what right now. This is the promise 08D.3 made to Module 13A: "make agent/human boundaries visible events in your trace and your UI."

The patterns, in increasing complexity:

Boundary What the user sees Example
AI acting alone The assistant's name/avatar; tool-call indicators ("Searching orders...") Support copilot looking up an order
AI delegating to another AI "Checking with the billing specialist..." — a named sub-agent or role Multi-agent research system spawning a verifier
AI escalating to human "Connecting you to a support agent" + the human's name/avatar when they arrive Chatbot → human handoff
Human acting with AI assist The human's name, with "drafted by AI" on the suggestion they're reviewing Agent console where the AI drafts and the human sends

The rules:

  1. Every transition is a visible event. The user should never wonder "is this a bot or a person?" mid-conversation. The boundary is a UI element — a system message, an avatar change, a label — not a subtle tone shift.
  2. The handoff carries context. When AI escalates to human, the human sees what the AI tried (the trace, the transcript, the failed approaches) — and the user sees that the human is now in charge. 08A.14's escalation patterns cover the mechanics.
  3. The human can hand back. If the AI escalated too early, the human can return the conversation to automation — the user sees "AI assistant has resumed". Without reversibility, every escalation is a permanent loss of coverage.
  4. Never simulate the boundary. Don't have the AI write "As a human agent, I..." or have a human secretly approve AI actions without disclosure. Both are deception; both destroy the trust the boundary was meant to build.

2.7 Persona and anthropomorphism#

Every AI feature has a persona whether you design one or not — users will anthropomorphise (attribute human-like minds, feelings, intentions) to anything that talks back. Epley, Waytz and Cacioppo's "On Seeing Human" (Psychological Review 114(4):864–886, 2007) gives the three-factor theory: people anthropomorphise when human-like knowledge is accessible, when they want to understand the agent's behaviour, and when they crave social connection. LLMs hit all three triggers constantly — fluent language, apparent memory, responsive tone.

The design question isn't "should we anthropomorphise?" — you can't opt out — it's how much, and to what end.

Choice Benefit Risk
Neutral/tool-like ("Assistant", no avatar, no name) Signals tool, not person; lower emotional stakes; honest about what it is Can feel cold; less engaging for consumer products
Named persona ("Aria", "Max", a consistent voice) Memorable, brandable, can express warmth appropriately Users may attribute feelings, intentions, accountability to it; harder to walk back
Human-like avatar/voice Maximum engagement, social presence Maximum anthropomorphism; users may believe it's a person; highest deception risk
Explicitly artificial ("I'm an AI assistant", mechanical voice, no avatar) Maximum honesty about nature Can feel hostile or gimmicky; may reduce appropriate trust below optimal

The risks that matter for your design:

  • Emotional reliance. A companionable persona can create parasocial attachment — users confiding, depending, believing the AI "cares". For vulnerable users this is a safety issue (see 12.9's companionship section). The defence isn't a cold persona — it's honest framing ("I'm an AI, I don't have feelings") and hard boundaries (no simulated intimacy, no fake reciprocity).
  • Accountability confusion. "The assistant decided" is not an answer when a human owns the outcome — 08A.14's rule applies directly: never anthropomorphise accountability. The persona can be warm; the responsibility chain must stay human-legible.
  • Sycophancy amplification. A persona trained to be agreeable becomes a persona that never disagrees — see Part 7 on why that's a product risk, not a feature.

The practical rule: the persona can be charming; the disclosure can't be optional. A named, warm assistant that introduces itself as "an AI assistant named Aria" gets the engagement without the deception.

2.8 Deceptive design red lines#

Some disclosure and persona choices cross from "persuasive" into "deceptive" — and deceptive design in AI UX is both a trust violation and, increasingly, a legal one. The red lines:

Deceptive pattern What it looks like Why it's wrong
Hidden AI No label; users assume they're talking to a person Violates disclosure duties; destroys informed consent
Fake humanity Simulated typing delays, "hmm let me think", human names on bot messages Deceptive anthropomorphism; erodes trust when discovered
Fake verification "Verified by AI" badges that mean nothing; progress spinners implying checks that don't happen UX theatre; users can't distinguish real evidence from decoration
Dark-pattern consent "Accept all" pre-checked, "no thanks" hidden in fine print, consent bundled with terms Undermines the feedback/consent infrastructure you'll need later
Sycophancy by design System prompt tuned to never disagree, always validate See 7.1 — this is manipulation, not service
Engagement loops Infinite scroll of AI content, streaks, "you haven't talked to me today" Optimising for time-on-site over user outcomes; the AI equivalent of slot-machine design
False scarcity/urgency "Only 3 refunds left at this price!" when the limit doesn't exist Classic dark pattern, amplified by AI's ability to generate convincing copy
Bait-and-switch autonomy User thinks they're chatting; the system is actually taking actions Autonomy without consent; see 4.1

These aren't edge cases — they're the default failure modes when AI UX is designed for engagement metrics rather than user outcomes. Part 7 audits them systematically.

What this means for you as an engineer: disclosure, capability statements and persona choices are not "design polish" — they're the load-bearing walls of calibrated trust. Get them right in the spec, not the styling pass. Every pattern in this part has a corresponding entry in the pattern catalogue and the pre-launch checklist.


Part 3: Showing evidence#

Parts 1 and 2 told users what to expect. This part gives them something to check — the difference between a disclaimer and a verification path.

3.1 Why evidence beats reassurance#

The research from 1.3 converges on one practical conclusion: users calibrate trust from verifiable signals, not from confident prose. A citation they can click, a source region they can see, a diff they can inspect — these are evidence. "Rest assured, our AI is highly accurate" is not.

This doesn't mean every output needs a citation. It means every output needs the strongest evidence its type supports:

Output type Strongest practical evidence
Factual answer from documents Citations to specific passages, quote-level attribution
Extracted structured data Source region highlights ("this value came from page 2, line 14")
Classification/routing The features that drove it (top signals, matched rules)
Generated text The sources it drew on, or an honest "no sources — this is the model's own knowledge"
Code The diff, the tests it ran, the docs it cited
Agent action The tool calls it made, the arguments, the results

The meta-rule: evidence is what the user needs to verify, not what makes the product look thorough. A citation list of 20 sources is worse than 3 precise ones; a "confidence: high" badge is worse than nothing if it's not calibrated.

3.2 Citations and source previews#

07.5 owns the citation machinery — how to produce them, verify them, and normalise provider-native formats into your own ClaimCitation/SourceRef types. This section is the UX layer: how citations should look and behave to the user.

The patterns that work:

  • Inline markers, not footnotes. [1] next to the claim it supports, not a bibliography the user has to cross-reference mentally. 07.5's docs_qa/cite.py already enforces this — markers are verified against the actual context sent to the model.
  • Hover/preview on the marker. A citation that requires a click to a separate page is friction; a preview that shows the source title, a one-line excerpt and the relevant passage on hover (or tap) is verification in one gesture.
  • Click-through to the source. For documents, deep-link to the page/section/line. For web sources, open the URL — but sanitise and warn (links in AI output are untrusted input; see 03.4's semantic validators and 12.5's output validation).
  • Visual distinction between verified and unverified. If your pipeline checks citations (07.5's verifier), show which ones passed. An unverified citation should look different — not hidden, but marked. Hiding failed citations teaches users the visible ones are all "good"; marking them teaches them the system knows its limits.
  • "No sources" is a first-class state. When the model answers from parametric knowledge rather than retrieval, say so explicitly — "This answer isn't grounded in your documents" — rather than letting the user assume citations exist.

What doesn't work:

  • Citation theatre. A wall of links that don't actually support the adjacent claim. Worse than no citations — it's evidence-shaped deception.
  • Citation overload. Every sentence cited is noise; the user can't tell which claims are load-bearing. Cite the claims that matter.
  • Dead links. Citations that 404 or require login are worse than none — they signal the pipeline wasn't checked end-to-end.

3.3 "Show your work"#

09.10's promise to Module 13A was specific: "show your work" — surface the transcript, the extracted fields with their source regions, or the "why" behind a classification. This generalises across every output type.

"Show your work" has three levels of depth, and the right level depends on the user's expertise and the stakes:

Level What it shows When
Summary One-line "how I got this": "Based on 3 handbook sections" / "Extracted from page 2" Default for most users
Expandable detail Tool calls, retrieved passages, reasoning trace (summarised), intermediate steps When the user wants to verify or the output is consequential
Raw transcript The full message log, raw model output, every tool call and result Debugging, audit, high-stakes review, power users

The patterns:

For RAG answers: the citation layer (3.2) plus a "sources used" panel showing count, titles and relevance scores. The user sees that retrieval happened and what it found — not the raw chunks unless they ask.

For extraction/classification: field-level provenance. Each extracted value links to its source region — bounding box on an image, page/line on a document, JSON path on structured input. 13B.3's document intelligence build makes this the core UX; the principle is universal: every extracted claim should be traceable to its evidence.

For agent actions: the tool-call summary. "I searched orders → found ORD-4472 → checked refund policy → drafted reply" — a compressed trace the user can expand. 13A.2's progress events own the real-time version; the post-hoc version is the audit trail (see 4.6).

For generated content: the "why" — the prompt, the sources, the constraints that shaped it. For a marketing email, "Generated from your brand guidelines + this product description" tells the user what levers were pulled.

The anti-pattern: showing raw chain-of-thought. Models don't have reliable access to their actual reasoning (see 02.8), and raw CoT can leak system prompts, private data or manipulative rationalisations. Show summaries of process — what was retrieved, what tools were called, what decisions were made — not the model's internal monologue.

3.4 Explanation patterns: what helps vs what persuades#

Not all explanations are equal. The research distinguishes:

Pattern What it does Evidence
Evidence-based (citations, source regions, data shown) Lets the user verify independently Strongest — supports calibration
Process-based ("I checked X, then Y") Shows the work happened Moderate — builds trust in the process
Confidence-based ("I'm 90% sure") States certainty Weak alone — verbalised confidence is poorly calibrated (02.10, 12)
Plausibility-based (fluent, confident, well-structured prose) Persuades without informing Can increase acceptance regardless of correctness (Bansal et al., CHI 2021)

The design rule: prefer evidence over explanation, explanation over confidence, confidence over nothing. A well-chosen citation beats a paragraph of rationale; a calibrated confidence proxy (see 3.5) beats a bare number; and "I don't know" beats a persuasive guess.

For the "explain this output" affordance — the "why did you say that?" button — the answer should be structured, not prose:

text
Sources: 3 handbook sections (HR-104, HR-201, POL-07)
Key claim: "Refunds within 30 days" ← HR-104 §2.3
Confidence signals: retrieval score 0.87, all 3 sources agree
Limitation: policy updated March 2026; newer exceptions not covered

This is evidence-shaped explanation — it tells the user what to check, not just what the model thinks.

3.5 Uncertainty display: honest limits of verbalised confidence#

02.10's Part 12 established that models' stated confidence is unreliable — "I'm 95% sure" is generated text, usually near-identical for right and wrong answers. 10A.5's judge-calibration work extends this: even judge models' confidence scores need validation before you trust them as probabilities.

So what can you show the user?

Signal What it actually measures How honest is it?
Verbalised confidence ("I'm 90% sure") What the model says Poorly calibrated — treat as decoration
Token probabilities / logprobs The probability the model assigned to its own tokens Better than verbalised, but still model-internal; see 02.5 for what logprobs actually are
Retrieval scores How relevant the sources were Honest for grounded answers — low retrieval score = weak grounding
Judge disagreement Whether multiple evaluators agree Honest proxy — disagreement = uncertainty
Self-consistency Whether multiple samples agree Honest proxy — variance across runs = uncertainty
Abstention rate on similar queries How often the system says "I don't know" in this domain Honest if measured on your eval set
Historical accuracy on this task type Your eval results for this feature Honest if current and sliced correctly

The display patterns:

Threshold-based routing (the strongest): don't show confidence at all — act on it. Route low-confidence outputs to review, abstention or a stronger model (4.2). The user sees "this needs a human check" or "I'm not sure enough to answer" — not a number they can't interpret.

Bucketed labels (the pragmatic middle): instead of "87% confident", show "High / Medium / Low confidence" where the buckets are calibrated against your eval data. "Medium" means "we've seen this fail ~30% of the time on similar inputs" — a statement the user can act on.

Verbal hedging (the weakest, use sparingly): "This might be incomplete" / "I found conflicting sources" — honest signals embedded in the answer text. Better than a fake percentage, worse than structured routing.

What doesn't work:

  • Fake precision. "87.3% confident" implies a measurement that doesn't exist.
  • Confidence without consequence. A number that doesn't change what the user does next is noise.
  • Confidence on everything. If every answer is "high confidence", the signal is dead — calibrate so the distribution matches reality.

3.6 Abstention and "I don't know" UX#

07.4 owns the abstention machinery — the sufficiency gates, the calibration, the "I don't know" prompt. This section is the UX of it: how abstention should look.

Abstention is a feature, not a failure — but only if the UX makes it useful. The patterns:

Good abstention:

  • "I couldn't find that in the handbook — it might be in a newer policy version. Want me to connect you to a human?"
  • "The invoice is unclear on the tax line — I extracted $1,240 but the total shows $1,340. Can you confirm which is right?"
  • "I'm not confident enough to answer this — here's what I found that might help: [partial results]"

Bad abstention:

  • "I don't know." (dead end, no path forward)
  • "I'm unable to assist with that request." (robotic, doesn't explain why)
  • Silence or a generic error (the user can't tell abstention from failure)

The rules:

  1. Abstention names the gap. "I don't have data on X" is useful; "I can't help" is not.
  2. Abstention offers the next step. Human handoff, partial answer, clarification question, related information — always a path forward.
  3. Abstention is calibrated, not random. If the system abstains on 40% of queries, the threshold is wrong — calibrate against your eval set (07.4's calibration section).
  4. Abstention is honest about partial knowledge. "I found 2 of 3 policies — the third isn't in my sources" beats "I don't know" when partial information exists.

3.7 Comparison and diff views#

When the AI's output modifies something — edits a draft, rewrites a paragraph, updates a record — the user needs to see what changed, not just the final result.

Pattern What it shows When
Side-by-side Original vs AI output When the user needs to compare quality or choose
Inline diff Red/green or strikethrough on changed parts When the user needs to review edits before accepting
Before/after toggle Flip between states When space is tight or the change is small
Field-level diff Changed fields highlighted in a form/table Structured data (extraction, updates)

The rules:

  • The diff is the evidence. "Here's what I changed" is more trustworthy than "I improved your text" — the user can verify each change.
  • Accept/reject is per-change, not all-or-nothing where feasible. Letting users cherry-pick which edits to keep respects their judgement and teaches the system what they actually want.
  • The original is always recoverable. Never let an AI edit destroy the user's work — undo must restore the exact prior state (4.6).

What this means for you as an engineer: evidence is a pipeline, not a widget. Citations need verification (07.5); confidence signals need calibration (10A.5); abstention needs threshold tuning (07.4). The UX patterns in this section are the presentation layer — the engineering quality of the underlying signals determines whether the evidence is real or theatre.


Part 4: Control and autonomy — the autonomy dial and human-in-the-loop#

Parts 2 and 3 help users understand the AI. This part gives them control over it — how much it does on its own, when it must ask, and how a human stays effectively in the loop rather than rubber-stamping.

4.1 The autonomy dial#

The autonomy dial is the product-level answer to "how much should the AI do without asking?" It's not a single setting — it's a per-action, per-context decision. The five rungs, from least to most autonomous:

Rung Name What happens User sees When to use
1 Suggest AI proposes; human executes "Try this?" with accept/dismiss Low-stakes, high-volume, user wants control (autocomplete, recommendations)
2 Draft AI produces a complete draft; human reviews and sends Editable draft with diff/preview Content creation, replies, reports — the human is the sender
3 Ask-before-acting AI prepares an action; human approves before it runs Approval card with args, reasoning, blast radius Consequential actions (refunds, emails, deletions)
4 Act-and-notify AI acts, then tells the human what it did Notification + undo window Reversible actions where speed matters (tagging, filing, low-value updates)
5 Act silently AI acts with no human notification Nothing (or audit log only) Only for trivial, fully reversible, low-risk automation — and even then, disclose in policy

The dial isn't a slider users drag — it's a design decision per action type, documented and enforced in code. The decision rule for approval versus autonomy (when a person must approve, when policy may) is 13A.8 D5; the gate that enforces rung 3 is in 08A.12. The worked table below applies it to the three capstone product shapes:

Action Support copilot (13B.2) Document intelligence (13B.3) Voice agent (13B.5)
Answer a question Suggest → Draft (rung 2) Suggest → Draft (rung 2) Act-and-notify (rung 4) — voice can't show drafts
Look up an order Act silently (rung 5) — read-only N/A Act silently (rung 5)
Draft a reply Draft (rung 2) Draft (rung 2) Draft → read-back for confirmation (rung 3 hybrid)
Issue a refund Ask-before-acting (rung 3) — required N/A Ask-before-acting (rung 3) — spoken confirmation
Delete/cancel Ask-before-acting (rung 3) Ask-before-acting (rung 3) Ask-before-acting (rung 3)
Create a ticket Act-and-notify (rung 4) Act-and-notify (rung 4) Act-and-notify (rung 4)
Extract fields from doc Draft → human verifies (rung 2) Draft → review queue (rung 2/3 hybrid) N/A
Send the final answer Human sends (rung 2 ceiling) Human exports (rung 2 ceiling) AI speaks (rung 4) — but logs transcript

4.2 HITL patterns and when each applies#

Human-in-the-loop isn't one pattern — it's a family. The right one depends on volume, reversibility and latency tolerance. The gate behind approve/reject and edit-then-send (the four decisions: approve, edit, deny, defer) is built in 08A.12 Part 3; this table is the wider product view, including the patterns that are not gates (queues, sampling, routing, escalation):

Pattern How it works Best for Cost
Approve/reject Human sees proposal, clicks approve or reject High-stakes, low-volume actions Reviewer attention per action
Edit-then-send Human modifies the draft, then sends Content where human judgement improves quality Slower than approve, better than reject-and-retry
Batch review queue Items accumulate; human reviews in batches High-volume, medium-stakes outputs Efficient per-item, but batch fatigue is real
Escalation to human AI hands off when stuck or out-of-scope Ambiguity, edge cases, user request Requires staffing; measure escalation rate
Sampling-based audit Most outputs auto-pass; a random % go to review High-volume where trust is established Cheap, catches drift, misses individual errors
Confidence-threshold routing Low-confidence outputs route to review When you have a calibrated confidence signal Depends on signal quality
Dual control Two humans must approve Highest-risk actions (payments, deletions, legal) Slowest; use sparingly

The choice isn't either/or — a production system mixes them. The support copilot might use approve/reject for refunds (rung 3), batch review for draft replies (rung 2 at scale), sampling audit for answered questions (rung 2 spot-checks), and escalation for novel cases. 13B.2 wires all four.

4.3 The ApprovalGate#

The framework-neutral gate (tiers, edit, defer, save-and-stop, default-deny) is built in 08A.12; 08A.14's policy layer and 12.6's signed approvals own the security machinery — tamper-evident grants, argument hashing, scoped credentials. This lesson's ai_product/approval.py is the product layer: the state machine and audit trail that sits above them, usable by any feature.

The contract:

  • States: pending → approved / rejected / expired (edited counts as approved-with-changes)
  • TTL: pending requests expire; expiry is a rejection — nobody answered, so the action doesn't run
  • Audit: every transition appends an entry with timestamp, actor, and arguments
  • Escalation hook: expiry or manual escalation calls a callback (page a backup reviewer, notify a channel)
  • Fail closed: unknown IDs raise, double decisions raise, late decisions on expired requests raise

One deliberate choice in the state list: edited is a decision, not a status. An edited request lands on approved with decided_args carrying the corrected arguments, and the edited event survives in the audit trail — an edited approval is an approval. If a report needs "edited" as an outcome, derive it from audit_trail(); don't add a fifth status.

python
"""ai_product/approval.py — a human-approval gate for consequential AI actions.

Pure standard library. The gate sits between an agent's proposed action and
the code that would execute it: the action pauses as PENDING until a person
decides APPROVED / REJECTED / EDITED, or the TTL expires (fail closed).

Every state change appends an AuditEntry — the audit trail is the product's
answer to "who approved this, when, and with what arguments?".
"""

from __future__ import annotations

import time
import uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable


class Decision(str, Enum):
    APPROVED = "approved"
    REJECTED = "rejected"
    EDITED = "edited"


class GateStatus(str, Enum):
    PENDING = "pending"
    APPROVED = "approved"
    REJECTED = "rejected"
    EXPIRED = "expired"


class GateError(Exception):
    """Raised for invalid gate operations (unknown id, double decision...)."""


@dataclass
class ApprovalRequest:
    """What the agent wants to do, and why it thinks it should."""

    action: str                       # e.g. "issue_refund", "send_email"
    args: dict[str, Any]              # the exact arguments that would run
    reason: str = ""                  # the agent's one-line justification
    risk_tier: str = "medium"         # low | medium | high | critical
    requested_by: str = "agent"       # which agent/persona proposed it
    context: dict[str, Any] = field(default_factory=dict)  # extra evidence for the reviewer


@dataclass
class AuditEntry:
    ts: float
    request_id: str
    event: str
    actor: str
    detail: str = ""


@dataclass
class ApprovalRecord:
    request_id: str
    request: ApprovalRequest
    status: GateStatus = GateStatus.PENDING
    decided_by: str = ""
    decided_args: dict[str, Any] | None = None
    created_at: float = 0.0
    expires_at: float = 0.0
    decided_at: float | None = None
    escalation_count: int = 0


class ApprovalGate:
    """A fail-closed approval gate with TTL, audit trail and escalation.

    Parameters
    ----------
    ttl_seconds:
        How long a request stays PENDING before it EXPIRES. Expiry is a
        rejection: nobody answered in time, so the action does not run.
    on_escalate:
        Optional callable ``(record, reason) -> None`` invoked when a request
        expires or is manually escalated — e.g. page a backup reviewer.
    clock:
        Injectable monotonic clock (tests pass a fake; production uses
        ``time.monotonic``).
    """

    def __init__(
        self,
        ttl_seconds: float = 300.0,
        on_escalate: Callable[[ApprovalRecord, str], None] | None = None,
        clock: Callable[[], float] = time.monotonic,
        id_factory: Callable[[], str] | None = None,
    ) -> None:
        self.ttl_seconds = ttl_seconds
        self.on_escalate = on_escalate
        self._clock = clock
        self._id_factory = id_factory or (lambda: uuid.uuid4().hex[:12])
        self._records: dict[str, ApprovalRecord] = {}
        self._audit: list[AuditEntry] = []

    # ------------------------------------------------------------- submit --

    def submit(self, request: ApprovalRequest) -> str:
        """Register a proposed action. Returns its request id."""
        now = self._clock()
        rid = self._id_factory()
        self._records[rid] = ApprovalRecord(
            request_id=rid,
            request=request,
            created_at=now,
            expires_at=now + self.ttl_seconds,
        )
        self._log(rid, "submitted", request.requested_by, request.action)
        return rid

    # ------------------------------------------------------------- decide --

    def decide(
        self,
        request_id: str,
        decision: Decision | str,
        actor: str,
        edited_args: dict[str, Any] | None = None,
    ) -> ApprovalRecord:
        """Record a human decision on a pending request.

        ``EDITED`` requires ``edited_args`` — the corrected arguments that
        should run instead. Any decision on an expired request first expires
        it, then raises GateError: a late approval is not an approval.
        """
        record = self._require(request_id)
        self._expire_if_due(record)
        if record.status is not GateStatus.PENDING:
            raise GateError(
                f"{request_id} is already {record.status.value}; "
                "decisions are final and single-shot"
            )

        decision = Decision(decision)
        if decision is Decision.EDITED and not isinstance(edited_args, dict):
            raise GateError("EDITED requires edited_args dict")

        record.decided_by = actor
        record.decided_at = self._clock()
        if decision is Decision.APPROVED:
            record.status = GateStatus.APPROVED
            record.decided_args = dict(record.request.args)
        elif decision is Decision.REJECTED:
            record.status = GateStatus.REJECTED
        else:
            record.status = GateStatus.APPROVED
            record.decided_args = dict(edited_args or {})
        self._log(
            request_id,
            decision.value,
            actor,
            _summarise_args(record.decided_args),
        )
        return record

    # ------------------------------------------------------------- expiry --

    def expire_due(self) -> list[str]:
        """Expire every pending request past its TTL. Returns expired ids."""
        expired = []
        for rid, record in self._records.items():
            if record.status is GateStatus.PENDING:
                self._expire_if_due(record)
                if record.status is GateStatus.EXPIRED:
                    expired.append(rid)
        return expired

    def escalate(self, request_id: str, reason: str, actor: str = "system") -> ApprovalRecord:
        """Manually escalate a pending request (e.g. reviewer asks for backup)."""
        record = self._require(request_id)
        self._expire_if_due(record)
        if record.status is not GateStatus.PENDING:
            raise GateError(f"cannot escalate {request_id}: already {record.status.value}")
        record.escalation_count += 1
        self._log(request_id, "escalated", actor, reason)
        if self.on_escalate:
            self.on_escalate(record, reason)
        return record

    # ------------------------------------------------------------- reads ---

    def pending(self) -> list[ApprovalRecord]:
        """Pending records, oldest first — the order a reviewer should see."""
        self.expire_due()
        return sorted(
            (r for r in self._records.values() if r.status is GateStatus.PENDING),
            key=lambda r: r.created_at,
        )

    def get(self, request_id: str) -> ApprovalRecord:
        record = self._require(request_id)
        self._expire_if_due(record)
        return record

    def audit_trail(self, request_id: str | None = None) -> list[AuditEntry]:
        entries = self._audit
        if request_id is not None:
            entries = [e for e in entries if e.request_id == request_id]
        return list(entries)

    # ------------------------------------------------------------- internals

    def _require(self, request_id: str) -> ApprovalRecord:
        try:
            return self._records[request_id]
        except KeyError:
            raise GateError(f"unknown approval request: {request_id}") from None

    def _expire_if_due(self, record: ApprovalRecord) -> None:
        if record.status is GateStatus.PENDING and self._clock() >= record.expires_at:
            record.status = GateStatus.EXPIRED
            self._log(record.request_id, "expired", "system", "ttl elapsed")
            if self.on_escalate:
                self.on_escalate(record, "expired unanswered")

    def _log(self, request_id: str, event: str, actor: str, detail: str) -> None:
        self._audit.append(
            AuditEntry(ts=self._clock(), request_id=request_id, event=event,
                       actor=actor, detail=detail)
        )


def _summarise_args(args: dict[str, Any] | None, limit: int = 80) -> str:
    text = str(args or {})
    return text if len(text) <= limit else text[: limit - 1] + "…"


# --------------------------------------------------------------------- demo

if __name__ == "__main__":
    # A fake clock so the demo is deterministic: every "tick" is one second.
    now = [1000.0]

    def clock() -> float:
        return now[0]

    escalations: list[tuple[str, str]] = []

    def on_escalate(record: ApprovalRecord, reason: str) -> None:
        escalations.append((record.request_id, reason))
        print(f"  ESCALATE {record.request_id} ({record.request.action}): {reason}")

    ids = (f"apr-{i:04d}" for i in range(1, 100))
    gate = ApprovalGate(ttl_seconds=30, on_escalate=on_escalate, clock=clock,
                        id_factory=lambda: next(ids))

    rid_refund = gate.submit(ApprovalRequest(
        action="issue_refund",
        args={"order_id": "ORD-4472", "amount": 84.50, "reason": "duplicate charge"},
        reason="customer verified, policy allows refund within 30 days",
        risk_tier="high",
        context={"ticket": "T-991", "policy_section": "REF-2.1"},
    ))
    rid_email = gate.submit(ApprovalRequest(
        action="send_email",
        args={"to": "customer@example.com", "subject": "Your refund",
              "body": "We've issued a refund of $84.50..."},
        reason="confirm refund to customer",
        risk_tier="medium",
    ))
    rid_delete = gate.submit(ApprovalRequest(
        action="delete_account",
        args={"user_id": "u_8812"},
        reason="user requested deletion",
        risk_tier="critical",
    ))

    print("== pending ==")
    for r in gate.pending():
        print(f"  {r.request_id}  {r.request.action:15s} tier={r.request.risk_tier:8s} "
              f"expires_in={r.expires_at - now[0]:.0f}s")

    # Reviewer approves the refund, edits the email, ignores the delete.
    gate.decide(rid_refund, Decision.APPROVED, actor="agent_lead_priya")
    gate.decide(rid_email, "edited", actor="agent_lead_priya",
                edited_args={"to": "customer@example.com",
                             "subject": "Your refund has been issued",
                             "body": "We've issued a refund of $84.50 to your card. "
                                     "It may take 5-10 business days to appear."})

    # 31 seconds pass: the delete request expires unanswered -> escalation.
    now[0] += 31
    print("\n== after TTL elapsed ==")
    for rid in gate.expire_due():
        print(f"  expired: {rid}")

    # A late decision on the expired request is refused.
    try:
        gate.decide(rid_delete, Decision.APPROVED, actor="agent_lead_priya")
    except GateError as exc:
        print(f"\n  late decision refused: {exc}")

    print("\n== audit trail ==")
    for e in gate.audit_trail():
        print(f"  [{e.event:9s}] {e.request_id} by {e.actor}: {e.detail}")

    print("\n== final states ==")
    for rid, rec in gate._records.items():
        args = rec.decided_args if rec.decided_args is not None else rec.request.args
        print(f"  {rid} {rec.request.action:15s} -> {rec.status.value:8s} "
              f"decided_by={rec.decided_by or '-':18s} args={args}")

Run it:

bash
uv run python ai_product/approval.py
Output · deterministic — fake clock and sequential IDs23 lines
== pending ==
  apr-0001  issue_refund    tier=high     expires_in=30s
  apr-0002  send_email      tier=medium   expires_in=30s
  apr-0003  delete_account  tier=critical expires_in=30s

== after TTL elapsed ==
  ESCALATE apr-0003 (delete_account): expired unanswered
  expired: apr-0003

  late decision refused: apr-0003 is already expired; decisions are final and single-shot

== audit trail ==
  [submitted] apr-0001 by agent: issue_refund
  [submitted] apr-0002 by agent: send_email
  [submitted] apr-0003 by agent: delete_account
  [approved ] apr-0001 by agent_lead_priya: {'order_id': 'ORD-4472', 'amount': 84.5, 'reason': 'duplicate charge'}
  [edited   ] apr-0002 by agent_lead_priya: {'to': 'customer@example.com', 'subject': 'Your refund has been issued', 'body'…
  [expired  ] apr-0003 by system: ttl elapsed

== final states ==
  apr-0001 issue_refund    -> approved decided_by=agent_lead_priya   args={'order_id': 'ORD-4472', 'amount': 84.5, 'reason': 'duplicate charge'}
  apr-0002 send_email      -> approved decided_by=agent_lead_priya   args={'to': 'customer@example.com', 'subject': 'Your refund has been issued', 'body': "We've issued a refund of $84.50 to your card. It may take 5-10 business days to appear."}
  apr-0003 delete_account  -> expired  decided_by=-                  args={'user_id': 'u_8812'}

What the demo shows: three proposed actions enter pending; the reviewer approves one, edits another (the corrected arguments are what run, not the agent's originals), and ignores the third — which expires and escalates. The audit trail is the answer to "who approved this, when, and with what arguments?" — the question every post-incident review asks.

What this means for you as an engineer: the gate is not optional for rung-3+ actions. A rule that lives only in the system prompt is a suggestion; a gate in code is a guarantee (08A.12 section 1.3 has the argument). And the audit trail is not just for compliance — it's how you debug "why did the agent do that?" at 2 a.m.

4.4 Review queues and confidence routing#

Not every output needs a gate — most need a queue. ai_product/review_queue.py handles the high-volume case: route each output to AUTO (no human), REVIEW (human now), or AUDIT (confident but sampled for quality checks). For who should approve each risk tier (and separation of duties), see 08A.12 section 2.2.

The routing rules, in order:

  1. Unknown, malformed or below-threshold confidence, or an unrecognised risk tier → REVIEW. You can't verify the proxy (a missing or NaN score counts as unknown), and a typo such as "Critical" must not quietly fall through to AUTO, so the guard fails closed.
  2. Critical tier → REVIEW always. Dual control: a person must see it even when the model is confident.
  3. High tier, confident → AUDIT always. 100% sampled — high stakes deserve scrutiny even when the signal says "fine".
  4. Otherwise confident → AUDIT with probability audit_rate, else AUTO.
python
"""ai_product/review_queue.py — a prioritised human review queue.

Pure standard library. Every AI output that *might* need a human gets routed
by one of three paths:

  AUTO    — confident enough, not sampled: no human time spent
  REVIEW  — queued for a person now (low or missing confidence, or a
            critical risk tier)
  AUDIT   — confident, but sampled at random for quality auditing

The queue orders REVIEW items by a transparent score: explicit priority,
uncertainty, and age. The audit sampler uses an injected seeded RNG so demos
and tests are deterministic.
"""

from __future__ import annotations

import math
import random
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable


class Route(str, Enum):
    AUTO = "auto"
    REVIEW = "review"
    AUDIT = "audit"


_KNOWN_TIERS = ("low", "medium", "high", "critical")


def _usable_confidence(value: object) -> bool:
    """True only for a real, finite number in [0, 1]. A bool, NaN, infinity
    or 7.0 is a bug upstream, not a confident answer."""
    return (isinstance(value, (int, float)) and not isinstance(value, bool)
            and math.isfinite(value) and 0.0 <= value <= 1.0)


class ItemStatus(str, Enum):
    QUEUED = "queued"
    DONE = "done"


@dataclass
class ReviewItem:
    """One output awaiting a routing decision."""

    item_id: str
    kind: str                            # e.g. "refund_draft", "answer", "tool_call"
    payload_ref: str = ""                # pointer to the artefact under review
    confidence: float | None = None      # uncalibrated proxy; None = unknown
    risk_tier: str = "medium"            # low | medium | high | critical
    priority: int = 0                    # explicit boost; higher = reviewed sooner
    metadata: dict[str, Any] = field(default_factory=dict)


@dataclass
class QueueEntry:
    item: ReviewItem
    route: Route
    score: float
    status: ItemStatus = ItemStatus.QUEUED
    verdict: str = ""
    enqueued_at: float = 0.0
    completed_at: float | None = None


class ReviewQueue:
    """Confidence-threshold routing plus random audit sampling.

    Parameters
    ----------
    confidence_threshold:
        Below this (or when confidence is None) an item always routes to
        REVIEW. Above it, items route to AUTO — except the audit sample.
    audit_rate:
        Fraction of confident items still sent to AUDIT review, to measure
        whether the confidence proxy is honest. 0.05 = 5%.
    rng / clock:
        Injectable for deterministic tests and demos.
    """

    def __init__(
        self,
        confidence_threshold: float = 0.6,
        audit_rate: float = 0.05,
        rng: random.Random | None = None,
        clock: Callable[[], float] = time.monotonic,
    ) -> None:
        if not 0.0 <= audit_rate <= 1.0:
            raise ValueError("audit_rate must be within [0, 1]")
        if not _usable_confidence(confidence_threshold):
            # A NaN threshold would make every "below threshold" test False
            # and route everything to AUTO.
            raise ValueError("confidence_threshold must be a number within [0, 1]")
        self.confidence_threshold = confidence_threshold
        self.audit_rate = audit_rate
        self._rng = rng or random.Random()
        self._clock = clock
        self._queue: list[QueueEntry] = []
        self._done: list[QueueEntry] = []
        self._auto_passed = 0

    # ------------------------------------------------------------- routing

    def route(self, item: ReviewItem) -> Route:
        """Decide AUTO / REVIEW / AUDIT for one item.

        Routing rules, in order:
          1. Unknown, malformed (bool, NaN, infinite, outside [0, 1]) or
             below-threshold confidence, or an unrecognised
             risk tier -> REVIEW (we can't verify the proxy, so a human
             looks; a typo in the tier must not fall through to AUTO).
          2. Critical tier -> REVIEW always (dual control: a person must
             see it even when the model is confident).
          3. High tier, confident -> AUDIT always (100% sampled).
          4. Otherwise confident -> AUDIT with probability audit_rate,
             else AUTO.
        """
        if item.risk_tier not in _KNOWN_TIERS:
            return Route.REVIEW  # fail closed on a tier we do not recognise
        if not _usable_confidence(item.confidence) or item.confidence < self.confidence_threshold:
            return Route.REVIEW  # also catches None, bool, NaN, inf and 7.0
        if item.risk_tier == "critical":
            return Route.REVIEW
        if item.risk_tier == "high":
            return Route.AUDIT
        if self._rng.random() < self.audit_rate:
            return Route.AUDIT
        return Route.AUTO

    # ------------------------------------------------------------- queue ops

    def enqueue(self, item: ReviewItem) -> QueueEntry | None:
        """Route an item; queue it if it needs a human. Returns the entry."""
        route = self.route(item)
        if route is Route.AUTO:
            self._auto_passed += 1
            return None
        entry = QueueEntry(
            item=item,
            route=route,
            score=self._score(item),
            enqueued_at=self._clock(),
        )
        self._queue.append(entry)
        self._queue.sort(key=lambda e: e.score, reverse=True)
        return entry

    def next_item(self) -> QueueEntry | None:
        """Return the highest-scored queued item without removing it —
        the reviewer 'claims' it by calling complete() when done."""
        for entry in self._queue:
            if entry.status is ItemStatus.QUEUED:
                return entry
        return None

    def complete(self, entry: QueueEntry, verdict: str) -> None:
        """Record a human verdict ("ok", "fix", "escalate", ...) and drop
        the entry from the queue."""
        if entry.status is not ItemStatus.QUEUED:
            raise ValueError("entry already completed")
        entry.status = ItemStatus.DONE
        entry.verdict = verdict
        entry.completed_at = self._clock()
        self._queue.remove(entry)
        self._done.append(entry)

    # ------------------------------------------------------------- scoring

    def _score(self, item: ReviewItem) -> float:
        """Higher = review sooner. Transparent on purpose — reviewers should
        be able to see *why* an item jumped the queue."""
        confidence_gap = (
            1.0 - item.confidence if _usable_confidence(item.confidence) else 1.0
        )   # a NaN key would misorder list.sort, so malformed counts as unknown
        risk = {"low": 0.0, "medium": 1.0, "high": 3.0, "critical": 5.0}.get(
            item.risk_tier, 1.0
        )
        return (
            item.priority * 10.0
            + confidence_gap * 5.0
            + risk
            + self._age_bonus(item)
        )

    def _age_bonus(self, item: ReviewItem) -> float:
        """Small nudge so old items don't starve behind fresh high-priority ones."""
        created = item.metadata.get("created_at")
        if created is None:
            return 0.0
        return min((self._clock() - float(created)) / 60.0, 2.0)

    # ------------------------------------------------------------- stats

    def stats(self) -> dict[str, int]:
        counts = {r.value: 0 for r in Route}
        for entry in self._done:
            counts[entry.route.value] += 1
        counts[Route.AUTO.value] = self._auto_passed
        return counts


# --------------------------------------------------------------------- demo

if __name__ == "__main__":
    queue = ReviewQueue(confidence_threshold=0.6, audit_rate=0.10,
                        rng=random.Random(42))

    items = [
        ReviewItem("it-001", "refund_draft", confidence=0.92, risk_tier="high",
                   metadata={"order": "ORD-4472"}),
        ReviewItem("it-002", "answer", confidence=0.41, risk_tier="medium",
                   metadata={"question": "sick leave policy"}),
        ReviewItem("it-003", "classification", confidence=None, risk_tier="low",
                   metadata={"ticket": "T-1024"}),
        ReviewItem("it-004", "tool_call", confidence=0.88, risk_tier="critical",
                   priority=5, metadata={"tool": "delete_account"}),
        ReviewItem("it-005", "answer", confidence=0.95, risk_tier="low",
                   metadata={"question": "store hours"}),
        ReviewItem("it-006", "answer", confidence=0.97, risk_tier="medium",
                   metadata={"question": "return window"}),
        ReviewItem("it-007", "refund_draft", confidence=0.55, risk_tier="high",
                   metadata={"order": "ORD-9901"}),
        ReviewItem("it-008", "answer", confidence=0.93, risk_tier="low",
                   metadata={"question": "wifi password"}),
    ]

    print("== routing ==")
    for item in items:
        # enqueue() routes once; None means AUTO. Never re-roll the dice
        # for display — the printed route must be the decision taken.
        entry = queue.enqueue(item)
        route = entry.route if entry else Route.AUTO
        conf = f"{item.confidence:.2f}" if item.confidence is not None else "  - "
        print(f"  {item.item_id} conf={conf} tier={item.risk_tier:8s} "
              f"priority={item.priority} -> {route.value.upper()}")

    print("\n== queue order (highest score first) ==")
    snapshot = sorted((e for e in queue._queue), key=lambda e: e.score, reverse=True)
    for i, entry in enumerate(snapshot, 1):
        print(f"  {i}. {entry.item.item_id} score={entry.score:5.1f} "
              f"route={entry.route.value} kind={entry.item.kind}")

    # Reviewer works the queue top-down via next_item/complete.
    print("\n== review session ==")
    while True:
        entry = queue.next_item()
        if entry is None:
            break
        verdict = "fix" if entry.item.confidence is not None and entry.item.confidence < 0.5 else "ok"
        queue.complete(entry, verdict)
        print(f"  {entry.item.item_id}: {verdict} (was {entry.route.value})")

    print("\n== stats ==", queue.stats())

Run it:

bash
uv run python ai_product/review_queue.py
Output27 lines
== routing ==
  it-001 conf=0.92 tier=high     priority=0 -> AUDIT
  it-002 conf=0.41 tier=medium   priority=0 -> REVIEW
  it-003 conf=  -  tier=low      priority=0 -> REVIEW
  it-004 conf=0.88 tier=critical priority=5 -> REVIEW
  it-005 conf=0.95 tier=low      priority=0 -> AUTO
  it-006 conf=0.97 tier=medium   priority=0 -> AUDIT
  it-007 conf=0.55 tier=high     priority=0 -> REVIEW
  it-008 conf=0.93 tier=low      priority=0 -> AUTO

== queue order (highest score first) ==
  1. it-004 score= 55.6 route=review kind=tool_call
  2. it-007 score=  5.2 route=review kind=refund_draft
  3. it-003 score=  5.0 route=review kind=classification
  4. it-002 score=  4.0 route=review kind=answer
  5. it-001 score=  3.4 route=audit kind=refund_draft
  6. it-006 score=  1.2 route=audit kind=answer

== review session ==
  it-004: ok (was review)
  it-007: ok (was review)
  it-003: ok (was review)
  it-002: fix (was review)
  it-001: ok (was audit)
  it-006: ok (was audit)

== stats == {'auto': 2, 'review': 4, 'audit': 2}

Notice it-004: critical tier, high confidence, explicit priority — it tops the queue because the scoring formula makes risk and priority visible, not hidden. The reviewer sees why an item jumped the line. And it-006 shows the audit sampler at work: confident, medium-tier output that cleared the threshold still routed to AUDIT because the seeded RNG drew below audit_rate — the random spot-check that keeps the confidence proxy honest. it-005 and it-008 are the only true AUTO passes; the queue listing and stats agree with the routing table because each item was routed exactly once.

4.5 Keeping the human effectively in the loop#

A human in the loop who rubber-stamps is worse than no human — they provide the appearance of oversight while adding latency and cost. The failure modes:

Failure What it looks like Why it happens
Rubber-stamping Approve clicked without reading, every time Review volume too high; items look identical; no consequence for bad approvals
Default-accept dark pattern "Approve" is the pre-selected, prominent button; "Reject" is hidden Designed for throughput, not accuracy — a dark pattern (Part 7)
Review fatigue Queue backed up; reviewers skim or batch-approve at end of day Volume exceeds attention budget; no prioritisation; no rotation
Automation bias Reviewer trusts the AI's confidence display over their own judgement The confidence signal is uncalibrated (3.5)
Learned helplessness Reviewer stops trying because their edits are rarely used Feedback loop broken; edits don't improve the system

The code-level controls (scoped grants, a policy-versus-human audit label, reviewer metrics) are in 08A.12 Part 6; the countermeasures below are the product side.

The countermeasures, mapped to code:

  • Prioritise by risk and uncertainty — the review queue's score does this; don't show reviewers a flat list.
  • Make the decision cost asymmetric — approving a bad refund costs more than rejecting a good one; the UI should reflect that (confirm dialogs on approve for high tiers, not on reject).
  • Measure review quality, not just throughput — track edit rate, reject rate, post-approval failure rate. A reviewer with 0% edit rate on a system with known errors is a signal, not a performance metric.
  • Cognitive forcing where it matters — Buçinca et al. (CSCW 2021) showed that making people engage analytically before seeing the AI's answer reduces over-reliance. For high-stakes reviews, require a justification field ("why are you approving this?") before the approve button enables — friction that forces thought.
  • Rotate and rest — reviewers who see the same item type for hours develop blind spots. Rotate queues, insert audit items with known answers (see below), and cap daily review volume.
  • Seed the queue with known-answer items — occasionally insert a deliberately wrong item; if the reviewer approves it, that's a calibration signal about the reviewer, not the model. This is the human version of 10A.5's canary examples.

4.6 Interrupt, steer, undo, pause and resume, audit trails#

Control isn't just pre-action approval — it's everything the user can do while the AI works and after it finishes.

Control What it does When it matters
Interrupt/stop Halt generation or tool execution mid-flight Long responses, wrong direction, user changed their mind
Steer Redirect mid-task ("actually, focus on Q3") Conversational agents, multi-step tasks
Undo Reverse the last action or edit Any reversible action; critical for rung 4-5 autonomy
Pause/resume Suspend a long-running task, return later Batch jobs, document processing, agent runs
Audit trail User-visible log of what the AI did, when, why Consequential actions, compliance, debugging

The UX rules:

  • Interrupt must actually interrupt. A "Stop" button that hides the output but lets the model keep running (and billing) is a lie. 03.3's disconnect handling covers the API side; the UX side is making the stop feel immediate and be complete.
  • Undo must restore exactly. "Undo" that approximates the prior state is worse than no undo — it teaches users the system is unreliable. Store the prior state, not a diff to reverse.
  • Steer is a first-class input, not a new prompt. "Wait, I meant the March invoice" mid-generation should adjust the current task, not start a new conversation. The event contract (13A.2) needs a steer or interrupt event type.
  • Audit trails are user-facing, not just internal. "What did the AI do while I was away?" should have a readable answer — a timeline of actions, approvals, and outcomes the user can scroll. The approval gate's audit trail is the backend (its design is in 08A.12 section 6.4); the UI is a filtered, human-readable view.
  • Pause/resume must survive disconnects. A user who closes the laptop shouldn't lose a 20-minute document-processing job — the job continues server-side, the UI reconnects to its state (13A.2's resumable streams, 13A.5's job patterns).

4.7 Standing approvals: reducing approval fatigue without removing the gate#

A gate that fires on every step teaches users to click through (4.5). Agents that run many steps make this worse, and the pressure to add "always allow" is predictable. The safe answer is not "never allow it" but to make standing approvals narrow, visible and revocable:

Design choice Weak version (trains rubber-stamping) Safer version
Scope "Always allow tool calls" "Allow lookup_order (read-only) for this ticket queue", bound to one action type, one resource set and a risk tier
Duration Forever This session, this task or N days, with an expiry the user sees at grant time
Ceiling Can be extended to anything A hard ceiling set by risk tier (4.1): a standing approval can never cover rung-3 actions such as refunds or deletions
Granularity of the ask One prompt per call Plan-level approval (approve the proposed plan of 5 steps once) or batch approval (approve 20 similar items with a diff view) for low-risk, reversible work
Visibility Silent after the first click A "standing approvals" list in settings and an in-context marker when one is used, each with a one-click revoke
Audit Not recorded Every use logs which standing approval covered it, so 4.6's audit trail still answers "who allowed this?"

Two implementation notes (the grant mechanics are in 08A.12 section 6.3). First, a standing approval is data, not a prompt: store it as a rule the policy layer evaluates (08A.14, 2.10) before it ever reaches ApprovalGate, so a model cannot "remember" its way into broader permission. Second, treat the grant screen as a consent surface: opt-in and opt-out take equal friction, or you have built the "nudged acceptance" dark pattern of 7.1. Measure the outcome (approval rate, edit rate on approved items, post-approval reversals): a standing approval that cuts prompts by 80% while reversals stay flat is working; one where reversals climb is not.

What this means for you as an engineer: autonomy is a spectrum you design per action, not a setting you ship once. The approval gate and review queue are the enforcement layer; the audit trail and undo are the safety net. And the human in the loop is only as good as the system that keeps them honest — measure their review quality, not just their throughput.


Part 5: Feedback design#

Deep-dive

Trust is built on evidence, and feedback is the evidence users give back. This part covers how to ask for it, what signals to capture, and how to turn it into eval cases — the data flywheel that makes the product better.

5.1 Explicit signals: thumbs, ratings, taxonomies, edits, reports#

Explicit feedback is what the user deliberately tells you. The signals, from weakest to strongest:

Signal What it captures Strength Cost
Thumbs up/down Binary satisfaction Weak — no reason, no context Near-zero UX cost
Reason taxonomy Why they rated it Moderate — structured, analysable One extra click
Comment/free text Nuance, specifics Strong — but unstructured, needs labelling User effort; moderation needed
Edit tracking What they changed Very strong — a corrected output is a labelled example Requires edit-capture infrastructure
Report button Safety/policy violations Strong — but different pipeline (safety, not quality) Dedicated triage
Regenerate/abandon Implicit dissatisfaction Moderate — behavioural, not stated Free (already logged)

The design rules:

  1. Thumbs without a reason is a dead end. A thumbs-down with no way to say why collects noise, not signal. Always pair the rating with an optional reason taxonomy — feedback.py implements this.
  2. The taxonomy must be small and stable. "What was wrong?" with 12 options is a research project; with 5-7 it maps to eval slices. Start with the taxonomy in 5.2 and resist adding categories until you have data showing the gap.
  3. Edit is the highest-value signal. When a user edits your draft and sends it, they've produced a labelled example: input → corrected output. Capture it — it's the cheapest eval data you'll ever collect (09.10's insight).
  4. Report is not feedback. A "report" button routes to safety/policy triage, not quality eval — different team, different SLA, different taxonomy (harm type, not helpfulness).
  5. Feedback must be visible to the user. "Was my feedback used?" — show a confirmation, a count ("helped improve 47 answers this month"), or a changelog. Feedback that disappears teaches users it's pointless.

5.2 The reason taxonomy#

The closed set of "what was wrong" categories. Keep it aligned with your eval dimensions:

Code Meaning Maps to eval slice
wrong Incorrect information Accuracy/factuality
unhelpful Didn't answer the question Task completion
incomplete Missing needed information Coverage/recall
too_verbose Too long or complex Conciseness/style
unsafe Unsafe, biased, inappropriate Safety (routes to 12.x, not eval)
off_topic Answered a different question Relevance/routing
other Something else Free-text follow-up required

Rules:

  • One primary reason per event. Multi-select dilutes the signal; let the comment carry nuance.
  • unsafe routes differently. It goes to safety triage, not the eval flywheel — but it still gets logged as feedback for the safety metrics (12.4, 12.10).
  • other requires a comment. If the taxonomy doesn't fit, the user must say why — otherwise it's a label you can't use.

This table is the path's one reason taxonomy. The capstone copilot (13B.2) uses these seven codes unchanged. The RAG service in 07.11 predates it and accepts a narrower, source-aware set (wrong, outdated, missing_source, other); map those four onto this table as wrong to wrong, outdated to wrong (keep the original value in the stored row, because a stale-source cluster needs a different fix from a bad generation), missing_source to incomplete, and other to other. Only codes in this table should reach the eval slices.

5.3 Implicit signals#

Not all feedback is stated. Behavioural signals are often more honest:

Signal What it suggests Caveats
Copied Output was useful enough to use Could be copied to complain about it
Accepted suggestion Draft was good enough Acceptance ≠ correctness — automation bias applies
Regenerated First attempt wasn't good enough Could be curiosity, not dissatisfaction
Abandoned mid-task Lost interest or hit a wall Could be unrelated interruption
Edit distance How much the user changed Small edits = mostly right; large edits = mostly wrong
Time-to-answer Fast answers may be too shallow; slow may be too complex Confounded by question difficulty
Escalated to human AI couldn't handle it Strong signal — but measure rate, not just count

10A.9's online evaluation owns the statistical treatment — the biases in feedback (satisfied users respond less, dissatisfied users respond more) and how to correct for them. This section's job is the UX: instrument these signals at the event level, because retrofitting them later is impossible.

Feedback data is user data. Before you capture it:

  • Consent: does the user know their thumbs-down, edits and comments are collected? A privacy policy mention isn't enough for sensitive contexts — in-product notice ("we use your feedback to improve answers") is the pattern.
  • PII in feedback: users paste personal data into comments, edits contain their corrections which may include PII, payloads contain their inputs. 12.4's leak-path checklist applies — feedback stores are a leak path like any other.
  • Retention: feedback events have a lifecycle — raw events for debugging (days), aggregated signals for metrics (months), curated eval cases (indefinite, but PII-scrubbed). 12.4's retention schedules own the policy side.
  • User control: can users see what feedback they've given, delete it, opt out? "Download my data" should include feedback events; "delete my account" must cascade to them.

5.5 From feedback to eval cases: the data flywheel#

flowchart LR
    U["User rates / edits / abandons"] --> F["feedback.py<br/>typed events + JSONL store"]
    F --> T["Triage<br/>cluster by reason/kind/slice"]
    T --> C["Curate<br/>eval cases via feedback_to_evalkit"]
    C --> G["Regression gate<br/>10A.8 CI suite"]
    G --> P["Prompt/model fix"]
    P --> B["Better production answers"]
    B --> U
    C -.->|"pii_reviewed=False<br/>scrub before canonical use"| S["12.4 PII pipeline"]

The flywheel: production feedback → curated eval cases → prompt/model improvements → better production → more (better) feedback. The mechanics:

  1. Capture — feedback.py stores typed events with payloads (the exchange, not just the rating).
  2. Triage — nightly job clusters feedback by reason/kind/slice; high-volume clusters get priority.
  3. Curate — a human (or LLM-assisted pipeline) converts clusters into eval cases: the thumbs-down becomes a "does not repeat this failure" rubric; the edit becomes an expected output.
  4. Gate — new eval cases join the regression suite (10A.8); prompt/model changes must pass them.
  5. Measure — the eval pass rate on feedback-derived cases becomes a product metric (13A.6 owns the metrics layer).
python
"""ai_product/feedback.py — typed user-feedback events, a JSONL store,
and an exporter that turns feedback into evalkit eval cases.

Pure standard library. Three jobs:

  1. Capture — FeedbackEvent records *what* the user did (thumbs, reason,
     edit, report...) attached to the exchange it refers to.
  2. Store — append-only JSONL, one event per line, the same convention
     evalkit uses for datasets (10A.2).
  3. Export — feedback_to_evalkit() writes EvalExample-shaped JSONL rows.
     A thumbs-down becomes a case tagged for human labelling; an *edit*
     becomes a case whose expected output is the user's corrected text —
     the cheapest labelled data you will ever collect.

Privacy: exported cases carry provenance.pii_reviewed=False on purpose —
the eval pipeline must scrub personal data before a case joins the
canonical set (12.4 owns that machinery).
"""

from __future__ import annotations

import json
import time
import uuid
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Any, Iterable


class FeedbackKind(str, Enum):
    THUMBS_UP = "thumbs_up"
    THUMBS_DOWN = "thumbs_down"
    REASON = "reason"            # taxonomy pick attached to a thumbs event
    EDITED = "edited"            # user edited the draft/output before using it
    REGENERATED = "regenerated"  # user asked for another attempt
    COPIED = "copied"            # user copied the output somewhere
    ABANDONED = "abandoned"      # user started but never used/sent it
    REPORTED = "reported"        # safety/policy report
    COMMENT = "comment"          # free-text remark


# The closed taxonomy for "what was wrong" — keep it small; every new value
# is a labelling decision your eval slices inherit.
REASON_TAXONOMY = {
    "wrong": "the output contained incorrect information",
    "unhelpful": "it did not answer what I asked",
    "incomplete": "it missed part of what I needed",
    "too_verbose": "it was longer or more complicated than needed",
    "unsafe": "it was unsafe, biased or inappropriate",
    "off_topic": "it answered a different question than I asked",
    "other": "something else (see comment)",
}


@dataclass
class FeedbackEvent:
    """One signal about one exchange."""

    kind: FeedbackKind
    exchange_id: str                     # id of the conversation turn / output
    reason: str = ""                     # REASON_TAXONOMY key or short code
    comment: str = ""
    payload: dict[str, Any] = field(default_factory=dict)
    # payload convention: {"inputs": {...what the user sent...},
    #                     "output": {...what the model produced...},
    #                     "edited_output": {...} for EDITED events}
    user_ref: str = ""                   # pseudonymous id, never an email/name
    created_at: float = 0.0
    event_id: str = ""

    def to_dict(self) -> dict[str, Any]:
        d = {
            "event_id": self.event_id,
            "kind": self.kind.value,
            "exchange_id": self.exchange_id,
            "reason": self.reason,
            "comment": self.comment,
            "payload": self.payload,
            "user_ref": self.user_ref,
            "created_at": self.created_at,
        }
        return d

    @classmethod
    def from_dict(cls, d: dict[str, Any]) -> "FeedbackEvent":
        return cls(
            kind=FeedbackKind(d["kind"]),
            exchange_id=d["exchange_id"],
            reason=d.get("reason", ""),
            comment=d.get("comment", ""),
            payload=d.get("payload", {}),
            user_ref=d.get("user_ref", ""),
            created_at=d.get("created_at", 0.0),
            event_id=d.get("event_id", ""),
        )


class FeedbackStore:
    """Append-only JSONL store. One FeedbackEvent per line."""

    def __init__(self, path: str | Path) -> None:
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)

    def record(self, event: FeedbackEvent) -> FeedbackEvent:
        if not event.event_id:
            event.event_id = uuid.uuid4().hex[:12]
        if not event.created_at:
            event.created_at = time.time()
        with self.path.open("a", encoding="utf-8") as fh:
            fh.write(json.dumps(event.to_dict(), ensure_ascii=False) + "\n")
        return event

    def load(self) -> list[FeedbackEvent]:
        if not self.path.exists():
            return []
        events = []
        with self.path.open(encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if line:
                    events.append(FeedbackEvent.from_dict(json.loads(line)))
        return events

    def by_kind(self, kind: FeedbackKind | str) -> list[FeedbackEvent]:
        kind = FeedbackKind(kind)
        return [e for e in self.load() if e.kind is kind]

    def reason_counts(self) -> dict[str, int]:
        counts: dict[str, int] = {}
        for e in self.load():
            if e.reason:
                counts[e.reason] = counts.get(e.reason, 0) + 1
        return dict(sorted(counts.items(), key=lambda kv: -kv[1]))


# Kinds that mark approval rather than a problem — exported as regression
# guards instead of failure cases.
_POSITIVE_KINDS = {
    FeedbackKind.THUMBS_UP,
    FeedbackKind.COPIED,
}


# ------------------------------------------------------------- evalkit export

def feedback_to_evalkit(
    events: Iterable[FeedbackEvent],
    out_path: str | Path,
    *,
    split: str = "dev",
    include_kinds: Iterable[FeedbackKind] | None = None,
) -> int:
    """Write feedback events as EvalExample-shaped JSONL rows (10A.2 schema).

    Mapping rules:
      EDITED       -> expected = the user's corrected output (a real label)
      THUMBS_DOWN + REASON -> rubric criterion derived from the taxonomy,
                      needs human confirmation before it can score
      REGENERATED  -> ambiguous signal (5.3), never an approval: exported
                      with a "first attempt did not satisfy" rubric for a
                      human to confirm
      other kinds  -> exported with a generic rubric so nothing is silently
                      dropped; set include_kinds to filter

    Returns the number of rows written. Rows without a payload are skipped —
    an eval case needs inputs.
    """
    include = {FeedbackKind(k) for k in include_kinds} if include_kinds else None
    events = list(events)
    # Reason taxonomy often arrives as a *follow-up* event on the same
    # exchange (user thumbs-downs, then picks a reason). Join it here so
    # the exported case carries the reason, not just the bare signal.
    reasons_by_exchange: dict[str, str] = {}
    for e in events:
        if e.kind is FeedbackKind.REASON and e.reason:
            reasons_by_exchange[e.exchange_id] = e.reason
    for e in events:
        if not e.reason and e.exchange_id in reasons_by_exchange:
            e.reason = reasons_by_exchange[e.exchange_id]
    out = Path(out_path)
    out.parent.mkdir(parents=True, exist_ok=True)
    written = 0
    with out.open("w", encoding="utf-8") as fh:
        for e in events:
            if include is not None and e.kind not in include:
                continue
            inputs = e.payload.get("inputs")
            if not inputs:
                continue  # no inputs -> not an eval case
            row = _event_to_eval_example(e, inputs, split)
            fh.write(json.dumps(row, ensure_ascii=False) + "\n")
            written += 1
    return written


def _event_to_eval_example(
    e: FeedbackEvent, inputs: dict[str, Any], split: str
) -> dict[str, Any]:
    tags = {"source": "user-feedback", "feedback_kind": e.kind.value}
    if e.reason:
        tags["reason"] = e.reason

    expected = None
    rubric = []
    if e.kind is FeedbackKind.EDITED and e.payload.get("edited_output") is not None:
        expected = {"response": e.payload["edited_output"]}
    elif e.kind in _POSITIVE_KINDS:
        # Approval signals become regression guards: "don't get worse than
        # what the user accepted."
        rubric = [{"criterion": "maintains the quality the user approved",
                   "weight": 1.0,
                   "guidance": "positive user signal; guard against regression"}]
    elif e.kind is FeedbackKind.REGENERATED:
        # Ambiguous signal (5.3): a regeneration can be curiosity, not
        # dissatisfaction — never an approval. Export it as a case for a
        # human to judge, not as a regression guard.
        rubric = [{"criterion": "the first attempt did not satisfy the user",
                   "weight": 1.0,
                   "guidance": "user asked for another attempt; ambiguous "
                               "signal — confirm what was lacking before scoring"}]
    else:
        criterion = (
            f"does not repeat the problem the user flagged "
            f"({REASON_TAXONOMY.get(e.reason, e.reason or e.kind.value)})"
        )
        rubric = [{"criterion": criterion, "weight": 1.0,
                   "guidance": e.comment or REASON_TAXONOMY.get(e.reason, "")}]

    notes = e.comment or ""
    if e.kind is FeedbackKind.THUMBS_DOWN and not e.reason:
        notes = (notes + " " if notes else "") + "[needs reason taxonomy]"

    # event_id is assigned by FeedbackStore.record(); events passed in by
    # hand fall back to exchange+kind so two kinds on one exchange can't
    # produce colliding example_ids.
    example_id = e.event_id or f"{e.exchange_id}-{e.kind.value}"
    return {
        "example_id": f"fb-{example_id}",
        "inputs": inputs,
        "expected": expected,
        "split": split,
        "tags": tags,
        "rubric": rubric,
        "provenance": {
            "source": "production-log",
            "recorded_by": "user-feedback",
            "pii_reviewed": False,
            "notes": "exported from user feedback; scrub PII before canonical use",
        },
        "notes": notes,
    }


# --------------------------------------------------------------------- demo

if __name__ == "__main__":
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        store = FeedbackStore(Path(tmp) / "feedback.jsonl")

        # A support-copilot conversation: draft answer, user edits it, thumbs down.
        exchange = {
            "inputs": {
                "ticket": "T-991: 'I was charged twice for March invoice INV-2042'",
                "mode": "draft_reply",
            },
            "output": {"draft": "We're sorry for the inconvenience. "
                                 "A refund has been issued for $84.50."},
        }

        store.record(FeedbackEvent(
            kind=FeedbackKind.EDITED, exchange_id="conv-1042", event_id="ev-0001",
            payload={**exchange,
                     "edited_output": {"draft": "We've identified a duplicate "
                                                "charge on INV-2042 ($84.50). "
                                                "A refund is being processed "
                                                "and should appear in 5-10 "
                                                "business days."}},
            user_ref="agent:u_77", comment="added the invoice number and timeline",
        ))
        # Two-step pattern: thumbs-down first, the reason taxonomy arrives
        # as a follow-up event on the same exchange.
        store.record(FeedbackEvent(
            kind=FeedbackKind.THUMBS_DOWN, exchange_id="conv-1055",
            payload={"inputs": {"question": "How many sick days do I get?"},
                     "output": {"answer": "You get 30 sick days per year."}},
            user_ref="agent:u_12", comment="policy says 15 days for my tier",
            event_id="ev-0002",
        ))
        store.record(FeedbackEvent(
            kind=FeedbackKind.REASON, exchange_id="conv-1055",
            reason="wrong", user_ref="agent:u_12", event_id="ev-0003",
        ))
        store.record(FeedbackEvent(
            kind=FeedbackKind.ABANDONED, exchange_id="conv-1061", event_id="ev-0004",
            payload={"inputs": {"question": "draft a apology email"}},
            user_ref="agent:u_31",
        ))
        store.record(FeedbackEvent(
            kind=FeedbackKind.THUMBS_UP, exchange_id="conv-1070", event_id="ev-0005",
            payload={"inputs": {"question": "what's the return window?"},
                     "output": {"answer": "30 days from delivery."}},
            user_ref="agent:u_44",
        ))

        print("== recorded events ==")
        for e in store.load():
            print(f"  {e.event_id} {e.kind.value:12s} reason={e.reason or '-':8s} "
                  f"exchange={e.exchange_id} comment={e.comment[:50]}")

        print("\n== reason counts ==", store.reason_counts())

        out = Path(tmp) / "evals" / "feedback_cases.jsonl"
        n = feedback_to_evalkit(store.load(), out)
        print(f"\n== exported {n} eval cases to {out.name} ==")
        for line in out.read_text().splitlines():
            row = json.loads(line)
            print(f"  {row['example_id']}: tags={row['tags']} "
                  f"expected={'yes' if row['expected'] else 'no'} "
                  f"rubric={len(row['rubric'])} pii_reviewed="
                  f"{row['provenance']['pii_reviewed']}")
        print("\n  first row, pretty-printed:")
        print(json.dumps(json.loads(out.read_text().splitlines()[0]), indent=2)[:800])

Run it:

bash
uv run python ai_product/feedback.py
Output41 lines
== recorded events ==
  ev-0001 edited       reason=-        exchange=conv-1042 comment=added the invoice number and timeline
  ev-0002 thumbs_down  reason=-        exchange=conv-1055 comment=policy says 15 days for my tier
  ev-0003 reason       reason=wrong    exchange=conv-1055 comment=
  ev-0004 abandoned    reason=-        exchange=conv-1061 comment=
  ev-0005 thumbs_up    reason=-        exchange=conv-1070 comment=

== reason counts == {'wrong': 1}

== exported 4 eval cases to feedback_cases.jsonl ==
  fb-ev-0001: tags={'source': 'user-feedback', 'feedback_kind': 'edited'} expected=yes rubric=0 pii_reviewed=False
  fb-ev-0002: tags={'source': 'user-feedback', 'feedback_kind': 'thumbs_down', 'reason': 'wrong'} expected=no rubric=1 pii_reviewed=False
  fb-ev-0004: tags={'source': 'user-feedback', 'feedback_kind': 'abandoned'} expected=no rubric=1 pii_reviewed=False
  fb-ev-0005: tags={'source': 'user-feedback', 'feedback_kind': 'thumbs_up'} expected=no rubric=1 pii_reviewed=False

  first row, pretty-printed:
{
  "example_id": "fb-ev-0001",
  "inputs": {
    "ticket": "T-991: 'I was charged twice for March invoice INV-2042'",
    "mode": "draft_reply"
  },
  "expected": {
    "response": {
      "draft": "We've identified a duplicate charge on INV-2042 ($84.50). A refund is being processed and should appear in 5-10 business days."
    }
  },
  "split": "dev",
  "tags": {
    "source": "user-feedback",
    "feedback_kind": "edited"
  },
  "rubric": [],
  "provenance": {
    "source": "production-log",
    "recorded_by": "user-feedback",
    "pii_reviewed": false,
    "notes": "exported from user feedback; scrub PII before canonical use"
  },
  "notes": "added the invoice number and timeline"
}

What the demo shows: five events of different kinds; the exporter writes four eval cases (the reason-only event has no payload, so it's skipped — a rating needs an exchange to evaluate). The edited event exports with expected = the user's corrected text — a real label. The thumbs_down exports with a rubric criterion derived from its reason taxonomy. The thumbs_up exports as a regression guard ("maintain the quality the user approved"). All carry pii_reviewed=False — the eval pipeline must scrub before canonical use.

One mapping subtlety worth internalising: a regenerated event never becomes a regression guard. 5.3's table calls it what it is — an ambiguous signal that may be curiosity rather than dissatisfaction — so the exporter files it as a case for a human to judge ("the first attempt did not satisfy the user"), not as an approval. Treating regeneration as a positive signal would teach the eval suite to penalise the system for producing output the user implicitly rejected.

5.6 Anti-patterns#

Anti-pattern What it looks like Why it fails
Thumbs-down with no why Rating collected, reason never asked Noise, not signal — you can't act on "bad"
Feedback that disappears User rates, never sees it used Users stop giving it; the flywheel starves
Feedback as surveillance Every click tracked, no disclosure Trust violation; may violate consent rules
Optimising for feedback volume Pop-ups asking for ratings constantly Annoys users; biases toward extremes (only delighted/angry respond)
Ignoring negative feedback Metrics dashboard shows thumbs-up rate only Survivorship bias — 10A.9's feedback_bias.py shows why raw rates lie
Feedback without eval linkage Data collected, never converted to cases The flywheel is broken — you're collecting for collection's sake

What this means for you as an engineer: feedback is a product feature, not a settings page. Design the taxonomy before you ship the button; capture the payload, not just the rating; and wire the exporter before you need it — retrofitting feedback→eval is ten times harder than building it in.


Part 6: Memory and personalisation UX#

Deep-dive

08B.2 owns the memory machinery — the four kinds of memory, the MemoryStore, write policies, retrieval scoring, poisoning defences. This section is the UX contract: what the user sees, controls, and expects when your AI "remembers" them.

6.1 What "remembered" means to a user#

Users don't distinguish short-term context from long-term memory — they just notice the bot "knows things". That knowledge can come from:

  • This conversation — what they said 3 messages ago (context window; 02.7)
  • Previous conversations — what they told the bot last week (long-term memory; 08B.2)
  • Their profile — name, role, preferences, past behaviour (key-value or profile memory)
  • Inferred patterns — "you usually ask about billing" (learned from behaviour, not stated)

The UX problem: users can't tell which kind of memory produced a response, and they can't predict what will be remembered. A bot that "remembers" your dietary restriction but not your name feels arbitrary; one that remembers everything feels surveilled.

6.2 Showing what is remembered#

The pattern that works: a visible, inspectable memory surface. Not a buried settings page — a "What I remember" view the user can reach from the conversation.

Element What it shows Example
Memory list Each remembered fact/preference with its source "You prefer metric units (from settings, March 2026)"
Source attribution Where the memory came from "You told me in conversation #1042" vs "Inferred from 5 similar queries"
Confidence/recency How sure the system is, how stale the memory is "Updated 2 weeks ago" / "Low confidence — inferred"
Edit/delete per item Granular control, not all-or-nothing Edit "metric" → "imperial"; delete "prefers window seats"
Bulk controls Clear all, export, pause learning "Forget everything" / "Stop learning from me"
In-context indicator Subtle marker when memory is used "Using your saved preference: metric units"

The rules:

  1. Memory is inspectable, not hidden. If the user can't see what the bot knows, they can't correct it — and they'll assume the worst (that it knows everything).
  2. Source matters. "You told me" is different from "I inferred" — the user should know which, because inferred memories are more likely wrong and more likely to feel creepy.
  3. Edit is better than delete-and-relearn. Letting users correct a memory ("I'm not vegetarian, I'm vegan") teaches the system faster than making them delete and re-explain.
  4. Deletion must cascade. "Forget this" removes it from the memory store and from future retrieval — not just hidden from the UI. 08B.2's MemoryStore handles the mechanics; the UX must make the promise.
  5. Inferred memories need consent. Behavioural inference ("you always ask about X") should be opt-in or clearly disclosed — 12.4's consent rules apply.

6.3 Surprising-memory incidents#

The failure mode that destroys trust: the bot references something the user doesn't remember telling it, or uses a memory in a context where it doesn't belong.

Incident type What happens Prevention
False memory Bot claims user said X; they didn't Memory write validation (08B.2, 6.2); source attribution lets users catch it
Stale memory Bot uses a preference from 2 years ago that no longer applies TTL/decay on memories (08B.2, 4.4); recency display
Cross-context leak Memory from work context surfaces in personal context Namespace isolation (08B.2, 5.1); context-aware retrieval
Inferred creepiness Bot "knows" something user never stated and finds invasive Consent for inference; transparent source labels; easy opt-out
Memory poisoning Malicious content written to memory persists and influences future outputs 08B.2's memory safety; input validation on writes

The UX response to an incident: acknowledge, correct, prevent recurrence. "You're right, I shouldn't have used that — I've removed it" + a visible audit of what was deleted + a system change that prevents the class of error. The incident is a trust test; the response is the trust builder.

Before memory is enabled, the user should understand:

  • What is remembered (facts, preferences, conversation summaries, behavioural patterns)
  • Where it's stored (their account, your servers, the provider's API)
  • Who can see it (them, your team for debugging, the provider per their policy)
  • How to see, edit, delete, and export it
  • How to turn it off (per-feature, per-conversation, globally)

This is 12.4's data-map requirement at the UX level: the memory contract is the user-facing half of the privacy policy. 08B.2's user-visibility section covers the engineering side; this is the design side.

What this means for you as an engineer: memory is a trust feature, not a convenience. Users forgive a bot that forgets; they don't forgive one that remembers wrong. Build the "what I remember" surface before you build the memory store — the UX contract shapes the data model, not the other way around.


Part 7: Dark patterns and manipulation in AI UX#

Deep-dive

Parts 1-6 designed for trust. This part audits for its opposite: the patterns that exploit trust, attention and autonomy. Defensive framing throughout — you're learning to recognise and refuse these in your own product, not to deploy them.

7.1 The landscape#

AI UX has unique dark patterns because the system is probabilistic, persuasive and always available. The taxonomy:

Pattern What it looks like Why it's dark
Sycophancy by design System prompt tuned to never disagree, always validate, flatter the user Exploits the user's desire to be right; erodes their judgement over time (02.10, Part 10)
Fake urgency "Only 3 refunds left!" / "This offer expires in 2 minutes!" — generated by AI, not real Manufactured scarcity; the AI can produce convincing urgency copy on demand
Hidden AI No disclosure; users assume they're talking to a person Violates consent; Part 2.4 covers the legal floor
Nudged acceptance "Approve all future actions" pre-checked; "Don't ask again" prominent; reject hidden Autonomy escalation without informed consent (4.1)
Engagement loops Infinite AI chat, streaks, "you haven't talked to me today", guilt trips Optimises time-on-site over user outcomes; the AI equivalent of slot-machine design
Fake verification "Verified by AI" badges, progress spinners implying checks that don't happen Evidence theatre — users can't distinguish real from decorative (3.4)
Misleading explanations Explanations crafted to increase trust regardless of correctness Lakkaraju & Bastani (AIES 2020) showed this is possible — and that it's manipulation
Bait-and-switch autonomy User thinks they're chatting; system is taking actions Autonomy without consent; the worst kind because it's invisible until it matters
Surveillance feedback Every interaction tracked, no disclosure, used for profiling Trust violation; 5.4 covers the consent rules

7.2 How manipulation works here#

The mechanism is the same as classic dark patterns — exploit a cognitive bias — but AI makes it scalable and personalised:

  • Sycophancy exploits the user's desire to be right. A bot that never disagrees feels supportive; it also means the user stops checking. The fix isn't a cold bot — it's honest disagreement ("I don't think that's right because...") and calibrated confidence.
  • Fake urgency exploits loss aversion. AI-generated urgency is convincing because it's specific ("your refund window closes Friday" vs generic "limited time"). The fix: urgency claims must be verifiable or absent.
  • Hidden AI exploits the user's assumption of humanity. The fix: disclosure at every boundary (2.4).
  • Nudged acceptance exploits default bias and friction asymmetry. The fix: autonomy changes require equal-friction opt-in and opt-out, and a visible audit trail of what was auto-approved.
  • Engagement loops exploit variable-reward psychology. The fix: success metrics are user outcomes (task completion, resolution), not session length.
  • Fake verification exploits the user's trust in process. The fix: every "verified" claim must map to a real check (3.2).

7.3 Auditing your own UI#

The audit is a checklist, run before launch and quarterly after:

Disclosure audit

  • Users know they're talking to AI at every entry point
  • AI-generated content is labelled where it leaves the UI
  • Agent/human boundaries are visible in every transition
  • No simulated humanity (fake typing, human names on bot messages)

Autonomy audit

  • Every action type has a documented rung on the autonomy dial
  • Rung-3+ actions go through the approval gate, not a prompt instruction
  • "Don't ask again" requires explicit, equal-friction opt-in
  • Undo exists for every reversible action; audit trail is user-visible

Evidence audit

  • Citations are verified, not just present
  • Confidence displays are calibrated or absent
  • "Verified" claims map to real checks
  • Abstention is a designed state, not a silent failure

Feedback audit

  • Thumbs have a reason taxonomy; edits are captured
  • Feedback is visible to the user as "used"
  • Feedback data has consent, retention and deletion paths
  • Feedback exports to eval cases automatically

Manipulation audit

  • No urgency/scarcity claims that aren't verifiable
  • No engagement loops optimising for time-on-site
  • Sycophancy is measured (flip rate on pushback) and bounded
  • Dark-pattern review: would you be comfortable showing this UI to a regulator?

The last question is the real test: if a journalist or regulator saw your UI, would they call it deceptive? If yes, it's a dark pattern — fix it before launch, not after.

What this means for you as an engineer: dark patterns aren't a design team's problem — they're an engineering problem because they're implemented in code. The approval gate, the reason taxonomy, the audit trail — these are the same mechanisms that enable trust and prevent manipulation. Build them right once, and both goals are served.


Part 8: The pattern catalogue, the checklist, and the ai_product package#

Reference

8.1 The pattern catalogue#

Every pattern in this lesson, in one table — the reference you'll keep open while designing:

Pattern Problem it solves Solution shape When NOT to use Product shapes
Capability statement Users don't know what the AI can/can't do Honest paragraph at point of use Trivial tools where the function is obvious All
First-run examples Users don't know how to start 3-5 real example prompts from golden set Features with no prompting (upload-only) Chat, copilot
"AI can be wrong" notice Users over-trust fluent output Specific, located, actionable copy Low-stakes where error cost ≈ 0 All, scaled by risk
Limitation notice Known bounded limits surprise users Named limitation + workaround, at point of use When the limitation is already obvious All
AI disclosure label Users think they're talking to a person Visible "AI" marker at interaction boundary Internal tools with trained users only All user-facing
AI-content label Generated content leaves the UI unmarked Label/metadata on export Ephemeral in-app content never shared Generation, voice
Agent/human boundary marker Users can't tell who acted Visible transition events Single-agent systems with no handoff Agents, voice
Persona with disclosure Engagement vs honesty tension Named/warm persona + "I'm an AI" High-stakes where persona adds risk Consumer, support
Inline citations Users can't verify factual claims [n] markers + hover preview + click-through Creative writing, no factual claims RAG, Q&A
Source region highlights Extracted values feel arbitrary Field-level link to source Unstructured free-text output Document AI, extraction
"Show your work" summary Output feels like a black box One-line "how I got this" + expandable detail When process is trivial or confidential Agents, extraction
Tool-call trace Agent actions are opaque Compressed step list, expandable Single-shot completions Agents, voice
Confidence bucket Users need uncertainty signal High/Med/Low calibrated to eval data When no calibrated signal exists Classification, routing
Abstention with path "I don't know" is a dead end Named gap + next step (human, partial, clarify) When partial answers mislead RAG, support
Side-by-side diff User can't see what changed Original vs output, per-change accept Read-only outputs Editing, drafts
Autonomy dial User doesn't know how much AI acts Per-action rung, enforced in code Single fixed-autonomy tools All consequential
Approval gate Consequential actions run unchecked pending→approved/rejected/expired + audit Read-only actions Refunds, deletions, sends
Review queue High-volume outputs need sampling Priority-scored queue + confidence routing Low-volume where gate suffices Drafts, classifications
Sampling audit Trust is established but unverified Random % of confident outputs to review When volume is too low to sample High-volume Q&A
Confidence routing Low-confidence outputs slip through Below-threshold → review automatically When confidence signal is uncalibrated Classification
Dual control Highest-risk needs two humans Two approvals required When latency matters more than safety Payments, legal
Escalation path AI gets stuck or out-of-scope Explicit "ask a human" tool + handoff When escalation rate would be >50% Support, agents
Interrupt/stop User can't halt runaway generation Real cancel, not just hide Trivial outputs (<2s) Streaming, agents
Undo AI actions are irreversible in practice Exact prior-state restore Truly irreversible actions (published posts) Drafts, edits, actions
User-visible audit trail "What did the AI do?" has no answer Readable timeline of actions/approvals Internal tools with no user-facing actions Agents, automation
Thumbs + reason Ratings without context are noise Binary + optional taxonomy + comment When taxonomy can't be kept small All conversational
Edit capture User corrections are lost Track edits as labelled examples Read-only outputs Drafts, copilot
Feedback→eval exporter Feedback never improves the system JSONL → EvalExample cases automatically When eval infra doesn't exist yet All
"What I remember" surface Memory is invisible and uncorrectable Inspectable list + edit/delete/export No memory features Personalised, agents
Memory source labels "You told me" vs "I inferred" Attribution per memory item When all memories are user-stated Personalised
Surprise-memory response Wrong memory destroys trust Acknowledge + delete + prevent When memories can't be wrong Personalised
Dark-pattern audit Manipulation hides in plain sight Pre-launch checklist + quarterly review Internal tools with no external users All user-facing

8.2 The pre-launch trust checklist#

Copy this into your project before shipping any AI feature:

markdown
## Trust & Transparency Checklist

### Disclosure
- [ ] Users know they're interacting with AI at every entry point
- [ ] AI-generated content is labelled where it leaves the UI
- [ ] Agent/human boundaries are visible in every transition
- [ ] No simulated humanity (fake typing, human names on bot messages)
- [ ] Legal disclosure requirements reviewed (12.9, jurisdiction-specific)

### Expectations
- [ ] Capability statement is visible at point of use
- [ ] First-run examples are real, from golden set, not marketing
- [ ] "AI can be wrong" notice is specific, located, actionable
- [ ] Known limitations have named notices with workarounds
- [ ] Limitation register is maintained and pruned when fixed

### Evidence
- [ ] Every output type has its strongest practical evidence
- [ ] Citations are verified, not just present
- [ ] Confidence displays are calibrated or absent
- [ ] Abstention is a designed state with a path forward
- [ ] "Show your work" is available at appropriate depth

### Control
- [ ] Every action type has a documented autonomy rung
- [ ] Rung-3+ actions go through approval gate, not prompt instruction
- [ ] "Don't ask again" requires equal-friction opt-in
- [ ] Undo exists for every reversible action
- [ ] Audit trail is user-visible and readable
- [ ] Interrupt/stop actually stops (not just hides)

### Feedback
- [ ] Thumbs have a reason taxonomy; edits are captured
- [ ] Feedback is visible to the user as "used"
- [ ] Feedback data has consent, retention, deletion paths
- [ ] Feedback exports to eval cases automatically
- [ ] Negative feedback routes to safety triage when `unsafe`

### Memory
- [ ] "What I remember" surface is inspectable and editable
- [ ] Memory sources are labelled (stated vs inferred)
- [ ] Deletion cascades to store and retrieval
- [ ] Inferred memories have consent and opt-out

### Dark patterns
- [ ] No urgency/scarcity claims that aren't verifiable
- [ ] No engagement loops optimising for time-on-site
- [ ] Sycophancy is measured and bounded
- [ ] Would a regulator call this UI deceptive? If yes, fix it.

8.3 The ai_product package and the FastAPI sketch#

This lesson adds three files to ai_product. The package grows across 13A.1–13B.6; the cumulative tree as of this lesson:

text
ai_product/
├── __init__.py
├── feature_brief.py      # 13A.1 — AI feature brief (Pydantic) + validator
├── events.py             # 13A.2 — typed SSE event models + encoder
├── smoother.py           # 13A.2 — chunk smoother (paced streaming)
├── progress.py           # 13A.2 — step-status tracker for multi-step work
├── approval.py           # 13A.3 — ApprovalGate state machine (this lesson)
├── review_queue.py       # 13A.3 — priority review queue (this lesson)
└── feedback.py           # 13A.3 — feedback events + evalkit exporter (this lesson)

Files from 13A.1 and 13A.2 are listed so the tree is cumulative; the three marked "this lesson" are the ones you save from this page.

The three files in this lesson are pure standard library — no dependencies, no keys. For a FastAPI service that exposes them (the shape 13A.5's reference architecture will formalise), the sketch is:

python
# app.py — ILLUSTRATIVE FastAPI sketch. Needs: fastapi and uvicorn[standard] (checked against 0.162.0 and 0.54.0)
# Save the three ai_product modules alongside this file and run:
#   uvicorn app:app --reload
from __future__ import annotations

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

from ai_product.approval import ApprovalGate, ApprovalRequest, Decision, GateError
from ai_product.review_queue import ReviewItem, ReviewQueue
from ai_product.feedback import FeedbackEvent, FeedbackKind, FeedbackStore

app = FastAPI(title="AI Product Trust Layer")

gate = ApprovalGate(ttl_seconds=300)
queue = ReviewQueue(confidence_threshold=0.6, audit_rate=0.05)
store = FeedbackStore("data/feedback.jsonl")


class ApprovalIn(BaseModel):
    action: str
    args: dict
    reason: str = ""
    risk_tier: str = "medium"


class DecisionIn(BaseModel):
    decision: str          # "approved" | "rejected" | "edited"
    actor: str
    edited_args: dict | None = None


class FeedbackIn(BaseModel):
    kind: str              # FeedbackKind value
    exchange_id: str
    reason: str = ""
    comment: str = ""
    payload: dict = {}
    user_ref: str = ""


@app.post("/approvals")
def create_approval(body: ApprovalIn) -> dict:
    rid = gate.submit(ApprovalRequest(
        action=body.action, args=body.args, reason=body.reason,
        risk_tier=body.risk_tier))
    return {"request_id": rid, "status": "pending"}


@app.get("/approvals/pending")
def pending_approvals() -> list[dict]:
    return [{"id": r.request_id, "action": r.request.action,
             "args": r.request.args, "risk_tier": r.request.risk_tier}
            for r in gate.pending()]


@app.post("/approvals/{rid}/decision")
def decide(rid: str, body: DecisionIn) -> dict:
    try:
        rec = gate.decide(rid, Decision(body.decision), body.actor,
                          edited_args=body.edited_args)
    except (GateError, ValueError) as exc:
        raise HTTPException(status_code=409, detail=str(exc))
    return {"id": rid, "status": rec.status.value,
            "decided_by": rec.decided_by}


@app.get("/approvals/{rid}/audit")
def approval_audit(rid: str) -> list[dict]:
    try:
        gate.get(rid)
    except GateError:
        raise HTTPException(status_code=404, detail="unknown request")
    return [{"event": e.event, "actor": e.actor, "detail": e.detail}
            for e in gate.audit_trail(rid)]


@app.post("/review/enqueue")
def enqueue_review(item: dict) -> dict:
    entry = queue.enqueue(ReviewItem(**item))
    return {"routed": entry.route.value if entry else "auto",
            "score": entry.score if entry else None}


@app.get("/review/next")
def next_review() -> dict:
    entry = queue.next_item()
    if entry is None:
        return {"empty": True}
    return {"id": entry.item.item_id, "kind": entry.item.kind,
            "route": entry.route.value, "score": entry.score,
            "payload_ref": entry.item.payload_ref}


@app.post("/feedback")
def record_feedback(body: FeedbackIn) -> dict:
    event = FeedbackEvent(
        kind=FeedbackKind(body.kind), exchange_id=body.exchange_id,
        reason=body.reason, comment=body.comment, payload=body.payload,
        user_ref=body.user_ref)
    store.record(event)
    return {"event_id": event.event_id}

This is a sketch, not a service — it has no auth, no persistence beyond the JSONL file, no rate limiting, and holds state in memory. 13A.5 builds the real version with ports, jobs and multi-tenancy.

8.4 Where you'll use this#

  • 13B.2 Support copilot: approval gate on refunds, review queue on drafts, feedback capture on every answer, citations on every claim.
  • 13B.3 Document intelligence: review queue as the core UX, source-region evidence, edit capture as the highest-value feedback.
  • 13B.5 Voice agent: spoken confirmation as rung-3 hybrid, audit trail as transcript, disclosure at call start.
  • 13B.6 Shipping: the pre-launch checklist is a launch gate; the dark-pattern audit is a pre-release review.
  • 13A.6 Metrics: the metric hierarchy for the signals this lesson generates — reliance and verification rates (1.5), escalation rate, review quality, feedback-derived eval pass rate.

What this means for you as an engineer: the pattern catalogue is the vocabulary; the checklist is the gate; the code is the enforcement. Ship features that pass the checklist, not features that merely demo well.


Common misconceptions#

Misconception Reality
"Users will trust the AI if we're confident." Confidence without evidence is persuasion, not trust. Users calibrate from verifiable signals — citations, diffs, audit trails — not adjectives.
"Explanations help users trust appropriately." Bansal et al. (CHI 2021) found explanations increase acceptance regardless of correctness. They persuade; they don't calibrate. Evidence does.
"Showing the model's confidence helps users." Verbalised confidence is poorly calibrated (02.10, 12). Show calibrated proxies (retrieval scores, judge disagreement) or route by them silently.
"A disclaimer covers us." "AI can be wrong" in fine print is legally present and functionally absent. The notice must be specific, located and paired with a check affordance.
"Human-in-the-loop means a human approves everything." That doesn't scale and produces rubber-stamping. The right pattern depends on volume, reversibility and risk — approve/reject for high-stakes, batch review for volume, sampling audit for established trust.
"The approval prompt is enough." "Please ask before refunding" in a system prompt is a suggestion the model can forget. A gate in code is a guarantee.
"Thumbs-down is feedback." It's a signal without context. Pair it with a reason taxonomy and capture the payload — or you're collecting noise.
"Memory makes the product better, so enable it." Memory is a trust feature. Users forgive forgetting; they don't forgive remembering wrong. Build the inspectable surface first.
"A named, friendly persona builds trust." It builds engagement — and anthropomorphism risk. The persona can be warm; the disclosure can't be optional, and accountability must stay human-legible.
"Dark patterns are a design problem." They're implemented in code — pre-checked boxes, hidden reject buttons, engagement-loop logic. Engineers own the fix.
"Once trust is built, it stays." Trust is per-task and per-context. A single confident error on a high-stakes action can poison a feature permanently (algorithm aversion, Dietvorst et al. 2015).

Key takeaways#

  • Calibrated trust is the goal, not maximum trust. Under-trust (disuse) and over-trust (misuse) are symmetric failures; both cost you — one the feature's value, the other its worst error.
  • The research is clear: explanations persuade but don't calibrate (Bansal CHI 2021); cognitive forcing reduces over-reliance but users dislike it (Buçinca CSCW 2021); confidence scores help but aren't sufficient (Zhang FAT* 2020); people abandon algorithms faster than humans after one visible error (Dietvorst JEP:G 2015).
  • Disclosure is a trust primitive, not just compliance. Users must know they're talking to AI, where AI content is labelled, and when a human takes over — at every boundary, not just in terms of service.
  • Evidence beats reassurance. Citations, source regions, diffs and audit trails are verifiable; "our AI is accurate" is not. Show the strongest evidence each output type supports.
  • Verbalised confidence is unreliable. Show calibrated proxies or route by them silently — never display "87% confident" as if it were a measurement.
  • The autonomy dial is per-action, enforced in code. Suggest → draft → ask-before-acting → act-and-notify → act silently; the minimum rung is set by risk, not user preference.
  • Human-in-the-loop fails silently. Rubber-stamping, default-accept and review fatigue defeat oversight while appearing to provide it. Measure review quality, not just throughput.
  • Feedback is a product feature. Typed events, reason taxonomies, edit capture, consent, and automatic export to eval cases — the flywheel that makes the product better.
  • Memory is a trust feature. Inspectable, editable, deletable, with source labels — or it's surveillance.
  • Dark patterns are engineering failures. Sycophancy by design, fake urgency, hidden AI, nudged acceptance — they're implemented in code, and the same mechanisms that enable trust prevent them.

Terms introduced in this lesson#

Term One-line definition
Calibrated trust Trust that matches real reliability — users verify exactly what needs verifying
Reliance rate Share of shown outputs the user acts on — the behavioural half of trust measurement
Verification rate Share of shown outputs the user checks before relying on them
Under-trust / disuse Users ignore the feature because they don't trust it enough (algorithm aversion)
Over-trust / misuse Users accept output without checking because they trust it too much (automation bias)
Automation bias Over-reliance on automated output, defeating human oversight
Complacency Reduced monitoring of automation due to over-trust
Cognitive forcing function Design that makes users engage analytically before seeing AI's answer, reducing over-reliance
Capability statement Honest description of what the AI can do, can't do, and what good looks like
Limitation notice Named, bounded disclosure of a known AI limitation with a workaround
AI disclosure Telling users they're interacting with an AI system
AI-content label Marking generated content as AI-produced when it leaves the UI
Agent/human boundary Visible transition between AI acting and human acting
Persona The name, voice and manner of an AI assistant
Anthropomorphism Attributing human-like minds, feelings or intentions to non-human agents
Evidence-based explanation Explanation that lets users verify independently (citations, source regions)
Plausibility-based explanation Fluent, confident prose that persuades without informing
Verbalised confidence The model saying "I'm 90% sure" — poorly calibrated, treat as decoration
Confidence proxy Measurable signal correlated with correctness (retrieval score, judge disagreement)
Abstention The system declining to answer when it lacks sufficient basis
Autonomy dial Per-action spectrum from suggest to act silently, enforced in code
Human-in-the-loop (HITL) Human oversight of AI actions at designated points
Approval gate State machine requiring human decision before consequential actions run
Review queue Prioritised list of outputs awaiting human review
Sampling audit Random fraction of confident outputs sent to review for quality checks
Confidence-threshold routing Low-confidence outputs automatically routed to human review
Dual control Two humans must approve the highest-risk actions
Rubber-stamping Approving without reading, defeating the purpose of review
Feedback taxonomy Closed set of "what was wrong" categories for structured feedback
Edit capture Recording user edits to AI output as labelled training examples
Feedback flywheel Production feedback → eval cases → improvements → better production
"What I remember" surface User-visible, inspectable view of what the AI remembers about them
Memory poisoning Malicious content written to memory that persists and influences outputs
Dark pattern UX design that exploits cognitive biases for engagement at user expense
Sycophancy by design Tuning the system to never disagree, eroding user judgement
Nudged acceptance Pre-checked "approve all" or hidden reject options escalating autonomy without consent
Standing approval A narrow, time-limited, revocable rule that pre-authorises a low-risk action type, evaluated by the policy layer, never covering rung-3 actions
Trust repair Acknowledge, scope, correct in place and prevent recurrence after a visible failure
Evidence theatre "Verified" badges or spinners implying checks that don't happen

All terms are also collected in the glossary.


Exercises#

All exercises work without API keys — they use the code from this lesson, design critique, and copywriting.

  1. Autonomy dial design. For each of these actions in a support copilot, assign an autonomy rung and justify it: (a) look up order status, (b) draft a refund reply, (c) issue a refund under $50, (d) issue a refund over $500, (e) close a ticket, (f) escalate to a human agent. Which actions would you raise the rung for after a month of data? Which would you never lower?

  2. ApprovalGate walkthrough. Run ai_product/approval.py and trace the audit trail. Then modify the demo: make the reviewer reject the refund instead of approving it, and add a fourth request that gets approved after the TTL but before expire_due() is called. What does the gate do, and why is that the right behaviour?

  3. Review queue tuning. Run ai_product/review_queue.py with confidence_threshold=0.8 and audit_rate=0.20. How does the routing change? What happens to queue depth and reviewer load? At what threshold does the queue become unmanageable?

  4. Feedback→eval export. Run ai_product/feedback.py and inspect the exported JSONL. Pick one thumbs_down event and write the eval case a human would create from it — what expected or rubric would you add that the auto-exporter didn't?

  5. Disclosure copy. Write three versions of an "AI can be wrong" notice for a medical-style FAQ bot (non-clinical): one minimal, one standard, one high-stakes. Which would you ship, and why?

  6. Dark-pattern audit. Take any AI chat product you use (ChatGPT, Claude, Gemini, Copilot). Audit its UI against the 7.3 checklist. Which items pass? Which fail? Is the failure a dark pattern or a genuine limitation?

  7. Memory surface design. Sketch (ASCII or wireframe) a "What I remember" page for a personal AI assistant. What memories would you show? How would you label inferred vs stated? What edit/delete controls would you include?

  8. Surprise-memory incident response. Write the three-sentence response a support agent would give when a user says "Why do you think I live in Berlin? I never told you that." What system change prevents recurrence?

  9. Evidence audit. Pick an AI feature you use daily. For its main output type, what's the strongest evidence it could show? Does it show it? If not, what's the gap between current and possible?

  10. Cognitive forcing trade-off. Buçinca et al. (CSCW 2021) found cognitive forcing reduces over-reliance but users rate it least favourably. Design a cognitive forcing function for a refund-approval UI that doesn't feel like friction — what would you show before the approve button enables?

  11. Standing approval design. A support team wants "always allow lookups" for their copilot. Using the table in 4.7, write the scope, duration, ceiling and revocation rule, and name two metrics that tell you it is working.

Hints for the exercises
  1. Defensible answers: (a) rung 5, read-only; (b) rung 2; (c) rung 3 at first, with rung 4 plus an undo window as the candidate to raise it to once post-approval reversals are near zero; (d) rung 3, with dual control worth considering; (e) rung 3 or 4 depending on whether a closed ticket can be reopened without harm; (f) rung 4, because escalating is the safe direction. Never lower: anything the risk tier sets as a floor (refunds, deletions).
  2. Rejecting the refund changes the audit entry to rejected and the final state to rejected. For the late approval: decide() calls _expire_if_due() first, so the gate expires the request by clock, logs expired, then raises GateError. Expiry must not depend on a sweeper having run, otherwise a late "yes" could slip through.
  3. With the shipped eight-item fixture the routing does not change at 0.8 and 0.20, because no item sits between 0.6 and 0.8 and the seeded RNG draws the same audit decisions. Add items with confidence 0.65 to 0.79 (and more of them) to watch REVIEW depth grow; the queue becomes unmanageable when arrivals per hour in REVIEW exceed what your reviewers can check with real attention, a number you must measure, not guess.
  4. A good human case adds an expected answer or a precise rubric criterion (for example "states the 15-day policy for the customer's tier and cites the policy section"), which the auto-exporter cannot infer from a bare thumbs-down.
  5. Compare against 2.2's three registers; a non-clinical FAQ bot usually ships the "standard" version with a pointer to a human or official source for anything personal.
  6. Typical failures are missing per-surface labels and no visible audit trail; whether a failure is a dark pattern depends on intent and effect (a hidden reject button is; an absent feature is a limitation).
  7. Show each memory with its source ("you told me" or "inferred"), age, edit and delete controls, and a global pause. Inferred items need the clearest label and an opt-in.
  8. Acknowledge, remove, and say what was removed: "You're right, I shouldn't have used that. I inferred it from earlier conversations, and I've deleted it; you can see everything I still remember here. I'll flag this so inferred details are labelled and need your OK." Prevention: consent for inference and source labels (6.2).
  9. Compare with the table in 3.1; the gap is usually that the product shows prose but not the source.
  10. Examples: require the reviewer to pick which source supports the amount before the button enables, or show the policy clause and ask them to confirm the number. Keep the friction proportional: high tier only, and measure approval time and error catch rate.
  11. A reasonable answer: scope to lookup_order and lookup_customer for one queue; duration of the shift or 8 hours; ceiling at rung 3 (never covers refunds or deletions); a "standing approvals" list with one-click revoke. Metrics: approval prompts per ticket (should fall) and post-approval reversals or edit rate (should stay flat).

Check yourself#

  1. What are the two symmetric failures of calibrated trust, and which research tradition names them?
  2. Why did Bansal et al. (CHI 2021) conclude that AI explanations don't improve complementary team performance?
  3. What did Buçinca et al. (CSCW 2021) find about cognitive forcing functions, and what's the trade-off?
  4. Why is verbalised confidence ("I'm 90% sure") unreliable as a user-facing signal?
  5. What's the difference between a limitation notice and a general "AI can be wrong" disclaimer?
  6. Name three places AI disclosure must appear beyond the terms of service.
  7. What's the difference between rung 3 (ask-before-acting) and rung 4 (act-and-notify) on the autonomy dial?
  8. Why is a prompt instruction ("please ask before refunding") weaker than an approval gate in code?
  9. What makes a review queue effective vs a rubber-stamp queue?
  10. What's the highest-value explicit feedback signal, and why?
  11. Why must exported eval cases carry pii_reviewed=False?
  12. What's the difference between "you told me" and "I inferred" memory, and why does the distinction matter?
  13. Name three AI-specific dark patterns and the mechanism each exploits.
  14. Why is "act silently" almost never the right rung for consequential actions?
  15. What does the approval gate's audit trail answer that a system log doesn't?

Further resources#

  • Microsoft HAX Toolkit — Guidelines for Human-AI Interaction (https://www.microsoft.com/en-us/haxtoolkit/ai-guidelines/): the 18 evidence-based guidelines, design library and workbook. Paper: Amershi et al., CHI 2019.
  • Google PAIR — People + AI Guidebook (https://pair.withgoogle.com/guidebook): six chapters on mental models, trust, feedback, control and errors; pattern library included.
  • Apple Human Interface Guidelines — Generative AI (https://developer.apple.com/design/human-interface-guidelines/generative-ai/): platform guidance on transparency about AI use and keeping people in control of generated output.
  • Parasuraman & Riley, "Humans and Automation: Use, Misuse, Disuse, Abuse" (Human Factors 39(2):230–253, 1997): the foundational taxonomy of automation trust failures.
  • Dietvorst, Simmons & Massey, "Algorithm Aversion" (JEP:General 144(1):114–126, 2015): why one visible error permanently damages trust in algorithms.
  • Bansal et al., "Does the Whole Exceed its Parts?" (CHI 2021): explanations increase acceptance regardless of correctness — the evidence against explanation-theatre.
  • Buçinca, Malaya & Gajos, "To Trust or to Think" (Proc. ACM HCI 5, CSCW1, 2021): cognitive forcing functions reduce over-reliance, at a UX cost.
  • Zhang, Liao & Bellamy, "Effect of Confidence and Explanation on Accuracy and Trust Calibration" (FAT* 2020): confidence scores calibrate trust but aren't sufficient alone.
  • Jung, Brahman & Choi, "Trust or Escalate" (ICLR 2025, arXiv:2407.18370): selective trust with provable human-agreement guarantees — the theory behind confidence routing.
  • Lakkaraju & Bastani, "'How Do I Fool You?'" (AIES 2020, arXiv:1911.06473): misleading explanations can manipulate user trust — the warning behind evidence theatre.
  • Epley, Waytz & Cacioppo, "On Seeing Human" (Psychological Review 114(4):864–886, 2007): the three-factor theory of anthropomorphism.
  • EU AI Act Article 50 — transparency obligations for AI systems (https://ai-act-service-desk.ec.europa.eu/en/ai-act/article-50): the legal floor for disclosure; 12.9 covers the full compliance treatment.
  • This module's earlier lessons: 13A.1 product thinking, 13A.2 streaming UX, 13A.4 failure states, 13A.5 architecture, 13A.6 metrics.

← 13A.2 — AI UX I: Streaming, Latency and Perceived Speed | Module 13A overview | 13A.4 — AI UX III: Failure States, Edge Cases and Inclusive Design →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close