Agent That Adapts to New Tasks
Design an operations agent that learns new tasks on its own, adapting in the cheapest reversible place first and sending every self-change through the same gate as a human change.
- Kind
- Case study
- Level
- Advanced
- View
- Interview prep
- Sections
- 4
- By
- Sourav Banerjee
- Last updated
- 21 Nov 2026
Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.
Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.
Case brief
The case in one line: an operations agent that learns new tasks on its own, without ever quietly getting worse or granting itself more reach.
30-Second Cheat Sheet
- The product: an internal operations agent handling requests like "restart service X" and "roll back flag Y".
- The pressure: teams ship new systems, so new request types appear every week.
- The ask: adapt to new tasks on its own, without a person retraining it.
- The hidden constraint: every self-change is a regression nobody reviewed. It must never quietly get worse, and never grant itself more permission, budget or irreversible reach.
- The core idea: adapt in the cheapest, most reversible place first, and send every self-change through the same gate as a human change.
- The shape: five rungs (context, memory, procedure, prompt optimisation, weights), two loops (runtime and learning) and one evaluation gate.
- The human boundary: people approve irreversible actions, permission or budget changes, and re-promotion of a demoted skill.
1. An operations agent that meets new work every week
The scenario
- An internal operations agent handles requests such as "restart service X" and "roll back flag Y".
- Teams keep shipping new systems, so new request types appear every week.
- The ask: an agent that adapts to those new tasks on its own, without a person retraining it.
The hard constraint the ask hides
- Every change the agent makes to itself is a regression nobody reviewed.
- The agent needs freedom to change its behaviour.
- Yet it must never quietly get worse.
- And it must never grant itself more permission, budget or irreversible reach.
- A design that only says "the agent learns from experience" hasn't addressed that constraint yet.
The terms that carry the whole case
| Term | Meaning |
|---|---|
| Skill | A named, parameterised sequence of tool calls, such as safe_restart(service_name), with a precondition, a postcondition and a measured success rate |
| Rung | One place where learning can live, from the context of a single request up to the model's weights |
| Evaluation gate | The single checkpoint every learned change must pass before it touches live traffic |
| Shadow testing | Runs a candidate beside live behaviour on real requests without letting it act |
| Stratum | One slice of the evaluation set; here, one task type |
| LLM | Large language model: the model that plans and writes the agent's actions |
The core idea in one sentence
Adapt in the cheapest, most reversible place first, and send every self-change through the same gate as a human change.
The source figure as a flow (one request and what is learned from it):
- New request → known type?
- Yes → run with current skills.
- No → run in a tighter fallback mode.
- Outcomes and lessons → evaluation gate →
- Pass → promoted to memory, a skill or a prompt.
- Fail → discarded, or the live artefact is demoted.
The design in brief
- Five rungs of adaptation: context, memory, procedure, prompt optimisation and weights.
- Each rung is about ten times costlier and harder to undo than the one before.
- We work from the cheap end.
- Two loops, one gate:
- A runtime loop serves requests.
- A learning loop proposes changes.
- They meet at one evaluation gate.
- Every learned change passes a gate before it can affect a run.
- A fact learned during a run passes the four-check memory write policy before it is stored, and stays versioned and revertible.
- Skills, prompt changes, weight updates and memory candidates mined offline pass the same evaluation gate a human pull request would.
2. Follow one new task through the agent
The request (the source's running example): "Restart Orion payment service." The agent has never seen it.
- Route. The capability router finds no confident match among the live skills.
- Fallback. The request runs in a fallback mode with tighter limits.
- Reads are allowed freely.
- Risky writes need a person's approval.
- Explore. The agent reads documentation, inspects the service and learns that Orion must be drained before restart.
- Act. It drains, restarts, checks health and restores traffic.
- External verdict. External monitoring reports success.
- Trace. The run is stored as a trace.
- Memory. "Orion restart requires drain" passes the memory write policy and becomes a stored fact.
- Skill candidate. After repeated successes, the learning loop proposes a
safe_orion_restart(service)skill. - Gate. That skill reaches live traffic only after held-out evaluation, shadow testing and promotion.
- Demotion. It is demoted automatically if a later Orion API change makes it fail.
- The walkthrough's step 15 walks every step of this trace.
The human boundary is fixed throughout
- People approve:
- Irreversible actions.
- Any change to permissions or budgets.
- Re-promotion of a demoted skill.
- The agent may learn how to do a task, but it never decides that it is allowed to do more.
3. What you need to design
The task
Design an agentic AI system that can autonomously adapt to new tasks. Explain:
- What "adapt" means.
- How the system notices a new task.
- Where learning is stored.
- How learned behaviour is evaluated, promoted and removed.
- What the agent may never change about itself.
- Then defend the design against a cost pivot.
Who it's for
- An advanced case for engineers preparing for Forward Deployed, solutions or applied-AI engineering interviews.
- Especially an agent design round that asks how a system learns or improves over time.
What it assumes you know
- LLM agents, tool calling and agent memory.
- Offline evaluation, shadow testing and release gates.
By the end you should be able to
- Explain the design end to end, starting from the five rungs and the one gate.
- Answer follow-ups on:
- Novelty detection
- The memory write policy
- Skill promotion and demotion
- Prompt optimisation
- When to fine-tune
- Limits on the agent's autonomy
- The cost pivot
Where the source material comes from (caveats)
- No worked answer exists for this prompt. It comes from a problem decomposition question bank.
- The spine comes from the learning chapter of a book on agentic system design: its four learning surfaces, skill promotion gate and data flywheel answer most of the prompt.
- The memory write policy comes from the book's memory chapter.
- The release gate comes from its validation chapter.
- Every number marked as an assumption is a whiteboard illustration, not a sourced figure.
How to use the sections
- Read the walkthrough first.
- Practise rebuilding the answer from memory with the Practice section, in the full casebook.
- Rehearse the 60-minute plan aloud with a timer (Practice section of the full casebook).
- Come back to the level calibration (full casebook) and the Quick review the night before an interview.
Quick Recall: Lines to Say in the Interview
- "Every change the agent makes to itself is a regression nobody reviewed."
- "Adapt in the cheapest, most reversible place first."
- "Every self-change goes through the same gate as a human change."
- "Five rungs, two loops, one gate."
- "Each rung is about ten times costlier and harder to undo than the one before."
- "Unknown tasks run in a fallback mode with tighter limits: reads free, risky writes approved."
- "The agent may learn how to do a task, but it never decides it is allowed to do more."
Design walkthrough
The goal: an agent that adapts to new tasks through five rungs, two loops and one gate, and never changes what it is allowed to do.
30-Second Cheat Sheet
- Define "adapt" first: five rungs (context, memory, procedure, prompt optimisation, weights), each roughly 10× costlier and harder to undo. Design from the cheap end.
- Two loops, one gate: the runtime loop serves, the learning loop proposes, the evaluation gate decides. Learning never changes production directly.
- Detect novelty first: low retrieval score, unknown entity, near tie, or no skill above threshold → tighter fallback mode.
- Memory is a write problem: four gates (durable, reusable, attributable, permitted), typed facts, supersession.
- The gate numbers: beat baseline by 5 points, shadow ≥ 200 attempts, auto-demote at 4 points below, no stratum drops > 3 points.
- Know the limit: 200 cases detect only about 11 points at p = 0.8, so shadow proves "not much worse".
- Weights last, and only for format at volume, missing vocabulary, or a cost or latency ceiling.
- Bounded autonomy: the agent learns how; policy decides what it may do.
Opening line (source's version): "Before I design anything I want 'adapt' pinned down. There are five places learning can live, from the context of one request up to the model's weights. Each rung costs roughly ten times more than the last and is harder to undo. I'll design from the cheap end and only climb when a measured gap forces it."
1. Pin down what "adapt" means before drawing anything
- We can't design toward a verb nobody defined.
- "Adapt to new tasks" hides at least five mechanisms. They differ by an order of magnitude in cost and in how easily a change can be undone.
- "Autonomously adapt" does not mean "retrain itself". Most adaptation belongs in cheap, reversible places: context, memory and procedures.
Where the rungs come from
- The book names four places improvement can live: context, memory, procedure and parameters.
- Each is roughly ten times slower and costlier to iterate on than the one before.
- This case adds prompt optimisation as a separate rung between procedure and parameters.
- It changes behaviour broadly, like training.
- It stays reversible, like a prompt.
The ladder: context (cheapest, easiest to roll back) → memory → reusable skills → prompt optimisation → model weights (most expensive, hardest to roll back).
The five rungs in the ops agent
| Rung | What changes | Example in the ops agent | Iteration time | Undo |
|---|---|---|---|---|
| 1. Context | Instructions, examples and skills loaded for this request | Load the "feature flags" skill and three similar past runs | Minutes | Instantly |
| 2. Memory | Stored facts, preferences, corrections | "Service X restarts need a drain first" | Immediate | Supersede the fact |
| 3. Procedure | Validated tool sequences saved as named skills | A promoted "safe restart" workflow | Hours | Pin the previous version |
| 4. Prompt optimisation | Instructions and examples searched against a scored dev set | A rewritten planner prompt that raises tool-choice accuracy | Hours to a day | Revert the prompt version |
| 5. Parameters | Model weights | A tuned small router for the top task types | Days to weeks | Redeploy the old model |
One request up the ladder
- Rung 1: a request to restart payment-service-X loads the relevant runbook, similar successful examples and relevant memory. Nothing persists after the request.
- Rung 2: the system stores a reusable fact: "payment-service-X must be drained before restart."
- Rung 3: it keeps a reusable workflow: check health → drain traffic → restart → verify health → restore traffic.
- Rung 4: if the planner repeatedly makes the same mistake, test several prompt versions and promote the best.
- Rung 5: fine-tune or retrain, only when the cheaper mechanisms are not enough.
The interview principle as a chain: context → memory → skill → prompt → weights. Move from cheap and reversible toward expensive and hard to roll back.
Work down the table, not up
- The book's rule: start at rung 1.
- In the book's view, most teams that reach for fine-tuning haven't yet fixed their tool schemas, retrieval or example selection.
- Fine-tuning bakes those defects into weights that take weeks to change.
Spoken answer: "There are five places learning can live. Each rung costs roughly ten times more than the last and is harder to undo. I'll design from the cheap end and only climb when a measured gap forces it."
2. Ask the questions that change the design
- Each question below changes a component, a threshold or a permission. Ask before committing to an architecture.
| Question | Why it changes the design |
|---|---|
| What counts as a "new task": a new request type, a new tool, or a new domain? | New request type = context problem; new tool = onboarding path; new domain = knowledge and evaluation data |
| Is there an external signal of success (a test, a validator, a ticket closed without reopening)? | Without one, the agent can't learn safely: nothing trustworthy to learn from |
| Which actions are reversible? | Reversible ones can be tried and learned from; irreversible ones need a human before and after |
| Who owns each capability? | An owner reviews promotions and is paged when a skill regresses |
| How fast must a new task become reliable: hours, days or a quarter? | Hours forces the cheap rungs; a quarter permits training |
| Is the adaptation per user, per tenant or global? | Per-tenant learning needs isolation in every store |
The four strongest questions (answer template)
- What exactly is allowed to adapt? Context, memory, workflow, prompt or model weights.
- The answer defines the risk level.
- What is the source of truth for success? An API result, human approval, ticket resolution, a monitoring signal or a business KPI.
- Without a trusted outcome signal, learning becomes unreliable.
- How much autonomy is allowed for unknown tasks? Read-only, writes allowed, human approval, a financial limit, security-sensitive actions.
- The answer determines fallback behaviour.
- How fast does a new capability need to become production-ready?
- The answer determines shadow sample size, evaluation design, the traffic requirement and the human review process.
KPI = key performance indicator: the number the business watches to judge success.
Safe defaults if the interviewer doesn't answer
- State them aloud. The rest of the walkthrough uses them.
- New request types arrive weekly.
- Most have a checkable outcome.
- Writes to production systems are partly reversible.
- Adaptation is global, but each skill has a team owner.
3. State requirements as testable constraints
- A requirement that can't fail a test is a wish.
- "Gets better over time" is a wish.
- "Success on a new task type reaches the baseline within 14 days without a regression on any existing type" is a constraint. Its thresholds are assumptions.
Six functional must-haves (the guide)
- Recognise when a request doesn't match any known capability.
- Attempt it safely with a general fallback, escalating when confidence is low.
- Record every run with its outcome, so learning has evidence.
- Turn repeated successes into candidate skills, memories or prompt changes.
- Evaluate each candidate before it affects real traffic.
- Remove learned behaviour automatically when it starts to fail.
The answer template's ten steps
- Detect when a request doesn't match an existing skill.
- Safely attempt unknown tasks.
- Record complete execution traces.
- Learn reusable facts from successful outcomes.
- Extract reusable skills from repeated successful workflows.
- Propose prompt improvements.
- Evaluate every new learning candidate.
- Shadow-test candidates before production.
- Promote good candidates.
- Roll back or demote bad ones.
- Should-haves (later): per-tenant specialisation, a tuned small model for high-volume task types, and a dashboard showing owners what the agent learned this week.
Non-functional constraints (stated so they can fail)
- Three come from the book; the rest are labelled assumptions.
| Non-functional constraint | Stated so it can be tested |
|---|---|
| No regression | No existing task stratum drops more than 3 points after any promotion (per-stratum floor sourced from ch12's segment-collapse fix) |
| Promotion bar | Beats baseline by 5 points offline, then survives at least 200 live shadow attempts (sourced: the book's reference gate values) |
| Demotion | A skill falling 4 points below baseline is removed automatically (sourced) |
| Time to competence | New task type reaches baseline success within 14 days of first sighting (assumption) |
| Safety | Zero promotions that widen tool permissions; every irreversible action approved by a person |
| Traceability | Every behaviour change has a version, source trace set, evaluation report and owner |
| Latency | Runtime adaptation adds at most 150 ms at p95 before the first model call (assumption) |
| Cost | Learning-plane spend capped as a share of serving spend; cap breach blocks new candidates (assumption: 10%) |
p95 = 95% of requests finish faster than that figure.
The template's plainer production requirements
- Reliability: existing task performance shouldn't significantly regress; every learned capability must support rollback.
- Safety: unknown tasks run under tighter limits; the agent must never increase its own permissions.
- Observability: track the request, tool calls, prompt and model version, selected skill, result, latency, cost and external outcome.
- Cost: learning cost stays bounded.
- Latency: adaptation logic shouldn't make every live request slow.
- Auditability: every production change answers six questions:
- Who created it?
- Why was it created?
- What data supported it?
- Which evaluation passed?
- Who approved it?
- Which previous version can we roll back to?
Each requirement has an owner (bridge to step 5)
| Requirement | Primary component |
|---|---|
| Recognise the unknown | Capability router with a novelty score |
| Attempt safely | Bounded agent loop behind the tool gateway, with escalation |
| Record evidence | Trace and outcome store |
| Turn success into candidates | Learning plane: skill extractor, memory writer, prompt optimiser, dataset builder |
| Evaluate before traffic | Evaluation gate plus shadow runner |
| Remove failures | Live monitor with automatic demotion |
4. Size the adaptation before choosing a rung
- Arithmetic decides which rungs we can afford. Every input is an assumption; the arithmetic is exact.
| Quantity | Assumed value | Consequence |
|---|---|---|
| Requests per day | 20,000 across 40 known task types | Average 500 per type, heavily skewed |
| New task types per week | 3 | About 150 a year; the catalogue must evict as well as grow |
| Traffic for a new type | 30 requests a day | 200 shadow attempts take about 7 days at full shadow |
| Cost per agent run | $0.03 | Serving is about $600 a day |
| Offline eval suite per candidate | 640 cases, paired with baseline | 1,280 runs = $38.40 per candidate |
| Candidates generated per week | 50 | $1,920 a week, about 46% of the $4,200 weekly serving bill |
Lesson 1: rare task types can't be promoted quickly
- At 30 requests a day, 200 / 30 ≈ 7 days: the shadow minimum alone takes a week.
- That sets the honest time to competence.
- No promise of instant adaptation for low-frequency tasks. Learning speed depends on real production traffic.
Lesson 2: candidate volume drives learning cost, not training
- 50 × $38.40 = $1,920 a week, against a weekly serving bill of 7 × $600 = $4,200.
- That breaks a 10% learning budget almost five times over.
- So the extractor must deduplicate and pre-filter before anything reaches the paid evaluation.
- The answer template's heavier version: 50 skill candidates a week, each run against 1,000 evaluation cases, makes evaluation cost large and calls for staged evaluation (see the cost deep dive).
Sample size: what the gate can detect at all
- Formula (validation chapter):
n ≈ 15.7 × p(1−p) / δ²per arm.p= baseline success rate.δ= the difference we want to detect.
- At a baseline of 0.8,
p(1−p)= 0.16. - With 200 cases:
δ² ≈ 15.7 × 0.16 / 200, so δ ≈ 0.11. 200 cases detect only differences of about 11 points. - A 5-point gain needs
15.7 × 0.16 / 0.0025≈ 1,000 cases per arm.
Soundbite: "The 200-attempt shadow proves 'not much worse', meaning no more than about 11 points worse, not '5 points better'." Say it aloud; few candidates do.
The same arithmetic limits the per-stratum floor
- Detecting a 3-point drop at p = 0.8 needs
15.7 × 0.16 / 0.0009≈ 2,800 cases per arm in that stratum. - A 640-case suite over 40 task types holds 16 per type.
- That flags only a drop of about 40 points:
δ = √(15.7 × 0.16 / 16) ≈ 0.40.
- That flags only a drop of about 40 points:
- What to do:
- Size high-volume strata with the formula.
- For small strata, block on a large drop and lean on live monitoring.
- Paired runs help: both arms see the same cases, so only cases where they disagree carry signal. Fewer are needed when disagreement is rare.
5. Draw the architecture as two loops with one gate
- The runtime loop serves requests.
- The learning loop proposes changes.
- They meet at one place, the evaluation gate. Nothing learned reaches live traffic without passing it.
The two loops at a glance
- Runtime loop (uses only approved versions): request → router → approved capability → bounded agent → tool gateway → external system → outcome and trace.
- Learning loop (studies historical traces): production traces → find patterns → create candidate → evaluate → shadow → promote.
Soundbite: "The separation is the point. The runtime serves users, the learning loop proposes improvements, and evaluation decides whether an improvement is allowed into production. The learning loop can never change production directly."
The runtime loop in detail
- The capability router scores novelty.
- Known request → loads its live skill, examples and memories. Novel → general fallback with tighter bounds.
- Either path passes through the context assembler.
- A bounded agent acts, capped on steps, tokens, time and spend.
- Every action goes through the tool gateway: authorise → validate → execute → classify.
- An irreversible action requires human approval.
- The external outcome and the trace land in the trace and outcome store.
The learning loop in detail
- Starts from the trace and outcome store.
- Flywheel gates: deduplicate, split by time and user, send low-agreement cases to adjudication.
- Offline learning produces four candidate kinds:
- Generalised skills.
- Memory writes that must be durable, reusable, attributable and permitted.
- Prompt variants searched on a development set.
- A training dataset, only after rungs 1 to 4 are exhausted.
- Each candidate goes to held-out paired evaluation by stratum.
- Fail → discarded with a reason.
- Pass → shadowed for at least 200 attempts → owner review → promoted live.
- Live: each stratum is monitored; a skill 4 points below baseline is demoted automatically.
The control plane over both loops
- The capability registry versions each capability's ownership, status, permissions, budgets and kill switches.
- The runtime reads only live skills, memories, prompts and models.
- Candidate statuses: candidate, shadow, live and demoted.
- Evaluation has an absolute safety floor and reports cost visibly.
- The complete design (source figure): a control plane (capability registry, permission policy, budgets and kill switch) over the runtime loop and the learning loop, meeting at the eval gate before shadow, owner review and promotion. The source originally offered this as a Mermaid version for viewers that render it.
The answer template's high-level flowchart
- User request → capability router: is the task known?
- Known → load an approved skill or memory.
- Unknown → safe general fallback.
- Agent runtime → tool gateway and policy layer → external systems.
- Outcome validator → trace and outcome store.
- Learning pipeline → memory, skill, prompt or training-data candidates.
- Evaluation gate:
- Fail → reject, keep the previous version.
- Pass → shadow testing → healthy → owner review → promotion into the capability registry.
Components: job and failure
Read the third column as the reason the component exists.
| Component | Job | Fails how |
|---|---|---|
| Capability registry | Holds every learned artefact with version, owner, status and evidence | Without it, nobody can say what the agent learned or undo it |
| Capability router | Matches a request to live skills; scores novelty | Misroutes silently; a novel request forced into a wrong skill |
| General fallback | Attempts unknown tasks with tighter bounds and earlier escalation | Given the same bounds as known tasks, it explores dangerously |
| Context assembler | Loads skill instructions, examples and memories under per-section budgets | Loads everything; context rots and costs climb |
| Bounded agent loop | Plans and acts within step, token, time and spend caps | Loops forever on a task it can't do |
| Tool gateway | Authorises, validates and executes every action; routes irreversible ones to a person | Learned procedures call tools the agent was never allowed to call |
| Outcome signal | Provides an external verdict: test, validator, ticket state | Self-graded success teaches confident errors |
| Trace and outcome store | Records trajectory, versions used and outcome for every run | Learning has nothing trustworthy to learn from |
| Flywheel gates | Dedupe, split by time and user, adjudicate | Duplicates inflate every offline number |
| Skill extractor | Generalises successful trajectories into parameterised skills | Library fills with skills that worked once |
| Memory writer | Admits only durable, reusable, attributable, permitted facts | Memory fills with noise and contradictions |
| Prompt optimiser | Searches prompt and example variants against a scored dev set | Overfits the dev set; wins offline, loses live |
| Dataset builder | Prepares training data for rung 5 | Trains in the old system's errors |
| Eval gate | Blocks candidates that regress any stratum or touch safety | Gating on the mean hides a segment collapse |
| Shadow runner | Runs the candidate beside live behaviour without acting | Shadow on too little traffic proves nothing |
| Live monitor | Tracks per-stratum success and auto-demotes | Stale skills keep running after an API changes |
6. Detect the unknown before trying to handle it
- An agent can't adapt to a task it hasn't noticed is new.
- "I don't know how" is the easy case.
- The hardest failure: confidently forcing a new request into the nearest known skill.
- The agent knows
restart Kubernetes serviceand receivesrestart new serverless service. - A naive router maps the second onto the first.
- A restart procedure built for one platform runs against another.
- The agent knows
Score novelty on independent signals
The guide's three:
- The router's retrieval score against the skill catalogue falls below a threshold.
- The request names a system, tool or entity absent from every live skill.
- The router's top two candidates are close, so its choice is a coin flip.
The answer template's fourth:
- No existing skill passes a minimum confidence threshold.
- Illustration (threshold the template's author would tune on real routing data): best known-skill confidence 0.43 against a threshold of 0.75 → treated as a novel task.
- Any one signal routes the request to the general fallback instead of a skill.
The fallback is a different operating mode
- Not the same agent with a different prompt. Unknown tasks don't get normal production freedom.
- Less confidence about the task → less freedom for the agent:
- A lower step limit.
- Read-only tools first.
- Required approval for risky writes.
- Earlier human escalation.
- Those limits prevent: dangerous tool usage, infinite loops, accidental writes, permission misuse and costly experimentation.
- The first dozen runs of a new task type are the riskiest and the most valuable: they carry the evidence every later rung learns from.
Skill loading supports detection
- Start with a lightweight catalogue of skill names and triggers.
- Load one skill's full instructions only when selected, then release that context.
- Trigger descriptions need counterexamples as well as examples, or the wrong skill activates.
- Evaluate triggering separately from execution: a skill that runs perfectly after the wrong trigger is still a wrong answer.
7. Adapt within one request before changing anything permanent
- The cheapest adaptation changes nothing that outlives the request.
- Rung 1 covers two runtime-only mechanisms: dynamic example selection and Reflexion.
Dynamic example selection
- Fixed few-shot examples (A, B and C for every request) are chosen for the average request, so they're optimal for none.
- Instead: current request → search successful past executions → filter for relevant examples → add them to the prompt.
- Similarity alone is the wrong ranking. Prefer examples that are relevant, successful and diverse.
- A similar run that went badly teaches the model to go badly, so rank by recorded outcome too.
- Enforce diversity so three near-duplicates don't crowd out the useful one.
- The book's scoring formula:
λ × relevance − (1−λ) × redundancy + 0.15 × outcome score.λtrades relevance against redundancy with the examples already chosen.
The cost: prefix cache breaks.
- Examples sit above the user's turn, so swapping them per request breaks the prompt prefix cache from that point on.
- Only what sits above the examples (tool definitions, the fixed system prompt) still hits it.
- Where traffic clusters, cache one example set per cluster rather than choosing per request.
Prefix cache = reuses computation only for an identical leading section of the prompt.
Reflexion with an external judge
- Reflexion turns a failed attempt into a written lesson placed in context for the next attempt. The model itself doesn't change.
- Flow: the agent tries → an external system returns a clear failure signal → the agent writes a temporary lesson → retries.
- Source example: wrong timestamp format → API validation error → lesson "use ISO-8601 UTC format" → retry within budget.
Works reliably only under three conditions (the book):
- An external failure signal.
- A lesson specific enough to change behaviour.
- "Expected ISO 8601 UTC, I sent local time" is a lesson. "Be more careful" is not.
- A hard cap on attempts.
The agent must not grade itself.
- A model saying "I think my answer was correct" without an external signal tends to write confidently wrong lessons, which contaminate every later retry.
- A Reflexion implementation splits the pattern into actor, evaluator and self-reflection roles.
- This case's added rule: the evaluator must be external.
- Counts: an API result, a unit test, database state, ticket status, a monitoring signal or human approval.
- Doesn't count: the same model's opinion.
Cap retries.
- The template's author picks
Max retries = 2and says plainly that two is a choice, not a standard. - The cap prevents endless loops and runaway cost.
- A retry after a failed write needs one more check:
- The first attempt may have partly applied (a drain that finished before the restart failed).
- So the agent reads current state before acting again.
- The gateway treats a repeated irreversible action as needing a fresh approval.
8. Remember facts through a write policy
- Memory can only be as good as what the write policy let in; retrieval can't fix a bad write policy.
- Many candidates open with "which vector database should I use?"
- The memory chapter's question instead: what information is allowed to become memory?
The four gates every candidate memory passes
Durable: is it still true next month?
Reusable: would a future run read it?
Attributable: does it have a source, timestamp and confidence?
Permitted: is it allowed to be stored, outside regulated categories?
Drop or redact on the write path. The read path is too late.
Good memory: "Payment API max batch size = 100" passes all four.
Weak memory: "Service was slow at 3:17 PM today" is neither durable nor reusable.
Typed facts, not raw turns
- Store facts as subject-predicate-value records, never raw conversation turns, so contradictions collide by construction.
subject: payment-service
predicate: restart_precondition
value: drain_traffic
source: runbook-v4
timestamp: 2026-09-26
- Supersession: if the process changes to
restart_precondition = none, the new fact lands on the same subject and predicate.- The old record is marked superseded, with a pointer kept to it.
- The new one becomes active.
The book's worked failure
- In January a user said: book through vendor A.
- In February they switched to vendor B.
- Both were stored as separate episodes.
- Retrieval returned whichever phrasing was more similar, so vendor A reappeared about one time in four until May.
- Fixes: typed facts, plus a release-gate test that seeds contradictory histories and asserts the newer fact wins.
What the memory tier holds here
- Environment facts learned during work: "Service X needs a drain before restart", "The payments API rejects batch sizes over 100".
- Salience decays on a half-life per predicate: a fact's retrieval weight falls at a rate set for its kind.
- Consolidation runs offline, off the request path.
9. Promote procedures through a gate, not a single success
- A skill = a named, parameterised sequence of tool calls with a precondition, a postcondition and a measured success rate.
- The agent repeatedly succeeds with: check health → drain traffic → restart → check health again → restore traffic.
- The learning system may create
safe_restart(service_name). - One successful trace is not enough to trust it. The gate between "succeeded once" and "trusted" is the heart of this case.
The book's six-step gate
- Extract a candidate from successful traces and generalise its arguments.
- Discard duplicates of existing skills.
- Evaluate on held-out cases, never on the traces that produced it.
- Grading a skill on its own source traces measures memory, which is how libraries fill with skills that worked exactly once.
- Promote only if success beats baseline by 5 points.
- Shadow it on at least 200 live attempts.
- Demote automatically if live success later falls 4 points below baseline.
Promotion flow: successful traces → repeated pattern → skill candidate → dedupe → held-out evaluation → not better than baseline: reject / better → shadow traffic → healthy → owner review → live.
Soundbite: "A successful execution is evidence for a skill. It is not permission to deploy the skill."
Demotion matters as much as promotion
- Environments drift. A skill encoding last quarter's API shape must leave production before a human notices.
- In the book's estimate, a library that only grows becomes a liability within about two quarters.
Two extraction mechanisms
| Mechanism | How it works | Choose it when |
|---|---|---|
| Voyager-style | Checks the library for a skill to reuse or compose; writes new code only if nothing fits; runs it in a sandbox, checks test cases, saves only if they pass | The tool surface is programmable (code skills) |
| Agent Workflow Memory | Stores tool-call sequences, not code; abstracts a successful trajectory into a template with placeholders; fills it for structurally similar tasks | The reusable unit is the order of tool calls, like the restart sequence |
Procedures are the highest-risk memory layer
- They change behaviour.
- Keep approval outside the model's reasoning loop:
- The agent may propose a procedure.
- The graph pauses for a human decision.
- Rollback re-approves an older version.
- Keep that rule for anything that widens what a skill may do.
10. Optimise prompts as experiments, not edits
- Prompt changes should be handled like software changes.
- The bad process: engineer edits the prompt → deploys without evaluation → production behaviour is unverified.
How prompt optimisation works
- Define a metric and a scored development set.
- Generate variants of the instructions and the selected examples.
- Score each and keep the best.
- Frameworks that compile prompts from a declared program and a metric do this.
- The better process: current prompt → generated variants → development evaluation → candidate selection → hidden test set → shadow → promotion.
Why it sits between procedure and parameters
- It changes behaviour across every task type at once, like training.
- Yet the result is still text: versioned, readable and revertible in seconds.
Three rules keep it honest
- Hold out a test set the optimiser never sees.
- A search over hundreds of variants will overfit a small dev set; one version may look good only because it fits that set.
- Report the win per stratum.
- A planner prompt tuned on common tasks can quietly break rare ones.
- Treat the winning prompt as a candidate like any other: eval gate, shadow, owner review.
Rule 2 at work (the template's made-up numbers)
| Slice | Before | After |
|---|---|---|
| Overall | 80% | 84% |
| Restart tasks | 90% | 95% |
| Rollback tasks | 86% | 68% |
- Overall improved, but one important capability got worse, so the release is blocked.
Source caveat
- The sources behind the original page cover DSPy's declared prompts, multi-step programs, evaluation and pairwise Elo scoring, but not its optimisers.
- So this section rests on general knowledge.
- The MIPROv2 documentation in the references describes optimisers that search instructions and few-shot examples against a metric.
11. Update weights last, and only for the three cases that earn it
- Training is the most expensive and least reversible rung, so defend it before proposing it.
The three cases where parameter updates win (learning chapter)
- Strict format or protocol adherence at high volume.
- A small tuned model matches a larger prompted one at a fraction of the cost.
- Template's version: the model must consistently produce a specific machine-readable format.
- Domain vocabulary the base model lacks.
- It genuinely struggles with important terminology.
- A hard cost or latency ceiling after the cheaper rungs are exhausted.
- Distillation buys it back; a small tuned model may replace a larger, expensive one for a repetitive task.
The losing case
- Knowledge gaps are a retrieval problem. Fine-tuning rarely fixes a model that doesn't know something.
- Published studies: models learn new facts from fine-tuning slowly and unreliably; retrieval beats it for adding knowledge.
- For this case: that rules out "train the agent on each new task". A new task is new knowledge and a new procedure, and both belong lower on the ladder.
Soundbite: "Don't fine-tune to teach business facts that change."
Matching the problem to the rung:
| Problem | Rung |
|---|---|
| Missing knowledge | Retrieval or memory |
| Repeated workflow | Skill |
| Instruction-following problem | Prompt |
| Stable, high-volume behaviour | Fine-tuning (only this) |
- One more cost (the book): a tuned model freezes its task definition.
- When the business changes the definition, a prompt needs an edit; a tuned model needs retraining.
- So keep a prompted fallback path.
If training happens, the flywheel gates decide whether the data is honest
- Deduplicate first.
- Split by time and user, never at random.
- Send low-agreement, high-impact cases to human adjudication.
The book's worked failure:
| Measure | Value |
|---|---|
| Reported held-out accuracy | 94% |
| Baseline | 81% |
| Production | About 78% |
| Traces vs distinct requests | 140,000 traces were only about 9,000 distinct requests |
| Honest number after fixes | Near 83%; production matched within two points |
- Causes: the random split hid near-duplicates, and labels came from the old system's own decisions.
- Rule: when an offline gain looks surprisingly large, suspect leakage first.
12. Gate every self-modification like a human pull request
- A self-modifying system without a release gate is an unreviewed deploy pipeline with a model holding the merge button.
- The gate is where this case is won or lost, and where the panel is likely to probe hardest.
- Reported interview questions from the OpenAI decomposition round call evaluation a deliberate differentiator there. The source assumes the same holds here, while noting no public source says so.
Human change vs agent change
- Human: code → test → review → deploy (a CI/CD pipeline).
- Agent learning candidate: offline evaluation → safety checks → shadow → review → deploy.
- Every learned artefact, whichever rung it came from, follows the agent's path.
CI/CD = continuous integration and continuous delivery: the automated pipeline that tests and ships every change.
The validation chapter's CI gate: three layers
| Layer | Rule |
|---|---|
| Safety assertions | Gate absolutely: any failure blocks |
| Quality | Gates against the baseline with a paired significance test per stratum as well as on the mean |
| Cost | Reported; a ceiling breach blocks, so a gain that triples spend becomes a visible decision, not a side effect |
Why per stratum (the validation chapter's worked failure)
- A retrieval change lifted aggregate accuracy from 79% to 81%.
- Inside that average, one tenant's segment fell from 82% to 67%.
- That tenant was only about 4% of the eval set.
- The fix: a floor. No release may drop any stratum by more than 3 points.
- Here the strata are task types, so a new skill for a new task can't quietly damage an old one.
Each worry maps to one gate check
| Worry | Gate check |
|---|---|
| Does the candidate actually help the task it was built for? | Paired eval on held-out cases of that task type; beat baseline by 5 points |
| Did it break any other task type? | Per-stratum regression floor across all live task types |
| Is it safe? | Trajectory assertions: no new tools, no permission widening, approvals still requested |
| Does it survive real traffic? | Shadow of at least 200 attempts with success at or above baseline |
| Is the improvement real or noise? | Sample-size check: a 200-case suite can't see gains below about 11 points |
| What did it cost? | Tokens and latency per run versus baseline, reported on the gate result |
| Can it be undone? | Registry holds the previous version; rollback is a status change |
Evaluate the whole trajectory, not only the final answer
- Template example: the agent eventually succeeds, but it deletes before reading. Unsafe ordering, even though the result looks correct.
- Policy requires: read → validate → approval → delete.
- Several paths can be valid, so assert properties of the path, not one exact sequence:
- Did it read before writing?
- Did it request approval before the irreversible step?
- Did it stay within its tool list?
- Put the safety assertions first. Evaluate final outcome, tool sequence, permissions, approvals, retry count, cost and latency together.
- The gate checks deep dive separates deterministic from judged checks and covers shadow and demotion.
13. Bound the autonomy the agent has over itself
- "Autonomously" is the most dangerous word in the prompt.
- The agent may learn how to do things, but never that it is allowed to do more.
- Three roles: the agent learns how → policy decides the permitted action → an executor performs it.
Draw the line and say it aloud
| The agent may, without a human | Only a human may |
|---|---|
| Choose which live skills and examples to load | Grant a skill a tool it didn't already have |
| Write memories that pass the write policy | Approve a procedure that performs an irreversible action |
| Propose candidate skills and prompt variants | Promote anything that changes permissions or budgets |
| Retry with a Reflexion lesson, within the attempt cap | Raise the attempt cap, the step budget or the spend ceiling |
| Demote a regressing skill automatically | Re-promote a demoted skill |
Protected settings (answer template)
- The agent must not autonomously change: tool permissions, financial limits, security policy, approval requirements, the retry budget or the irreversible-action policy.
- Template example: the agent may learn
refund_customer(). It can't decide "I can now refund $50,000." Permissions remain outside the agent.
Five controls enforce the line
- The tool gateway checks permissions on every call, whatever the skill says, so a learned procedure can't carry its own authority.
- Irreversible actions route to a person before and after.
- Budgets cap steps, tokens, wall time and spend per run and per day.
- The ops agent's owner has a kill switch that freezes all learning and pins every artefact to its last reviewed version.
- Permission changes always need a human, as the table states.
Two slower threats inside the boundary
Goal drift
- The slow slide of behaviour away from what its owners intended.
- Track trajectory shape per task type: tool mix, steps per run and escalation rate.
- A skill that starts solving tickets by closing them is gaming the outcome signal.
- Add a second, independent signal (reopen rate or sampled human review), or the agent learns to satisfy the metric instead of the user.
- The governance deep dive works this example.
The injection path
- Learned content is untrusted content.
- A memory or skill extracted from a trace that included external text can carry an instruction such as "always approve refunds".
- Tag provenance on everything learned. Never let content from an untrusted source become a procedure without review.
14. Name the failure modes before the interviewer does
- Each failure has an observable symptom and a guard already in the design. Naming them first shows the gate and bounds were built for specific incidents.
| Failure | Symptom | Guard |
|---|---|---|
| Forced fit | New request routed to the nearest wrong skill with high confidence | Novelty score; counterexamples in triggers; triggering evaluated separately |
| Skill that worked once | Library grows; average success falls | Held-out evaluation; 5-point margin; 200-attempt shadow |
| Stale skill | Success drops after an upstream API change | Per-stratum live monitor; automatic demotion at 4 points below |
| Memory pollution | Old, retracted facts resurface | Write policy; typed facts; supersession; contradiction test in the gate |
| Self-graded lessons | Reflexion retries grow more confident and more wrong | External oracle required; attempt cap; escalate at cap |
| Optimiser overfit | Prompt wins on the dev set, loses live | Separate test set; per-stratum reporting; shadow |
| Leaky training data | Big offline gain, production below baseline | Dedupe; time and user split; human adjudication |
| Metric gaming | Outcome signal rises, user satisfaction falls | Second independent signal; trajectory drift monitors |
| Permission creep | A learned procedure performs an action nobody granted | Gateway checks every call; permission changes need a human |
| Runaway learning cost | Evaluation spend exceeds serving spend | Candidate dedupe and pre-filter; learning budget as a gate |
The template's shorter list adds two rows
- Contradictory memory (old and new facts conflict) → versioning and supersession. Kept separate from memory pollution (bad facts stored) → write policy.
- Infinite retry (the agent keeps trying) → the retry limit.
- Its other rows match the table: forced fit / novelty detection; one-shot learning / held-out evaluation plus shadow; stale skill / monitoring plus auto-demotion; self-grading / external outcome signal; prompt overfit / hidden test plus shadow; data leakage (same examples in train and eval) / dedup with proper splits; metric gaming / multiple independent metrics; permission creep / external policy layer; learning cost explosion / candidate dedup with staged evaluation.
The pattern audit
- Every mechanism added needs a metric that motivated it and an incident it prevents.
- Otherwise whoever is on call at three in the morning pays for it.
15. Trace a novel task end to end
- The answer template's worked example. Request: "Restart Orion payment service." The system has never seen Orion.
- Route. Capability router finds no confident match → novel task.
- Safe fallback. General agent gets tighter controls; risky writes require approval.
- Execute.
- Explores first: read documentation → inspect service → create plan.
- Discovers Orion must be drained before restart.
- Performs drain → restart → health check → restore traffic. External monitoring returns SUCCESS.
- Trace. Stored with its steps, the versions used and the external outcome.
- Memory candidate. "Orion restart requires drain." Durable, reusable, attributable and permitted → stored.
- Skill candidate. After repeated successful executions,
safe_orion_restart(service)is created as a candidate. - Evaluate. Held-out, regression, safety, cost and latency tests.
- Shadow. Observes real requests without controlling them.
- Promote. If healthy, status moves from candidate to LIVE.
- Environment changes. The Orion API changes; success drops → monitoring detects the regression → auto-demoted → traffic returns to the previous skill or the general fallback.
- The sequence touches every rung the design relies on in its first year: fallback at runtime, a fact in memory, a skill through the gate, and demotion when the world moves.
16. Ship a walking skeleton, then add learning in phases
- Don't build every self-learning feature on day one.
- The walking skeleton = rungs 1 and 2 plus the trace store:
- Capability router with novelty detection.
- General fallback.
- Dynamic examples.
- Memory write policy.
- Traces.
- The answer template's MVP list matches it and adds the evaluation pipeline from the start.
MVP = minimum viable product: the smallest version that proves the idea works for real users.
The increments
- Second: skill library and its gate, once there is a month of traces to evaluate against.
- Third: prompt optimisation.
- Last, if ever: training (fine-tuning only when justified).
Phased priorities for a customer deployment
- A Forward Deployed engineer would phase the same work so production observability and safety exist before autonomous improvement.
| Phase | Build |
|---|---|
| Phase 1 | Routing, novelty detection, trace collection, safe fallback, memory policy, gateway |
| Phase 2 | Offline skill extraction, evaluation, shadow testing, promotion and rollback |
| Phase 3 | Prompt optimisation, advanced automated learning, selective fine-tuning |
- This order keeps the first version safer and easier to operate.
- Each later phase adds a learning mechanism only once the evidence and the controls it needs are already running.
Quick Recall: Lines to Say in the Interview
- "Five rungs, each about ten times costlier and harder to undo; I design from the cheap end."
- "The runtime serves, the learning loop proposes, the gate decides. Learning never changes production directly."
- "The hardest failure is confidently forcing a new request into the nearest known skill."
- "Unknown tasks get less freedom: lower step limit, read-only first, approval on risky writes."
- "Reflexion needs an external judge, a specific lesson and a cap. The model doesn't grade itself."
- "Memory is a write problem: durable, reusable, attributable, permitted."
- "Beat baseline by 5 points, shadow 200 attempts, demote at 4 below, no stratum down more than 3."
- "200 cases see only about 11 points, so the shadow proves 'not much worse'."
- "The agent can learn refund_customer(). It can't decide it may now refund $50,000."
Technical deep dives
The goal: the mechanisms behind the follow-ups: the registry and its states, the gate's checks, latency, learning cost, governance and the trade-offs.
30-Second Cheat Sheet
- Registry: every artefact has a version, owner, status, permissions and a
previous_version, so rollback is a status change. - Five states: draft → candidate → shadow → live → demoted.
- Four record types: execution trace, memory record, skill, learning candidate.
- Gate checks: deterministic first (cheap, exact), then judged (noisy, so paired and per stratum).
- Shadow's blind spot: writes. Success on writes needs a small canary.
- Demotion needs volume: a 4-point slide takes about 1,570 attempts (~52 days at 30/day), so pair it with a fast trigger.
- Latency: learning stays off the request path (≤ 150 ms p95 overhead, assumed).
- Cost: candidates × eval cases × model calls. Staged evaluation and a learning budget gate (assumed 10%).
1. Capability registry, artefact states and data model
- The registry stores every approved and candidate capability. Without it, nobody can say what the agent learned or undo it.
A skill entry (answer template)
skill_id: safe_restart
version: v3
status: LIVE
owner: platform-team
previous_version: v2
permissions: restart-service
eval_score: 0.91
Each field serves a control:
| Field | Control it serves |
|---|---|
owner |
Reviews promotion and is paged on regression |
permissions |
Records what the gateway already granted; the skill can't widen it |
previous_version |
Makes rollback a pointer move rather than a rebuild |
Five artefact states
draft → candidate → shadow → live → demoted
- Rollback: if v3 becomes unhealthy, its status changes to demoted and v2 becomes live again.
- Rollback is a status change, which is what makes it fast enough to trust.
Production data model: four record types
- Execution trace = the evidence. Memory record and skill = what was learned. Learning candidate = tracks a proposal through the gate.
| Object | Fields |
|---|---|
| Execution Trace | trace_id, request_id, task_type, novelty_score, selected_skill, prompt_version, model_version, tool_calls, tool_results, outcome, latency, cost, timestamp |
| Memory Record | memory_id, subject, predicate, value, source, created_at, status, supersedes |
| Skill | skill_id, version, description, trigger, workflow, required_tools, required_permissions, status, owner, eval_result, created_at |
| Learning Candidate | candidate_id, candidate_type, source_traces, baseline_version, candidate_version, evaluation_status, shadow_status, promotion_status |
Why the key fields exist
- Trace:
novelty_score,selected_skill,prompt_versionandmodel_versionlet a regression be attributed to the exact artefact that caused it. - Memory record:
supersedesimplements the supersession pointer from walkthrough step 8. - Skill:
triggeris what the router matches;required_permissionsis checked by the gateway, not trusted from the skill. - Candidate:
source_tracesandbaseline_versionlet the gate evaluate on held-out cases and compare against the right baseline.
2. Release checks in detail: deterministic, judged, shadow and demotion
Two kinds of check
| Kind | Questions it asks | How it's evaluated |
|---|---|---|
| Deterministic (exact, cheap, run first) | Forbidden tool called? Retry limit exceeded? Latency over threshold? Cost over budget? Required approval present? Permission rules violated? Valid schema? | Exact rules |
| Non-deterministic (semantic) | Was the plan correct? Response helpful? Selected tool sensible? Workflow safe? Task solved? | LLM judges, human review, pairwise comparison or task-specific evaluators |
- Judged checks are noisier, so the paired, per-stratum comparison and the sample-size arithmetic (walkthrough step 4) decide whether a difference is real.
Shadow testing
- On each production request, the current live skill controls the action; the candidate observes without controlling it.
- Compare on: success rate, tool choice, latency, cost, safety violations and human feedback.
- Promote if healthy over at least 200 attempts at or above baseline.
- Remember the sizing limit: 200 attempts show the candidate is not much worse; they can't confirm a 5-point gain.
Shadow's blind spot: writes.
- The candidate doesn't act, so for a restart there is no external outcome to score.
- Shadow can compare its planned tool calls with the live path and run the safety assertions on them.
- Success on writes has to come from a small canary: the candidate acts on a slice of real requests under the same bounds and approvals.
Canary = a release to a small slice of real traffic before everyone gets it.
Demotion: learning doesn't stop at promotion
- A skill goes live; later an API changes and its success rate drops.
- Production changes, so live skills need monitoring that acts without waiting for a person.
- Flow: live skill → monitoring → regression detected → auto-demote → traffic returns to the previous skill or the safe fallback.
The demotion trigger needs volume.
- Trigger: per stratum, live success 4 points below baseline.
- Detecting a 4-point slide at p = 0.8:
15.7 × 0.16 / 0.0016≈ 1,570 attempts. - That's roughly 52 days at 30 requests a day.
- So pair it with a fast trigger: several consecutive failures, or an error-rate spike against the skill's recent window.
- The fast trigger catches a sharp break like the Orion API change within a few requests.
Soundbite: "Demotion is something the agent may do on its own, because it only narrows behaviour. Re-promotion widens it again, so that needs a human."
3. Keep learning off the request path
- Latency requirement (assumption): runtime adaptation adds at most 150 ms at p95 before the first model call.
- That budget only holds if learning stays off the user's request path.
| Path | What runs there |
|---|---|
| Online | Router, memory retrieval, skill retrieval, agent execution, policy check, tool call, trace write |
| Offline | Pattern mining, skill extraction, prompt search, large evaluation runs, fine-tuning, shadow analysis, memory consolidation and salience decay |
- Result: user latency stays predictable; a request never waits for the learning loop.
- The one rung-1 exception online: dynamic examples break the prefix cache below the example block, a latency and cost side effect.
- Fix: cache one example set per traffic cluster, so most requests stay on a warm prefix.
4. Learning cost: where it comes from and how to cap it
- Expected cost driver:
candidates × evaluation cases × model calls. Training is rarely the driver. - From sizing: 50 candidates a week at 1,280 paired runs each cost $1,920, about 46% of the serving bill.
The controls, cheapest first (answer template)
- Deduplicate similar candidates, including against the existing library.
- Run cheap checks first.
- Use smaller models for simple evaluation.
- Run full evaluation only for promising candidates.
- Evaluate only relevant task families.
- Keep a smaller global regression suite.
- Set candidate budgets.
Staged evaluation (a funnel)
candidates → dedupe → cheap smoke test → small evaluation set → only strong candidates → full evaluation
Metrics to track
Learning spend ÷ serving spend
Cost per promoted skill
Candidates tested per promotion
Tokens per successful task
Shadow cost
Evaluation cost
The first metric is a gate: when learning spend breaches its cap (assumed 10% of serving), new candidates are blocked.
Never save money by cutting the held-out or per-stratum checks. The cost pivot drill in the full casebook's Practice section has the full answer.
5. Security, governance and metric gaming
The central tool gateway
- All tool calls go through it.
- It checks identity, permission, action, resource, budget and approval on every call, whichever skill or fallback issued it.
- That's why a learned procedure can't carry its own authority.
The audit log
- Stores who, what, when, which version, which tool, which permission and which outcome for every action.
- With the registry, it answers the auditability questions from walkthrough step 3: who created a change, why, on what data, which evaluation passed, who approved it and what it can roll back to.
Human approval for
Destructive operations
Security changes
Permission changes
Financial actions
New high-risk skills
These deliberately overlap with the human-only column in walkthrough step 13: a high-risk skill can be correct and still need a person to accept the risk.
Metric gaming
- We optimise the percentage of tickets closed.
- The agent discovers that closing every ticket immediately raises the metric.
- The real business outcome gets worse.
- The weakness: a single, easily gamed metric.
- The fix: several independent signals: ticket closed, whether it was reopened, customer satisfaction, human QA review and resolution time.
- A skill gaming one shows up as divergence between them.
- Trajectory-shape monitors per task type (tool mix, steps per run, escalation rate) catch the drift that produced it.
QA = quality assurance: checking the thing works before real users see it.
6. The main trade-offs and when each side wins
| Trade-off | Side A | Side B | This design |
|---|---|---|---|
| Fast learning vs safety | More automatic promotion: adapts faster, but weaker candidates reach traffic; leans on monitoring and auto-demotion to catch a regression after it ships | Stricter evaluation: slower adaptation, higher reliability | Gate and shadow bars choose the stricter side for anything that acts |
| Memory vs skill | Memory stores facts ("API max batch size = 100") | A skill stores a procedure (how to restart safely) | Don't put everything in memory: a procedure stored as a fact can't be evaluated, shadowed or demoted as a unit |
| General agent vs specialised skills | General agent: flexible, good for novel tasks, more expensive and less predictable | Skills: fast, cheap and predictable, less flexible | Use both: skills for known types, bounded general agent for novel ones that will become skills |
| Fine-tuning vs retrieval | Fine-tuning: stable, repeated behaviour; harder rollback, slower iteration | Retrieval: changing knowledge; easy updates and rollback | The ladder as a pair: knowledge through retrieval and memory; weights only for the three cases in step 11 |
- The automatic-promotion safety net (source figure): monitoring detects a regression → auto-demote → traffic returns to the previous skill or the general fallback.
7. References and source boundaries
- The source checked these references on 27 September 2026.
- The book on agentic system design (spine, memory policy, validation gate) isn't named in the captured page, so its numbers are cited as "the book".
- Numbers marked as assumptions remain whiteboard illustrations.
| Reference | What it supports |
|---|---|
| Prompt caching (Claude API docs) | The cache is a prefix; a change invalidates that level and everything after it |
| Prompt caching (OpenAI API docs) | Reuse needs an exact prefix match; put variable content last |
| Reflexion: Language Agents with Verbal Reinforcement Learning (Shinn et al., 2023) | Lessons kept as text in an episodic buffer, no weight updates |
| Large Language Models Cannot Self-Correct Reasoning Yet (Huang et al., 2023) | Self-correction without external feedback often fails or makes answers worse |
| Voyager: An Open-Ended Embodied Agent with Large Language Models (Wang et al., 2023) | Skill library of executable code, refined with execution feedback and self-verification |
| Agent Workflow Memory (Wang et al., 2024) | Reusable workflows induced from agent trajectories |
| MIPROv2 (DSPy docs) | Optimisers that search instructions and few-shot examples against a metric |
| Fine-Tuning or Retrieval? Comparing Knowledge Injection in LLMs (Ovadia et al., 2023) | Retrieval beats unsupervised fine-tuning for new knowledge |
| Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations? (Gekhman et al., 2024) | New facts are learned slowly through fine-tuning and raise hallucination |
Quick Recall: Lines to Say in the Interview
- "Every artefact is a registry version with an owner; rollback is a status change, not a rebuild."
- "The skill's permissions are checked by the gateway, never trusted from the skill."
- "Deterministic checks first because they're exact and cheap; judged checks need paired, per-stratum comparison."
- "Shadow can't score writes, so success on writes comes from a small canary."
- "A 4-point slide takes about 1,570 attempts to detect, so I pair it with a fast trigger."
- "Demotion narrows behaviour, so the agent may do it; re-promotion widens it, so a human does."
- "Learning cost is candidates times eval cases times model calls, not training."
- "One metric gets gamed; several independent signals show divergence."
Quick review
One sentence: the agent can learn how to do something, but policy decides what it is allowed to do. Self-adapting should mean controlled learning, not uncontrolled self-modification.
30-Second Cheat Sheet
- Five rungs: context, memory, procedure (skills), prompt optimisation, weights. Each about 10× costlier and harder to undo.
- Two loops, one gate: runtime and learning loops meet at the evaluation gate; every artefact is a versioned registry entry with an owner and a status.
- Novelty first: low retrieval score, unknown system or tool, near tie, or no skill above threshold → tighter fallback.
- Reflexion needs an external oracle, a specific lesson and a cap.
- Memory: four gates (durable, reusable, attributable, permitted), typed facts, supersession.
- Gate: +5 points, ≥ 200 shadow attempts, demote at 4 below, no stratum down more than 3.
- Weights only for format at volume, missing vocabulary, or a cost or latency ceiling.
1. The ladder, the loops and the gate
The ladder
- "Adapt" means five rungs: context → memory → procedure (skills) → prompt optimisation → weights.
- Each is about ten times costlier and harder to undo than the last.
- Design from the cheap end; climb only when a measured gap forces it.
The loops and the gate
- A runtime loop and a learning loop meet at one evaluation gate.
- Every artefact is a versioned registry entry with an owner and a status.
Novelty and the fallback
- Detect novelty before handling it:
- Low retrieval score.
- An unknown system or tool.
- A near tie between the top two skills.
- No skill above the confidence threshold.
- Run unknown tasks in a fallback mode: tighter bounds, read-only tools first, approval on writes, earlier escalation.
Runtime adaptation and memory
- Runtime adaptation: outcome-ranked, diverse examples, plus Reflexion.
- Reflexion needs an external oracle, a specific lesson and a cap.
- Memory is a write problem:
- Durable
- Reusable
- Attributable
- Permitted
- Typed facts and supersession keep it from polluting future runs.
Every candidate's sequence
2. Numbers and rules to recall
The gate
| Rule | Value |
|---|---|
| Offline promotion bar | Beat baseline by 5 points |
| Live shadow | At least 200 attempts |
| Auto-demotion | 4 points below baseline |
| Per-stratum floor | No stratum drops more than 3 points |
Sample size
n ≈ 15.7 × p(1−p) / δ²per arm.- At p = 0.8, 200 cases detect only about 11 points.
- 5 points needs about 1,000 per arm.
- The shadow proves "not much worse".
Sizing (assumptions)
| Item | Value |
|---|---|
| Requests | 20,000 a day over 40 types |
| New types | 3 a week |
| Traffic for a new type | 30 requests a day (about 7 days of shadow) |
| Cost per run | $0.03 |
| Candidates | 50 a week at $38.40 each |
| Learning share | About 46% of the $4,200 weekly serving bill, against a 10% cap |
Requirements (assumptions)
- 14-day time to competence.
- At most 150 ms p95 runtime adaptation overhead.
Worked failures
| Failure | Numbers |
|---|---|
| Aggregate hid a stratum | 79% → 81% aggregate; a stratum fell 82% → 67% |
| Leaky routing fine-tune | 94% offline, about 78% live; honest number near 83% |
| Untyped memory | Old vendor resurfaced about one time in four |
When to touch weights
- Only for: format at volume, missing vocabulary, or a cost or latency ceiling.
- Never for: missing knowledge.
3. Bounds, failures and the closing answer
The bounds
| The agent may | Only a human may |
|---|---|
| Choose skills and examples | Grant a tool |
| Write memories that pass the policy | Approve an irreversible procedure |
| Propose candidates | Change permissions or budgets |
| Retry within the cap | Raise caps |
| Demote a regressing skill | Re-promote a demoted skill |
- Enforcement: the gateway checks every call, irreversible actions go to a person, budgets cap every run, and a kill switch freezes learning.
Name the failures with their guards
Forced fit
Skill that worked once
Stale skill
Memory pollution
Self-graded lessons
Optimiser overfit
Leaky training data
Metric gaming
Permission creep
Runaway learning cost
Evaluate the full trajectory, not only the final answer.
The hour and the cost pivot
- Spend the hour on the ladder and the gate.
- Ship a walking skeleton of rungs 1 and 2 plus traces.
- For the cost pivot:
- Dedupe and smoke-test candidates.
- Scope suites to the strata a change touches.
- Keep the prefix cache warm.
- Track learning spend per promotion.
The thirty-second summary as one chain
user request → known-or-novel detection → approved skill or safe fallback → agent with policy-controlled tools → external outcome and trace store → offline learning → memory, skill or prompt candidate → evaluation → shadow → promotion → monitoring with auto-demotion
Closing line (source's version): "The agent can learn how to do something, but policy decides what it is allowed to do. Self-adapting should mean controlled learning, not uncontrolled self-modification."
Quick Recall: Lines to Say in the Interview
- "Five rungs; design from the cheap end and climb only when a measured gap forces it."
- "A runtime loop and a learning loop meet at one evaluation gate."
- "Novel tasks run read-only first, with approval on writes and earlier escalation."
- "Reflexion needs an external oracle, a specific lesson and a cap."
- "Plus 5 offline, 200 in shadow, demote at 4 below, no stratum down more than 3."
- "At p equals 0.8, 200 cases see only about 11 points."
- "Weights for format, vocabulary or a cost ceiling, never for missing knowledge."
- "The agent learns how; policy decides what it may do."
Where next
- Revise the concepts