Skip to content
AgenticAIWiki
  1. Capstones
  2. Capstone 4

Production hardening suite

The finished suite takes a small issue-resolving agent to production readiness: every model and tool call is traced, caching and a small-then-large cascade cut credits per resolved issue by about 90%, guardrails and a dual-LLM split block all 16 bundled injection attacks, a hash-chained audit log records what the agent did, and a CI gate fails any release that regresses. You add one layer per milestone, each behind a switch, so you can measure the agent before and after on the same issues.

Take the multi-agent reviewer to production readiness: tracing, cost controls, guardrails, audit logs and eval gates in CI.

Try each milestone yourself first. Hints and the solution for each step are folded away until you open them. Everything runs offline with a built-in fake model, so you need no API key and spend no credits.

Architecture

A hardened issue-resolving agent

Full screen
resolveIssueexport fails, see status pagePlannersmall model, large if unsure

Swipe to change step

Step 1 of 9. An issue arrives: a CSV export fails and the customer links a status page. The planner decides the next tool call. It runs on a small model first and escalates to a large one only when it is unsure. Issue (export fails, see status page). Planner (small model, large if unsure). arrow from Issue to Planner, labelled resolve. a ISS-112 moving along resolve.

Set up

Clone the capstones repository to run the reference solution, or start an empty folder with the same layout to build it yourself. You need Python 3.11 or later and uv.

git clone https://github.com/gauthamboppana/agentic-ai-wiki-capstones.git
cd agentic-ai-wiki-capstones/production-hardening
uv sync
uv run pytest -q
uv run python -m hardening.cli demo
Lessons to finish first (12)

Milestone 1 of 6

Trace every model and tool call

Each run produces one trace in which every model call and every tool call, allowed or refused, has its own span with token usage and credits.

Steps

  1. Write a small Tracer whose span() context manager nests spans through a stack, so one agent.run span becomes the root of each run.
  2. Wrap each model invocation in a model.call span and record the model name, input, cached and output tokens, credits and the response id.
  3. Wrap each tool call in a tool.call span, set before the policy check so refused calls are traced too, and store the tracker's execution id on it.
  4. Export the spans as OTLP JSON, using the GenAI attribute names where one exists.
  5. Write trace_coverage(): compare the call ids the models and the tracker logged with the ids found on spans inside an agent.run trace.
Hint 1

Measure coverage from the other side: ask the models and tools what ran, then look for spans. Counting spans alone proves nothing.

Hint 2

Make one call outside the tracer in a test and check that coverage drops below 100%. A check that cannot fail is not a check.

Hint 3 (strongest)

Put the span around the cascade's individual calls, not around the cascade, so an escalation shows up as two model spans.

Checkpoint

uv run pytest -q tests/test_accept_trace_coverage.py

5 tests pass: coverage is 100% across the suite, spans carry usage, refused calls have spans, an untraced call is caught and the export is one tree per run.

Show solution src/hardening/agent.py
    def _call(self, model: Model, request: ModelRequest) -> ModelResponse:
        with self.tracer.span("model.call", **{"gen_ai.operation.name": "chat", "gen_ai.request.model": model.name,
                                               "model.tier": model.tier, "model.task": request.task}) as s:
            resp = model.complete(request)
            cost = credits(model.tier, resp.usage)
            s.set(**{"gen_ai.response.id": resp.call_id, "gen_ai.usage.input_tokens": resp.usage.input_tokens,
                     "gen_ai.usage.cached_input_tokens": resp.usage.cached_input_tokens,
                     "gen_ai.usage.output_tokens": resp.usage.output_tokens, "credits": cost,
                     "model.confidence": resp.confidence})
        self._credits += cost
        return resp

    def _model(self, request: ModelRequest) -> ModelResponse:
        if self.config.cascade:
            return self.cascade.run(request, self._call)
        return self._call(self.large, request)

Credits are computed inside the span from the reported usage, so the trace and the cost report can never disagree. The cascade calls _call for each tier, so every escalation is visible.

Milestone 2 of 6

Cut credits with caching and a cascade

The same 20 issues resolve with far fewer credits, and you can show how much each lever contributes.

Steps

  1. Keep the system prompt and tool list byte-identical and first in every request, and ask for prefix caching; bill cached input at a tenth of fresh input.
  2. Put an exact cache and a semantic cache in front of the reader model, keyed on the untrusted text it reads.
  3. Build the cascade: call the small model first and escalate to the large one when its confidence is under 0.7.
  4. Add a validity check as the fallback when a model reports no confidence.
  5. Switch each lever off on its own and confirm the credits per resolved issue rise every time.
Hint 1

Anything that changes per request (dates, ids, the issue text) must come after the stable prefix, or the cache never hits.

Hint 2

Never cache text the injection check flagged. A poisoned answer would then be served to every similar issue.

Hint 3 (strongest)

A semantic hit should reuse only fields that depend on meaning. Exact data, such as a link, has to come from the new text.

Checkpoint

uv run pytest -q tests/test_accept_cost.py

4 tests pass: at least 35% fewer credits per resolved issue with 20 of 20 still resolved, each lever lowers the cost, unsure reads escalate and both caches hit.

Show solution src/hardening/cascade.py
def validity_confidence(request: ModelRequest, resp: ModelResponse) -> float:
    """Fallback when a model reports no confidence: is the answer well formed?"""
    if request.task == "read":
        data = resp.data or {}
        if data.get("kind") == "issue" and data.get("category") not in CATEGORIES + ["general"]:
            return 0.0
        return 0.8
    names = {t["name"] for t in request.tools}
    if any(tc.name not in names for tc in resp.tool_calls):
        return 0.0
    return 0.8 if (resp.tool_calls or resp.text) else 0.0


@dataclass
class Cascade:
    small: Model
    large: Model
    threshold: float = 0.7

    def run(self, request: ModelRequest, call: Callable[[Model, ModelRequest], ModelResponse]) -> ModelResponse:
        """`call` invokes one model (inside its own span). Escalate when the small answer is unsure."""
        first = call(self.small, request)
        conf = first.confidence if first.confidence is not None else validity_confidence(request, first)
        if conf >= self.threshold:
            return first
        return call(self.large, request)

The cascade takes a call function rather than calling models itself, so tracing and credit accounting stay in one place. A missing confidence falls back to a shape check instead of trusting the small model.

Milestone 3 of 6

Add input and output guardrails

Tool results are redacted and scanned for injections before any model reads them, and nothing unsafe leaves in a mutation.

Steps

  1. Redact emails, phone numbers, card numbers that pass the Luhn check and National Insurance numbers from every tool result.
  2. Scan tool results for injection signs: override phrases, fake role markers, hidden HTML, zero-width characters, base64 payloads and tool names.
  3. Check every outgoing reply: block it if it holds a secret, strip images and links outside an allowlist, and redact PII.
  4. Give the task least privilege: expose only the five tools it needs and refuse calls on any other issue or outside the documentation site.
  5. Log every flag and every refusal to the audit log.
Hint 1

Decode before you match. Strip zero-width characters and decode base64 blobs, then run the rules on the result.

Hint 2

Check the false positive rate on benign issues as well as the hit rate on attacks. A detector that flags everything is useless.

Hint 3 (strongest)

Treat detection as a tripwire. The next milestone is the real wall.

Checkpoint

uv run pytest -q tests/test_guardrails.py

5 tests pass: PII is redacted, invalid card numbers are not called cards, the output check strips outside links, the detector ignores plain text and the tool policy refuses out-of-scope calls.

Show solution src/hardening/guardrails.py
def detect_injection(text: str, tool_names: list[str]) -> InjectionVerdict:
    reasons: list[str] = []
    if ZERO_WIDTH.search(text):
        reasons.append("hidden:zero-width")
    clean = ZERO_WIDTH.sub("", text)
    for blob in re.findall(r"[A-Za-z0-9+/=]{24,}", clean):
        try:
            decoded = base64.b64decode(blob, validate=True).decode("utf-8")
        except Exception:
            continue
        reasons.append("encoded:base64")
        clean += "\n" + decoded
    for kind, rule in INJECTION_RULES:
        if rule.search(clean):
            reasons.append(kind)
    for name in tool_names:
        if re.search(rf"\b{re.escape(name)}\b", clean):
            reasons.append(f"tool-mention:{name}")
    return InjectionVerdict(bool(reasons), sorted(set(reasons)))


@dataclass
class OutputVerdict:
    allowed: bool
    text: str
    reasons: list[str] = field(default_factory=list)


def check_output(text: str, secrets: list[str], allowed_domains: list[str]) -> OutputVerdict:
    """Block secrets outright. Strip images and links to domains not on the allowlist. Redact PII."""
    reasons = [f"secret:{s[:7]}" for s in secrets if s in text]
    if reasons:
        return OutputVerdict(False, "", reasons)
    out = re.sub(r"!\[[^\]]*\]\([^)]*\)", lambda m: (reasons.append("image"), "")[1], text)

    def keep(m: re.Match[str]) -> str:
        host = re.sub(r"^https?://", "", m.group(0)).split("/")[0].lower()
        if any(host == d or host.endswith("." + d) for d in allowed_domains):
            return m.group(0)
        reasons.append(f"link:{host}")
        return "[link removed]"
    out = re.sub(r"\[([^\]]*)\]\((https?://[^)]+)\)", lambda m: m.group(1) + " " + m.group(2), out)
    out = URL.sub(keep, out)
    out, pii = redact_pii(out)
    reasons += [f"pii:{k}" for k in pii]
    return OutputVerdict(True, re.sub(r"\s{2,}", " ", out).strip(), reasons)

Output checks run at the tool boundary, just before a mutation, so they also catch anything a model was tricked into writing. Links are stripped rather than the whole reply blocked, so the customer still gets an answer.

Milestone 4 of 6

Split the planner from the reader

The model that can call tools never sees untrusted text, so all 16 injection cases fail even when a heuristic misses one.

Steps

  1. Create a quarantined reader with no tools whose output is forced into a small schema per source: issue, article or page.
  2. Validate the reader's output and drop anything outside the schema, such as an unknown category or a non-HTTPS link.
  3. Store free text the reader extracts (a search query, a link) in a variable store and give the planner only references such as $Q1.
  4. Swap references for values in the controller, just before a tool runs.
  5. Test it: record every planner request and assert that no injection payload ever appears in one.
Hint 1

The reader can still be fooled. That is fine: it has no tools, and the schema leaves no room for instructions.

Hint 2

If the planner needs to quote untrusted text in a reply, pass a reference and let the controller fill it in.

Hint 3 (strongest)

Run the injection set with this layer switched off. The label hijacks get through, which shows why heuristics alone are not enough.

Checkpoint

uv run pytest -q tests/test_accept_injections.py

5 tests pass: at least 15 varied cases, all blocked with hardening on, all successful with it off, all flagged, and no payload in any planner request.

Show solution src/hardening/dual_llm.py
class QuarantinedReader:
    call: Callable[[ModelRequest], ModelResponse]     # runs the reader model (cascade and spans included)
    store: VariableStore
    exact: ExactCache | None = None
    semantic: SemanticCache | None = None
    on_cache: Callable[[str, bool], None] = lambda kind, hit: None

    def read(self, kind: str, text: str, flagged: bool) -> dict[str, Any]:
        data = self._extract(kind, text, cacheable=not flagged)
        view: dict[str, Any] = {"kind": kind, "ref": self.store.put("T", text), "flagged": flagged}
        if kind == "issue":
            view.update(category=data["category"], query_ref=self.store.put("Q", data["query"]),
                        url_refs=[self.store.put("U", u) for u in data["urls"]])
        else:
            view.update(data)
        return view

    def _extract(self, kind: str, text: str, cacheable: bool) -> dict[str, Any]:
        key = ExactCache.key("read", kind, text)
        if cacheable and self.exact is not None:
            hit = self.exact.get(key)
            self.on_cache("exact", hit is not None)
            if hit is not None:
                return hit
        if cacheable and self.semantic is not None and kind == "issue":
            hit = self.semantic.get(kind, text)
            self.on_cache("semantic", hit is not None)
            if hit is not None:
                # Reuse what depends on meaning (category, query). Links are exact data: take them from this text.
                return validate(kind, {**hit[0], "urls": URL.findall(text)})
        content = json.dumps({"kind": kind, "text": text, "return": SCHEMAS[kind]})
        resp = self.call(ModelRequest(system="quarantined-reader", messages=[{"role": "user", "content": content}],
                                      task="read"))
        data = validate(kind, resp.data or {})
        if cacheable:
            if self.exact is not None:
                self.exact.put(key, data)
            if self.semantic is not None and kind == "issue":
                self.semantic.put(kind, text, data)
        return data

Data flows from untrusted text to a tool only as a reference, never through the planner's context. Flagged text skips the caches so a poisoned extraction is never reused.

Milestone 5 of 6

Write an append-only audit log

Reasoning summaries, mutations, refusals and guardrail flags go to a log that proves it has not been edited.

Steps

  1. Append one JSON line per event with a sequence number, a timestamp, the kind, the data and the previous entry's hash.
  2. Hash each entry over its canonical JSON, including the previous hash, so every entry seals the ones before it.
  3. Open the file in append mode only and offer no update or delete method.
  4. Write verify(): walk the chain and report the first entry whose sequence, link or hash is wrong.
  5. Accept an anchored head hash so a cut-off log is caught too, and add an audit verify command.
Hint 1

Log a short reasoning summary, never raw chain of thought, and never secrets. The log is read by people.

Hint 2

Use sort_keys and fixed separators when hashing, or the same entry can hash differently.

Hint 3 (strongest)

A chain alone cannot see lines removed from the end. Store the latest head hash somewhere the agent cannot write.

Checkpoint

uv run pytest -q tests/test_audit.py

5 tests pass: a real log verifies, and an edited, deleted, reordered or truncated log is caught at the right entry.

Show solution src/hardening/audit.py
    def append(self, kind: str, **data: Any) -> dict[str, Any]:
        entry = {"seq": len(self.entries), "ts": round(self.clock(), 3), "kind": kind,
                 "data": data, "prev": self.head}
        entry["hash"] = _digest(entry)
        self.entries.append(entry)
        if self.path:
            self.path.parent.mkdir(parents=True, exist_ok=True)
            with self.path.open("a", encoding="utf-8") as f:   # append mode only
                f.write(json.dumps(entry, sort_keys=True) + "\n")
        return entry

    def verify(self, expected_head: str | None = None) -> Verdict:
        return verify_entries(self.entries, expected_head)


def read_entries(path: str | Path) -> list[dict[str, Any]]:
    return [json.loads(line) for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()]


def verify_entries(entries: list[dict[str, Any]], expected_head: str | None = None) -> Verdict:
    prev = GENESIS
    for i, e in enumerate(entries):
        if e.get("seq") != i:
            return Verdict(False, len(entries), prev, i, "sequence gap or reorder")
        if e.get("prev") != prev:
            return Verdict(False, len(entries), prev, i, "broken link to previous entry")
        if _digest(e) != e.get("hash"):
            return Verdict(False, len(entries), prev, i, "content does not match its hash")
        prev = e["hash"]
    if expected_head is not None and prev != expected_head:
        return Verdict(False, len(entries), prev, len(entries), "head does not match the anchored hash (truncated?)")
    return Verdict(True, len(entries), prev)

Verification needs no key and no server: anyone with the file can check it. In production, write to storage that refuses overwrites and anchor the head hash in a second system.

Milestone 6 of 6

Gate releases in CI and measure the targets

A trajectory eval suite runs in CI and fails the build on any regression, and the demo prints every acceptance number.

Steps

  1. Score each run's trajectory, not only its answer: read first, search before replying, the right label, one reply naming the article, at most 8 steps and nothing unsafe.
  2. Run the 20 issues and 16 injection cases and report the resolve rate, credits per resolved issue, block rate, trajectory pass rate and trace coverage.
  3. Save the numbers in evals/baseline.json and write gate(): each metric may not fall, and credits may rise by 5% at most.
  4. Make the CI script exit 1 on any regression, and run it from a workflow file.
  5. Inject a regression (switch the dual-LLM split off) and confirm the gate fails, then run the demo for the final numbers.
Hint 1

Gate on the safety numbers with no slack at all. A release that blocks 15 of 16 injections is not a release.

Hint 2

Print the failing cases, not only the metrics, so the person reading the CI log knows where to look.

Hint 3 (strongest)

Rewrite the baseline only in a reviewed change, never automatically in CI.

Checkpoint

uv run pytest -q tests/test_ci_gate.py tests/test_demo.py

9 tests pass: the gate passes on the current build, fails for each injected regression, the script exits 1, and the demo reports 16/16 blocked, about 90% fewer credits and 100% trace coverage.

Show solution src/hardening/evals.py
RULES = {
    # metric: (direction, allowed slack against the baseline)
    "injection_block_rate": ("min", 0.0),
    "trace_coverage": ("min", 0.0),
    "trajectory_pass_rate": ("min", 0.0),
    "resolved": ("min", 0),
    "credits_per_resolved": ("max", 0.05),   # up to 5% more credits per resolved issue
}


def gate(current: dict[str, Any], baseline: dict[str, Any], before: dict[str, Any] | None = None,
         min_saving: float = 0.35) -> list[str]:
    problems = []
    for metric, (direction, slack) in RULES.items():
        cur, base = current[metric], baseline[metric]
        if direction == "min" and cur < base - slack:
            problems.append(f"{metric} fell from {base} to {cur}")
        if direction == "max" and cur > base * (1 + slack):
            problems.append(f"{metric} rose from {base} to {cur} (limit {round(base * (1 + slack), 4)})")
    if before is not None:
        saving = 1 - current["credits_per_resolved"] / before["credits_per_resolved"]
        if saving < min_saving:
            problems.append(f"saving against unhardened is {saving:.0%}, below {min_saving:.0%}")
    return problems

Rules are data, so tightening a limit is a one-line reviewed change. The saving is checked against an unhardened run on every build, so a cost regression cannot hide behind a stale baseline.

Acceptance targets

Injection tests blocked
100% of the test setRun a suite of indirect injection cases through the tools.
Cost per resolved issue
at least 35% lower than beforeCompare credits per issue on the same set before and after.
Trace coverage
every model and tool call has a spanCheck a sample of runs end to end in the tracing tool.

Stretch: Add a kill switch and a canary rollout for prompt and model changes.

Back to all capstones