A field guide to 64 real, verified patterns for designing, securing, and shipping production AI agents — in Python and TypeScript, with every claim checked by actually running the code.
The end result of these lessons is a production-ready agent called Eunomia. We named it for the decision-first Jev pattern it applies: choose a typed route with explicit confidence before policy and tool execution, then escalate safely when confidence is low.
64 lessons2 languages, side by side10 parts1 capstone: Eunomia
Front Matter
How to Read This Book
Each lesson follows the same shape: a plain-English problem, the jargon you need (explained in parentheses the first time it appears), a dark-themed diagram, a short code example in both Python and TypeScript, one honest real-world finding (including the occasional real bug), and a direct tie-in to the capstone product, Eunomia. Parts I–IX build 64 individual patterns; Part X assembles them into one production-shaped architecture. Every code block has a Copy button for fast local experimentation.
How to read the examples in this part: each lesson uses the same simple scenario so you can focus on one new idea at a time.
Input: a job-market query, for example "What is demand for LangGraph roles right now?"
Shared context: a skill name extracted from that query, such as langgraph
Goal: produce a reliable output your code can use (a checked object, a real tool result, a routed branch, or an evidence-based answer)
So when you see names like evaluate_demand_node or route_by_priority, they are steps in that same scenario: decide if the extracted skill is high demand, then route to the right next step.
Part I
Foundations of an Agent with Checked Data
Before an AI agent (software that lets a model use instructions, data, and tools to complete a task) can be trusted with real work, it needs replies a program can read, access to current facts, incremental delivery, evidence from private documents, and routing for multi-step decisions. This part builds those five foundations in Python and TypeScript and exercises each one with running examples.
Two problem domains run through this part:
Domain A — Skill Reporter (simple baseline): input is a job-market query. Goal is to extract a skill, assess demand, and produce structured output your code can trust.
Domain B — Fintech Service Agent (higher-risk): input is a customer question about accounts, product rules, or simulation. Goal is to route safely, ground policy answers in evidence, and enforce consent/risk checks before simulations.
How these lessons interlink: Lesson 1 defines checked output contracts, Lesson 2 adds fresh tool data, Lesson 3 adds live delivery, Lesson 4 adds evidence grounding (RAG), and Lesson 5 adds graph routing that composes those earlier pieces.
Runnable-example rule for this part: each snippet should include all imports it uses, and every variable should be introduced before first use.
Lesson 1
Agent Foundations with Checked Types
The problem: Eunomia and Skill Reporter cannot operate reliably if model output is just free-form prose. Downstream code needs typed fields, not guesses from paragraphs. Without fixed output structure, both domains risk mis-parsing critical values and making wrong decisions.
The fix is type-safe data (checked so values have the kinds the code expects): tell the AI which fields (named values in a data object) to return and what kind each one is, using a schema (a machine-checked description such as "field X is text, field Y is a whole number from 1 to 10"). In Python this is built with Pydantic (a Python data-validation library); in TypeScript, with Zod (a TypeScript data-validation library). A tool validates each answer against that schema before your own code sees it and can retry when an attempt does not fit. This checks structure and ranges, not whether the AI's claims are factually correct.
PLAIN QUESTION → AI DRAFTS A REPLY → SCHEMA VALIDATES REQUIRED FIELDS (retry if it fails) → YOUR CODE READS CHECKED VALUES
Here's what that looks like in Python, using pydantic_ai: a BaseModel (Pydantic's building block for defining a validated data model) called MarketInsight with three required fields, and an Agent told to produce values that pass those checks.
import asyncio
from pydantic import BaseModel, Field
from pydantic_ai import Agent
class MarketInsight(BaseModel):
skill_name: str = Field(description="The exact name of the technical skill identified.")
demand_frequency: int = Field(ge=1, le=10, description="Frequency level found in text from 1 (low) to 10 (high).")
justification: str = Field(description="A single clear sentence explaining why this skill is needed.")
market_agent = Agent(
"openai:gpt-4o",
output_type=MarketInsight,
system_prompt="Extract one skill and rate demand from 1 to 10.",
)
sample_job = "Hiring an AI engineer with strong LangGraph and Python experience."
async def main() -> None:
result = await market_agent.run(sample_job)
data: MarketInsight = result.output
print(data.model_dump())
if __name__ == "__main__":
asyncio.run(main())
A real finding worth knowing: field descriptions are not just comments for other developers — they are sent to the AI as part of its instructions and guide what it writes. Clear descriptions reduce ambiguity, while the schema performs the actual validation.
The TypeScript equivalent swaps Pydantic for Zod and pydantic_ai for the Vercel AI SDK (a popular TypeScript library for generating text, calling tools, and streaming replies across model providers), but the idea is identical: define the schema once, hand it to the model-calling function, and validate the declared fields and constraints. These default object schemas do not promise to reject every undeclared extra property; configure strict rejection separately if that matters.
import { generateObject } from "ai"
import { openai } from "@ai-sdk/openai"
import { z } from "zod"
const MarketInsight = z.object({
skillName: z.string().describe("The exact name of the technical skill identified."),
demandFrequency: z.number().int().min(1).max(10).describe("Frequency level, 1 (low) to 10 (high)."),
justification: z.string().describe("A single clear sentence explaining why this skill is needed."),
})
const sampleJob = "Hiring an AI engineer with strong LangGraph and Python experience."
async function main(): Promise<void> {
const { object: data } = await generateObject({
model: openai("gpt-4o"),
schema: MarketInsight,
prompt: sampleJob,
})
console.log(data)
}
main().catch(console.error)
In the capstone: the account facts Eunomia uses — balance, interest rate, maturity date — cross typed, validated capability boundaries before a template or the model turns them into customer-facing wording. The validation protects the data boundary; separate checks (Part X's verifier and quality suite) are still needed for the final prose.
Lesson 2
Fresh Request Data & Tool Calling
The problem: Eunomia and Skill Reporter both need current system facts, not only model memory. Training data can be stale, and prompt text alone cannot fetch live account or reporting state. Without explicit tools, both domains answer confidently with outdated or missing data.
Baking a live number straight into the AI's setup doesn't work either — the moment you have more than one user, or the number changes between requests, a hardcoded value (one written directly into the program) is wrong. The fix is two matched pieces: a dependency (fresh data or a service the agent needs) supplied for each request through dependency injection (providing those needs from the outside instead of making the agent fetch global data itself), and a tool call (a function the AI can decide to run mid-answer instead of only replying with text) that reads from that bundle.
LIVE DATA BUNDLE INJECTED → AGENT DECIDES IT NEEDS A FACT → CALLS A TOOL → TOOL READS THE BUNDLE → A BOUNDED FOLLOW-UP STEP CAN WORD THE RESULT
In Python, this is deps_type plus a decorated function (a function registered by placing @agent.tool above it):
import asyncio
from dataclasses import dataclass
from pydantic import BaseModel
from pydantic_ai import Agent, RunContext
@dataclass
class DatabaseDeps:
user_id: str
skill_database: dict[str, int]
class TrendAssessment(BaseModel):
skill_name: str
live_count: int
summary: str
trend_agent = Agent(
"openai:gpt-4o",
deps_type=DatabaseDeps,
output_type=TrendAssessment,
system_prompt="Use the tool to get the live count before answering.",
)
@trend_agent.tool
async def fetch_live_skill_count(ctx: RunContext[DatabaseDeps], skill_name: str) -> int:
return ctx.deps.skill_database.get(skill_name.lower().strip(), 0)
mock_deps = DatabaseDeps(
user_id="demo-user",
skill_database={"langgraph": 142, "pydantic": 118, "llamaindex": 96},
)
prompt = "What is live demand for LangGraph?"
async def main() -> None:
result = await trend_agent.run(prompt, deps=mock_deps)
print(result.output.model_dump())
if __name__ == "__main__":
asyncio.run(main())
import { generateText, stepCountIs, tool } from "ai"
import { openai } from "@ai-sdk/openai"
import { z } from "zod"
interface DatabaseDeps {
userId: string
skillDatabase: Record<string, number>
}
const SkillNameSchema = z.object({ skillName: z.string() })
const deps: DatabaseDeps = {
userId: "demo-user",
skillDatabase: { langgraph: 142, pydantic: 118, llamaindex: 96 },
}
const prompt = "What is live demand for LangGraph?"
async function fetchLiveSkillCount(deps: DatabaseDeps, skillName: string): Promise<number> {
return deps.skillDatabase[skillName.toLowerCase().trim()] ?? 0
}
async function main(): Promise<void> {
const result = await generateText({
model: openai("gpt-4o"),
tools: {
fetchLiveSkillCount: tool({
description: "Look up the current count for a skill.",
inputSchema: SkillNameSchema,
execute: (args) => fetchLiveSkillCount(deps, args.skillName),
}),
},
stopWhen: stepCountIs(3),
prompt,
})
console.log(result.text)
}
main().catch(console.error)
A real finding worth knowing: the Python dataclass gives constructor structure and the TypeScript interface gives compile-time field checks, but neither is a strict runtime schema. If request data comes from an external boundary, validate it there; otherwise a missing lookup can still collapse to the examples' default value of zero.
In the capstone: this is how Eunomia gets a real customer's balance — the service calls its readSnapshot capability, whose scope is injected from the verified token for the authenticated customer only, so the actual numbers come from the account store, never from a value typed into a prompt by a developer.
Lesson 3
Streaming Replies / A Live-Typing Chat Page
The problem: Eunomia and Skill Reporter can generate valid answers slowly enough to appear broken. If users see no progress while work is running, trust drops and retries increase. Both domains need streaming and explicit progress state, not silent waits.
The fix is streaming (sending a reply piece by piece as it is generated instead of waiting for the whole response). In a browser, the HTTP response body is exposed to JavaScript as a ReadableStream (a Web API for consuming streamed data), so the user sees chunks (pieces delivered by the stream) arrive like live typing in a modern chat interface. Tool arguments can still be type-checked and schema-validated before execution; this example does not add runtime validation for the tool's returned value.
BROWSER REQUESTS → HTTP RESPONSE BODY STREAMS → TEXT ARRIVES IN CHUNKS WHILE TOOL ARGUMENTS REMAIN TYPED AND VALIDATED
The way to actually prove a reply is streaming — rather than one big blocking response dressed up to look streamed — is to measure it directly: count the chunks and time the gap between the first one arriving and the whole thing finishing. The Python example observes model-output deltas in a terminal; the TypeScript example observes stream parts that an HTTP handler can pass to a browser. They test the same incremental-generation idea at different layers.
import asyncio
import time
from pydantic_ai import Agent
trend_agent = Agent("openai:gpt-4o", system_prompt="Answer in plain English.")
prompt = "Explain in two short sentences why liquidity buffers matter."
async def main() -> None:
chunk_count = 0
started = time.perf_counter()
first_chunk_ms = None
async with trend_agent.run_stream(prompt) as result:
async for chunk in result.stream_text(delta=True):
if chunk:
chunk_count += 1
if first_chunk_ms is None:
first_chunk_ms = (time.perf_counter() - started) * 1000
total_ms = (time.perf_counter() - started) * 1000
print(f"chunks={chunk_count}, first_chunk_ms={first_chunk_ms:.1f}, total_ms={total_ms:.1f}")
if __name__ == "__main__":
asyncio.run(main())
import { streamText } from "ai"
import { openai } from "@ai-sdk/openai"
async function main(): Promise<void> {
const started = Date.now()
let chunkCount = 0
let firstChunkMs: number | null = null
const result = streamText({
model: openai("gpt-4o"),
prompt: "Explain in two short sentences why liquidity buffers matter.",
})
for await (const part of result.fullStream) {
if (part.type === "text-delta" && part.textDelta.length > 0) {
chunkCount += 1
if (firstChunkMs === null) firstChunkMs = Date.now() - started
}
}
const totalMs = Date.now() - started
console.log({ chunkCount, firstChunkMs, totalMs })
}
main().catch(console.error)
A real finding worth knowing: a terse, purely numeric question can produce a reply with zero narrated text chunks — the model goes straight to a tool call and stops, because there's nothing to narrate. That's not a bug; it's a reminder that "no text streamed" and "streaming is broken" are two different claims that need separate checks.
In the capstone:Eunomia's chat page keeps this lesson's goal (visible progress instead of a silent wait) with one deliberate change: the service verifies the whole answer before streaming, so the web client receives paced, already-verified answer.delta events closed by one answer.final, not live model tokens. Text already shown in a browser cannot be recalled, so the first release never streams unchecked chunks.
Lesson 4
Evidence-Based Answers with a Search-Then-Answer Workflow
The problem: Eunomia and Skill Reporter can sound confident while being wrong when answers are not grounded in approved sources. Model pretraining does not include your current product and policy truth. Both domains need retrieval-backed evidence to prevent confident hallucinations.
The fix is RAG (Retrieval-Augmented Generation — searching real documents before asking the AI to answer) to make responses grounded (conditioned on supplied evidence). This example uses vector search (matching numeric representations of meaning rather than exact words), applies a minimum relevance threshold, and returns a fixed no-evidence message when nothing qualifies. It is the first genuine multi-step workflow (a pipeline where each step does one job and passes its result to the next): search, check relevance, then generate.
QUESTION → SEARCH BY MEANING → RELEVANCE CHECK → GENERATE FROM RETRIEVED EVIDENCE, OR RETURN A FIXED NO-EVIDENCE MESSAGE
Splitting search and generation into two separate steps — instead of one function that does both — means either step can be tested, replaced, or reordered on its own: a real document database can later replace the sample sentences without touching how the final answer gets generated.
Instruction that matters, but is not an enforcement boundary: tell the AI to use the retrieved evidence. The relevance threshold prevents unsupported generation when search returns nothing useful; the prompt reduces the risk of blending in general knowledge, but cannot prove that every generated sentence came from the evidence.
import asyncio
from dataclasses import dataclass
from pydantic_ai import Agent
@dataclass
class Match:
text: str
score: float
class InMemoryVectorStore:
def __init__(self, docs: list[str]) -> None:
self.docs = docs
async def search(self, query: str, top_k: int) -> list[Match]:
query_terms = set(query.lower().split())
scored: list[Match] = []
for doc in self.docs:
overlap = len(query_terms.intersection(doc.lower().split()))
score = overlap / max(len(query_terms), 1)
scored.append(Match(text=doc, score=score))
return sorted(scored, key=lambda m: m.score, reverse=True)[:top_k]
vector_store = InMemoryVectorStore(
[
"ISA withdrawals may be restricted during a fixed term.",
"Instant access accounts allow withdrawals without notice.",
"Portfolio simulations require consent and a complete risk profile.",
]
)
rag_agent = Agent("openai:gpt-4o", system_prompt="Answer using only the retrieved evidence.")
MIN_RELEVANCE = 0.35
question = "Can I withdraw early from a fixed-term ISA?"
async def main() -> None:
matches = await vector_store.search(query=question, top_k=3)
relevant = [match for match in matches if match.score >= MIN_RELEVANCE]
if not relevant:
print("I don't have enough product evidence to answer that.")
return
context = "\n".join(match.text for match in relevant)
answer = await rag_agent.run(
f"Use only this retrieved evidence:\n{context}\n\nQuestion: {question}"
)
print(answer.output)
if __name__ == "__main__":
asyncio.run(main())
import { generateText } from "ai"
import { openai } from "@ai-sdk/openai"
type Match = { text: string; score: number }
class InMemoryVectorStore {
constructor(private readonly docs: string[]) {}
async search({ query, topK }: { query: string; topK: number }): Promise<Match[]> {
const queryTerms = new Set(query.toLowerCase().split(/\s+/))
const scored = this.docs.map((text) => {
const docTerms = new Set(text.toLowerCase().split(/\s+/))
const overlap = [...queryTerms].filter((term) => docTerms.has(term)).length
return { text, score: overlap / Math.max(queryTerms.size, 1) }
})
return scored.sort((a, b) => b.score - a.score).slice(0, topK)
}
}
const vectorStore = new InMemoryVectorStore([
"ISA withdrawals may be restricted during a fixed term.",
"Instant access accounts allow withdrawals without notice.",
"Portfolio simulations require consent and a complete risk profile.",
])
const MIN_RELEVANCE = 0.35
async function answerQuestion(question: string): Promise<string> {
const matches = await vectorStore.search({ query: question, topK: 3 })
const relevant = matches.filter((match) => match.score >= MIN_RELEVANCE)
if (relevant.length === 0) return "I don't have enough product evidence to answer that."
const context = relevant.map((match) => match.text).join("\n")
const { text } = await generateText({
model: openai("gpt-4o"),
prompt: `Use only this retrieved evidence:\n${context}\n\nQuestion: ${question}`,
})
return text
}
answerQuestion("Can I withdraw early from a fixed-term ISA?")
.then(console.log)
.catch(console.error)
A real finding worth knowing: a vector search genuinely matches on meaning, not spelling — a question that never literally uses the word "frameworks" can still correctly retrieve a sentence about frameworks, something a classic exact-keyword search would miss entirely.
In the capstone:Eunomia gathers approved evidence — catalogue rows through queryCatalogue and guidance passages through lookupGuidance — before wording claims about rates, maturity terms or deposit protection. When no suitable passage is found, the turn does not compose from nothing; it steps down towards a person. Part X adds the citation check this lesson leaves open: the verifier requires every claim to cite evidence ids that exist in the frozen bundle.
Lesson 5
Branching Agent Workflows with Shared State
The problem: Eunomia and Skill Reporter should not run every request through one identical path. Request intent and risk differ sharply: routine explanations, account-scoped retrieval, ISA-rule questions, and simulation requests need different controls. A single linear flow increases cost, latency, and policy risk in both domains. The real problem is deciding the next operational step from state, not just generating text.
The real problem is deciding the next operational step from state, not just generating text. The role of the graph is to make that control flow explicit: it owns step order, branch rules, and state updates. LLMs still do useful work inside steps (for example, extracting entities and intent from the customer question), but they do not directly decide control flow.
If control flow stays implicit inside one model prompt, planning, tool use, retrieval, guardrails, and human approval can blur into one opaque step. Then teams cannot clearly answer why a request took a specific path, why a safety gate was skipped, or why a risky action was attempted. The graph fixes that by turning routing into an explicit, auditable system decision.
The fix is a stateful workflow (one that remembers shared values as it runs) with conditional routing (choosing the next path from those values). A graph connects each node (one processing step) through an edge (a path to another step). The graph checks its state (the shared notebook of current values) and chooses which node runs next — built here with LangGraph (a library family for branching, stateful AI workflows; this lesson uses Python and TypeScript variants).
Libraries used in this lesson: Python uses langgraph for graph routing and Python's built-in typing module for a clear state shape. TypeScript uses @langchain/langgraph for the same graph routing pattern. The small examples below now include imports so you can see exactly where StateGraph comes from.
When the next step depends on what we already know, use a graph: think of the graph as a traffic controller. It reads the current state and sends each request to the right lane. For example, an interest question goes to the interest lane, a product-rule question goes to the policy lane, and a simulation request goes to the simulation lane. The model can still help inside each lane (for extraction or wording), but the graph owns the route, so behavior stays predictable, testable, and easy to audit.
How the agent uses the graph at run time: (1) the agent receives a query and stores it in state, (2) it runs extract_skill_node to pull out one skill name, (3) it runs evaluate_demand_node to set demand_level (demandLevel in TypeScript), and (4) the graph routes to exactly one final node based on that value. The graph is the step-order engine for the agent.
AI EXTRACTS SKILL → PLAIN CODE CHECKS A FIXED LIST → GRAPH BRANCHES LIVE: priority path OR standard path, never both
Not every decision needs an AI call. evaluate_demand_node never touches the model — a simple list-membership check is faster, free, and literally cannot hallucinate. Reaching for an AI call here would be slower for zero benefit.
Here is the full branching wiring in one place. StateGraph is LangGraph's workflow builder object: it holds your state shape, your nodes, and your routing rules. First, evaluate_demand_node writes demand_level (demandLevel in TypeScript) into shared state. Next, the routing function reads that value. Finally, the map tells the graph which node to run for each possible value.
import asyncio
from typing import Literal, TypedDict
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph
class GraphState(TypedDict):
job_query: str
identified_skill: str
demand_level: str
final_report: str
async def extract_skill_node(state: GraphState) -> dict[str, str]:
llm = ChatOpenAI(model="gpt-4o", temperature=0)
response = await llm.ainvoke(
[
SystemMessage(
content="Extract the primary technical skill name from the user's job query. Reply with only the skill name."
),
HumanMessage(content=state["job_query"]),
]
)
return {"identified_skill": str(response.content).strip()}
async def evaluate_demand_node(state: GraphState) -> dict[str, str]:
skill = state["identified_skill"].lower()
target_stack = ["langgraph", "pydantic", "vercel ai", "llamaindex"]
demand = "HIGH_DEMAND" if any(target in skill for target in target_stack) else "STANDARD_DEMAND"
return {"demand_level": demand}
async def high_priority_evaluator(state: GraphState) -> dict[str, str]:
return {
"final_report": f"PRIORITY TRACK: '{state['identified_skill']}' is a high-demand core skill."
}
async def standard_evaluator(state: GraphState) -> dict[str, str]:
return {"final_report": f"STANDARD TRACK: Identified skill '{state['identified_skill']}'."}
def route_by_demand(state: GraphState) -> Literal["high_priority_evaluator", "standard_evaluator"]:
return "high_priority_evaluator" if state["demand_level"] == "HIGH_DEMAND" else "standard_evaluator"
# Runtime flow:
# 1) Agent receives a query in state["job_query"].
# 2) extract_skill_node writes state["identified_skill"].
# 3) evaluate_demand_node writes state["demand_level"].
# 4) route_by_demand picks exactly one final evaluator node.
builder = StateGraph(GraphState)
builder.add_node("extract_skill_node", extract_skill_node)
builder.add_node("evaluate_demand_node", evaluate_demand_node)
builder.add_node("high_priority_evaluator", high_priority_evaluator)
builder.add_node("standard_evaluator", standard_evaluator)
builder.set_entry_point("extract_skill_node")
builder.add_edge("extract_skill_node", "evaluate_demand_node")
builder.add_conditional_edges(
"evaluate_demand_node",
route_by_demand,
{
"high_priority_evaluator": "high_priority_evaluator",
"standard_evaluator": "standard_evaluator",
},
)
builder.add_edge("high_priority_evaluator", END)
builder.add_edge("standard_evaluator", END)
graph = builder.compile()
async def main() -> None:
final_output = await graph.ainvoke(
{
"job_query": "Senior AI role requiring expertise in LangGraph.",
"identified_skill": "",
"demand_level": "",
"final_report": "",
}
)
print(final_output["final_report"])
if __name__ == "__main__":
asyncio.run(main())
import "dotenv/config"
import { openai } from "@ai-sdk/openai"
import { generateText } from "ai"
import { END, START, StateGraph, StateSchema } from "@langchain/langgraph"
import * as z from "zod"
const MarketState = new StateSchema({
jobQuery: z.string(),
identifiedSkill: z.string(),
demandLevel: z.string(),
finalReport: z.string(),
})
async function extractSkillNode(state: typeof MarketState.State) {
const { text } = await generateText({
model: openai("gpt-4o"),
system: "Extract the primary technical skill name from the user's job query. Reply with only the skill name.",
prompt: state.jobQuery,
})
return { identifiedSkill: text.trim() }
}
async function evaluateDemandNode(state: typeof MarketState.State) {
const skill = state.identifiedSkill.toLowerCase()
const targetStack = ["langgraph", "pydantic", "vercel ai", "llamaindex"]
const demand = targetStack.some((target) => skill.includes(target)) ? "HIGH_DEMAND" : "STANDARD_DEMAND"
return { demandLevel: demand }
}
async function highPriorityEvaluator(state: typeof MarketState.State) {
return { finalReport: `PRIORITY TRACK: '${state.identifiedSkill}' is a high-demand core skill.` }
}
async function standardEvaluator(state: typeof MarketState.State) {
return { finalReport: `STANDARD TRACK: Identified skill '${state.identifiedSkill}'.` }
}
function routeByDemand(
state: typeof MarketState.State,
): "highPriorityEvaluator" | "standardEvaluator" {
return state.demandLevel === "HIGH_DEMAND" ? "highPriorityEvaluator" : "standardEvaluator"
}
// Runtime flow:
// 1) Agent receives a query in state.jobQuery.
// 2) extractSkillNode writes state.identifiedSkill.
// 3) evaluateDemandNode writes state.demandLevel.
// 4) routeByDemand picks exactly one final evaluator node.
const graph = new StateGraph(MarketState)
.addNode("extractSkillNode", extractSkillNode)
.addNode("evaluateDemandNode", evaluateDemandNode)
.addNode("highPriorityEvaluator", highPriorityEvaluator)
.addNode("standardEvaluator", standardEvaluator)
.addEdge(START, "extractSkillNode")
.addEdge("extractSkillNode", "evaluateDemandNode")
.addConditionalEdges("evaluateDemandNode", routeByDemand, {
highPriorityEvaluator: "highPriorityEvaluator",
standardEvaluator: "standardEvaluator",
})
.addEdge("highPriorityEvaluator", END)
.addEdge("standardEvaluator", END)
.compile()
async function main() {
const finalOutput = await graph.invoke({
jobQuery: "Senior AI role requiring expertise in LangGraph.",
identifiedSkill: "",
demandLevel: "",
finalReport: "",
})
console.log(finalOutput.finalReport)
}
main().catch(console.error)
CLASSIFY REQUEST → INTEREST / RULES / SIMULATION GATE → RUN SIMULATION ONLY WITH CONSENT + RISK PROFILE, ELSE ADVISOR REVIEW
Second scenario (fintech request routing): we now apply the same graph pattern to concrete customer questions: "How much interest did I earn this month on my instant access account?", "What is my notice period?", "Can I withdraw early from a fixed-term ISA?", and "Run a portfolio optimization simulation." These questions should not share one blind path. The graph routes each one to the right branch, and the simulation branch only proceeds when both consent and risk profile are present; otherwise it routes to advisor review.
Putting Lesson 4 and Lesson 5 together: use the graph as the control-flow engine and use RAG as one branch tool. In practice, a classify_intent_node labels each question as faq, account_data, mixed, or unclear, plus a confidence score.
faq → faq_rag_node (retrieve policy/docs evidence and answer with citations). Example: "What is the early-withdrawal rule on a fixed-term ISA?" returns a policy answer with document references.
account_data → auth_check_node → account_data_lookup_node. Example: "How much interest did I earn last month on my Instant Saver?" requires customer authentication and account-level lookup.
mixed → split handling: policy via RAG + account consequence via authenticated lookup. Example: "If I move £5,000 from my Easy Access account into a fixed-term ISA today, what penalty rule applies and how would that affect my current month interest?" combines policy rules with personal account impact.
unclear → clarification_node. Example: "Can I do that transfer now?" is ambiguous, so the assistant asks what transfer, which account, and whether the question is policy-only or account-specific.
FAQ vs account-data routing rule: account signals include personal scope and identifiers (for example "my balance", "my account", reference numbers, "this month for me"). FAQ signals are general policy/how-to/eligibility questions that can be answered from docs without user-record access.
Ambiguity rule: if confidence is below threshold, ask one clarifier: "Are you asking about general policy, or your specific account details?" In high-risk cases, default to the account-data path rather than guessing.
from typing import Literal, TypedDict
from langgraph.graph import END, StateGraph
class FinState(TypedDict):
question: str
is_authenticated: bool
risk_profile_complete: bool
simulation_consent: bool
intent: str
next_route: str
answer: str
def classify_intent_node(state: FinState) -> dict[str, str]:
q = state["question"].lower()
account_signals = any(token in q for token in ["my", "account", "balance", "this month", "earned"])
faq_signals = any(token in q for token in ["policy", "notice period", "fixed-term", "isa", "how do i", "eligibility"])
simulation_signals = any(token in q for token in ["simulation", "optimiz", "projection"])
if simulation_signals:
return {"intent": "portfolio_simulation", "next_route": "simulation_gate_node"}
if account_signals and faq_signals:
return {"intent": "mixed", "next_route": "split_and_answer_node"}
if account_signals:
return {"intent": "account_data", "next_route": "auth_check_node"}
if faq_signals:
return {"intent": "faq", "next_route": "faq_rag_node"}
return {"intent": "unclear", "next_route": "clarification_node"}
def faq_rag_node(_state: FinState) -> dict[str, str]:
return {
"answer": "FAQ answer from policy evidence: fixed-term ISA withdrawals may carry restrictions. [Policy KB §3.1]"
}
def auth_check_node(state: FinState) -> dict[str, str]:
return {"next_route": "account_data_lookup_node" if state["is_authenticated"] else "verification_required_node"}
def account_data_lookup_node(_state: FinState) -> dict[str, str]:
return {"answer": "Account answer: you earned £42.18 interest this month on your instant access account."}
def split_and_answer_node(_state: FinState) -> dict[str, str]:
return {
"answer": "Mixed answer: policy says early fixed-term ISA withdrawal is restricted; your account-specific outcome needs authenticated lookup."
}
def clarification_node(_state: FinState) -> dict[str, str]:
return {"answer": "Are you asking about general policy, or your specific account details?"}
def simulation_gate_node(state: FinState) -> dict[str, str]:
if state["risk_profile_complete"] and state["simulation_consent"]:
return {"next_route": "simulation_node"}
return {"next_route": "advisor_review_node"}
def simulation_node(_state: FinState) -> dict[str, str]:
return {"answer": "Simulation answer: projected 12-month range generated from your risk profile."}
def advisor_review_node(_state: FinState) -> dict[str, str]:
return {"answer": "Simulation paused: missing consent or risk profile. Routed to advisor review."}
def verification_required_node(_state: FinState) -> dict[str, str]:
return {"answer": "Please verify your identity to access account-specific data."}
def route_by_next(state: FinState) -> Literal[
"faq_rag_node",
"auth_check_node",
"split_and_answer_node",
"clarification_node",
"simulation_gate_node",
"account_data_lookup_node",
"verification_required_node",
"simulation_node",
"advisor_review_node",
]:
return state["next_route"]
graph_builder = StateGraph(FinState)
graph_builder.add_node("classify_intent_node", classify_intent_node)
graph_builder.add_node("faq_rag_node", faq_rag_node)
graph_builder.add_node("auth_check_node", auth_check_node)
graph_builder.add_node("account_data_lookup_node", account_data_lookup_node)
graph_builder.add_node("split_and_answer_node", split_and_answer_node)
graph_builder.add_node("clarification_node", clarification_node)
graph_builder.add_node("simulation_gate_node", simulation_gate_node)
graph_builder.add_node("simulation_node", simulation_node)
graph_builder.add_node("advisor_review_node", advisor_review_node)
graph_builder.add_node("verification_required_node", verification_required_node)
graph_builder.set_entry_point("classify_intent_node")
graph_builder.add_conditional_edges(
"classify_intent_node",
route_by_next,
{
"faq_rag_node": "faq_rag_node",
"auth_check_node": "auth_check_node",
"split_and_answer_node": "split_and_answer_node",
"clarification_node": "clarification_node",
"simulation_gate_node": "simulation_gate_node",
},
)
graph_builder.add_conditional_edges(
"auth_check_node",
route_by_next,
{
"account_data_lookup_node": "account_data_lookup_node",
"verification_required_node": "verification_required_node",
},
)
graph_builder.add_conditional_edges(
"simulation_gate_node",
route_by_next,
{
"simulation_node": "simulation_node",
"advisor_review_node": "advisor_review_node",
},
)
graph_builder.add_edge("faq_rag_node", END)
graph_builder.add_edge("account_data_lookup_node", END)
graph_builder.add_edge("split_and_answer_node", END)
graph_builder.add_edge("clarification_node", END)
graph_builder.add_edge("simulation_node", END)
graph_builder.add_edge("advisor_review_node", END)
graph_builder.add_edge("verification_required_node", END)
fin_graph = graph_builder.compile()
import { END, START, StateGraph, StateSchema } from "@langchain/langgraph"
import * as z from "zod"
const FinState = new StateSchema({
question: z.string(),
isAuthenticated: z.boolean(),
riskProfileComplete: z.boolean(),
simulationConsent: z.boolean(),
intent: z.string(),
nextRoute: z.string(),
answer: z.string(),
})
type Route =
| "faqRagNode"
| "authCheckNode"
| "splitAndAnswerNode"
| "clarificationNode"
| "simulationGateNode"
| "accountDataLookupNode"
| "verificationRequiredNode"
| "simulationNode"
| "advisorReviewNode"
function classifyIntentNode(state: typeof FinState.State) {
const q = state.question.toLowerCase()
const accountSignals = ["my", "account", "balance", "this month", "earned"].some((token) => q.includes(token))
const faqSignals = ["policy", "notice period", "fixed-term", "isa", "how do i", "eligibility"].some((token) =>
q.includes(token),
)
const simulationSignals = ["simulation", "optimiz", "projection"].some((token) => q.includes(token))
if (simulationSignals) return { intent: "portfolio_simulation", nextRoute: "simulationGateNode" }
if (accountSignals && faqSignals) return { intent: "mixed", nextRoute: "splitAndAnswerNode" }
if (accountSignals) return { intent: "account_data", nextRoute: "authCheckNode" }
if (faqSignals) return { intent: "faq", nextRoute: "faqRagNode" }
return { intent: "unclear", nextRoute: "clarificationNode" }
}
function faqRagNode() {
return { answer: "FAQ answer from policy evidence: fixed-term ISA withdrawals may carry restrictions. [Policy KB §3.1]" }
}
function authCheckNode(state: typeof FinState.State) {
return { nextRoute: state.isAuthenticated ? "accountDataLookupNode" : "verificationRequiredNode" }
}
function accountDataLookupNode() {
return { answer: "Account answer: you earned £42.18 interest this month on your instant access account." }
}
function splitAndAnswerNode() {
return {
answer:
"Mixed answer: policy says early fixed-term ISA withdrawal is restricted; your account-specific outcome needs authenticated lookup.",
}
}
function clarificationNode() {
return { answer: "Are you asking about general policy, or your specific account details?" }
}
function simulationGateNode(state: typeof FinState.State) {
return { nextRoute: state.riskProfileComplete && state.simulationConsent ? "simulationNode" : "advisorReviewNode" }
}
function simulationNode() {
return { answer: "Simulation answer: projected 12-month range generated from your risk profile." }
}
function advisorReviewNode() {
return { answer: "Simulation paused: missing consent or risk profile. Routed to advisor review." }
}
function verificationRequiredNode() {
return { answer: "Please verify your identity to access account-specific data." }
}
function routeByNext(state: typeof FinState.State): Route {
return state.nextRoute as Route
}
const finGraph = new StateGraph(FinState)
.addNode("classifyIntentNode", classifyIntentNode)
.addNode("faqRagNode", faqRagNode)
.addNode("authCheckNode", authCheckNode)
.addNode("accountDataLookupNode", accountDataLookupNode)
.addNode("splitAndAnswerNode", splitAndAnswerNode)
.addNode("clarificationNode", clarificationNode)
.addNode("simulationGateNode", simulationGateNode)
.addNode("simulationNode", simulationNode)
.addNode("advisorReviewNode", advisorReviewNode)
.addNode("verificationRequiredNode", verificationRequiredNode)
.addEdge(START, "classifyIntentNode")
.addConditionalEdges("classifyIntentNode", routeByNext, {
faqRagNode: "faqRagNode",
authCheckNode: "authCheckNode",
splitAndAnswerNode: "splitAndAnswerNode",
clarificationNode: "clarificationNode",
simulationGateNode: "simulationGateNode",
})
.addConditionalEdges("authCheckNode", routeByNext, {
accountDataLookupNode: "accountDataLookupNode",
verificationRequiredNode: "verificationRequiredNode",
})
.addConditionalEdges("simulationGateNode", routeByNext, {
simulationNode: "simulationNode",
advisorReviewNode: "advisorReviewNode",
})
.addEdge("faqRagNode", END)
.addEdge("accountDataLookupNode", END)
.addEdge("splitAndAnswerNode", END)
.addEdge("clarificationNode", END)
.addEdge("simulationNode", END)
.addEdge("advisorReviewNode", END)
.addEdge("verificationRequiredNode", END)
.compile()
A real finding worth knowing: each node returns only the fields it changed, and the graph engine merges that update into shared state. In TypeScript, a narrow return type such as Pick<typeof MarketState.State, "demandLevel"> lets a type-checker (a tool that checks declared types before the program runs) reject updates to unrelated state fields. Python needs an equivalent narrow return model if the same ownership check is required there.
In the capstone: this branching pattern becomes Eunomia's routing policy: a classifier gives each message a typed question type and a confidence score, and a reviewed, versioned table maps it to a starting answer step — a template, a composed answer from catalogue or guidance evidence, or an immediate hand-off to a person. Low confidence goes straight to a person. The branch is chosen per message, but by a table that is tested and released like code, not improvised.
Part II
Giving Agents Tools at Scale (Protocols & Dynamic Tooling)
A tool written inside one agent works until another agent needs it, a team changes it, or live data moves underneath it. This part replaces that brittle arrangement in five steps: put tools behind a standard server, discover them while the agent is running, subscribe to changing resources, register carefully generated tools without a restart, and build input checks from every tool's own description. Read Lessons 6, 23, 32, 33 and 48 in that order: each adds the piece the next one depends on.
Dual-domain map for this part: every mechanism is shown in the fintech Eunomia implementation and should be mirrored in the Skill Reporter implementation.
Fintech domain: balances, savings goals, interest projection, and runtime safety boundaries around customer-impacting tools.
Skill Reporter domain: skill lookup, report generation, report-ready updates, and runtime safety boundaries around publishing/reporting tools.
Interlink chain: Lesson 6 creates shared MCP servers, 23 discovers tools at runtime, 32 pushes live updates, 33 adds sandboxed runtime registration, and 48 validates every call against advertised schemas.
Lesson 6
MCP Server Architecture with FastMCP and the TypeScript SDK
The problem: a balance-checking tool starts life inside one assistant. When a second assistant needs the same capability, copying the function feels harmless, but there are now two implementations to secure, test and keep in step. Add more agents and every fix becomes a synchronisation problem. The Skill Reporter agent hits the same failure mode when skill-lookup and report-formatting functions get copied across assistants.
The replacement is MCP — Model Context Protocol (a published set of rules for how an AI agent asks a separate program what tools it has and then calls one). The functions move into an MCP server (the separate program that owns the tools and answers an agent's requests, rather than living inside the agent). Any compliant client can now use one shared implementation, whether that client is written in Python, TypeScript or something else. FastMCP (a Python framework for implementing MCP servers) powers the Python examples; the TypeScript examples use the MCP TypeScript SDK.
Client and server still need a transport (the wire that carries their messages). stdio, standard input/output, pipes text between one client and the server process it launches on the same machine; several clients therefore launch separate processes from the same server implementation. HTTP, Hypertext Transfer Protocol, lets several clients connect over a network to one server process. When a client asks what is available, the server returns a tool schema (a machine-readable description, usually expressed as JavaScript Object Notation or JSON, of a tool's name, purpose and required inputs). FastMCP builds that description from the registered Python function, so a function written once becomes both executable code and a discoverable contract.
from fastmcp import FastMCP
mcp = FastMCP("Eunomia")
@mcp.tool
async def get_balance(account_id: str) -> dict[str, int | str]:
"""Return the current balance in pence."""
return {"account_id": account_id, "balance_pence": 125_00}
if __name__ == "__main__":
mcp.run(transport="stdio")
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({ name: "eunomia", version: "1.0.0" });
server.registerTool("get_balance", {
description: "Return the current balance in pence",
inputSchema: { accountId: z.string() },
}, async ({ accountId }) => ({
content: [{ type: "text", text: JSON.stringify({ accountId, balancePence: 12500 }) }],
}));
await server.connect(new StdioServerTransport());
TWO HTTP CLIENTS → ONE NETWORK SERVER; STDIO CLIENTS INSTEAD LAUNCH SEPARATE SERVER PROCESSES FROM ONE SHARED IMPLEMENTATION
A real finding worth knowing: with the stdio transport, an ordinary debug print to standard output corrupts the protocol's message stream. The client then fails with a confusing parse error that points away from the real cause. Logs must go to standard error instead. The same trap exists in both versions: Python's print and TypeScript's console.log are unsafe on that channel.
In the capstone: this is where Eunomia's optional MCP server is born, and the Skill Reporter server follows the same shape. Guidance lookup and catalogue queries stay in the service, and the optional MCP server is a second adapter that exposes those same reviewed implementations to other approved hosts, while the customer's own account snapshot never leaves the service; skill lookup and report-formatting tools do the same in the Skill Reporter stack. An HTTP deployment can serve both halves of either server from one process; a stdio deployment starts one server process per client. Lesson 23 then shows how the hosts that consume such a server discover its tools instead of hardcoding them.
Lesson 23
Dynamic Tool Discovery & MCP Client Connection
The problem: in Eunomia, compliance can require a new tool immediately — for example, splitting "general savings question" from "regulated advice request" before any answer is shown. If the agent carries a hardcoded tool list, that urgent server-side tool cannot be used until the agent is edited, rebuilt and redeployed. Skill Reporter hits the same failure mode when a new report-validation or publishing-safety tool exists on the server but the running agent still cannot see it.
An MCP client (the part of the agent that connects to an MCP server, sends requests and reads replies) removes that last fixed list. It performs runtime discovery (finding which tools exist while the program is running, rather than fixing the list when the code is built). In Eunomia, this means newly deployed account-check, consent-check, or simulation-gate tools become callable without waiting for an app redeploy. In Skill Reporter, newly deployed report-quality and publish-policy tools become callable the same way. The client opens a session (the live connection and context used for discovery and calls) and begins it with a handshake (the opening initialize exchange in which client and server agree on a protocol version), then asks for the current tools.
The reply is a tool manifest (the server's list of each tool's name, description and input schema). A production client follows pagination until it has every page, then converts the complete manifest into definitions the large language model (the AI model that selects and calls tools), or LLM, can see. When the model selects one, a long-lived client sends the call through the still-open session. The short excerpts below demonstrate discovery only: both deliberately close after reading the first page, so they must not be used as the owner of an agent-lifetime session.
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def discover_tools() -> list[str]:
params = StdioServerParameters(command="python", args=["eunomia_server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
manifest = await session.list_tools()
return [tool.name for tool in manifest.tools]
HANDSHAKE → ASK THE SERVER WHAT EXISTS NOW → CONVERT ITS MANIFEST FOR THE LLM → CALL THE SELECTED TOOL
A real finding worth knowing: the two SDKs (software development kits, meaning the official client libraries) manage connection lifetime differently. Python ties the session to an async with block; TypeScript needs an explicit close call. Discovery helpers such as those above cannot later call a selected tool because they close before returning. An agent therefore needs a long-lived owner that keeps the session open through discovery and calls, follows every manifest page, and closes only during shutdown.
In the capstone:Eunomia's own service deliberately keeps a fixed, reviewed set of three capabilities, because each one is part of a gated release. Runtime discovery applies to the other approved hosts that consume Eunomia's optional MCP server (building on the server from Lesson 6), and Skill Reporter's consumers use the same long-lived pattern against its server. Each MCP client connects at startup, reads every page of the current manifest, builds its toolset and keeps that session available for calls until shutdown, so a consumer picks up a new server tool without its own redeploy. Lesson 32 layers live updates on top of this discovered toolset.
Lesson 32
MCP Real-Time Resource Subscriptions
The problem: discovering tools at startup solves a changing catalogue, but Eunomia still needs fresh customer state during the conversation — balance, goal progress, and eligibility facts that can change after a deposit or profile update. Polling for those changes wastes calls and can leave Eunomia speaking from stale data. Skill Reporter has the same issue for report-ready state and policy updates during an active publishing workflow.
In MCP, a resource (readable data exposed by the server at an address, rather than an action to perform) might live at eunomia://accounts/123/balance. That address is a Uniform Resource Identifier, or URI (the name of a particular MCP resource). The simplest way to watch it is polling (asking the same question again and again on a timer to see if the answer changed), but most requests return “no” and the client can remain stale until the next timer fires.
A subscription (a standing request asking the server to report whenever a named resource changes) reverses that flow. On a deposit, the server sends a notification (a one-way message that expects no reply, here saying that a resource address was updated). The client reads the resource once and receives the fresh balance without a loop of empty checks. A multi-client server must record subscribed URIs separately for each live session, remove them on unsubscribe or disconnect, and notify only the relevant sessions.
The excerpts below isolate the update mechanism for one connected client. They do not implement production subscription routing: the Python call targets the session that invoked the tool, and the TypeScript set assumes exactly one connection.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { SubscribeRequestSchema } from "@modelcontextprotocol/sdk/types.js";
const server = new McpServer(
{ name: "eunomia", version: "1.0.0" },
{ capabilities: { resources: { subscribe: true } } },
);
const subscribedUrisForThisConnection = new Set<string>();
server.server.setRequestHandler(SubscribeRequestSchema, async (request) => {
subscribedUrisForThisConnection.add(request.params.uri);
return {};
});
async function balanceChanged(uri: string): Promise<void> {
if (subscribedUrisForThisConnection.has(uri)) {
await server.server.sendResourceUpdated({ uri });
}
}
POLLING REPEATS EMPTY CALLS AND CAN BE STALE; A SUBSCRIPTION PUSHES ONE ADDRESS UPDATE, THEN THE CLIENT READS ONCE
A resource update is a signal, not a durable event log. Subscriptions improve live responsiveness; they do not guarantee that a disconnected client can recover every change it missed.
A real finding worth knowing: the TypeScript excerpt is a handler fragment layered onto Lesson 6's connected server; by itself it omits the transport connection bootstrap and is not standalone. The notification contains only the resource's address, not its new value, so the client must perform a second read. Nothing replays an update that happened before subscription setup or while the connection was down; it is simply lost. The one-client excerpts above are not sufficient for a shared network server: that version also needs per-session subscribe and unsubscribe handling, disconnect cleanup, a resource-read handler and dispatch only to sessions subscribed to the changed URI. Subscription APIs vary between SDK versions, so the installed version and transport must be checked before the design relies on them.
In the capstone:Eunomia's read-only first release does not subscribe to a customer's balance or savings-goal progress: each turn reads a fresh snapshot through readSnapshot and freezes it as evidence. Subscriptions appear only at the optional MCP server, where a host can be told that the catalogue version changed and then re-read it, while a turn already in progress keeps its pinned catalogue version. Skill Reporter applies the same subscription pattern to report-ready and policy-update resources so publication decisions use fresh state instead of stale polling snapshots.
Lesson 33
Dynamic Tool Synthesis & Runtime Registration
The problem: Eunomia can receive customer questions that need a narrow helper tool that does not exist yet (for example, a specific savings projection transform). If every tool must be prewritten, discovery can only confirm the gap and the customer flow stalls until a developer ships a new release. Skill Reporter encounters the same stall when a report-formatting helper is missing in the middle of a reporting run.
Tool synthesis (having an AI or code generator write the source of a new tool function instead of a human writing it) can fill narrow, low-risk gaps. In Eunomia, that means bounded read-only helpers such as calculations or formatting, never money movement or customer-record mutation. In Skill Reporter, that means bounded report-transformation helpers, never privileged publication actions. Before registration, generated source must pass syntax checks, an import allow-list, known test inputs and a sandbox run. A sandbox (a locked-down environment where untrusted code has limited access) is essential because generated source must be treated as hostile until proven otherwise.
If that separate gate succeeds, runtime registration (adding a tool to a running server's catalogue without restarting it) makes the function available. Connected clients must then be told to request the tool list again. In FastMCP, automatic tools/list_changed notifications (messages telling clients that the catalogue changed) depend on registration occurring in an active MCP request context; otherwise the application must arrange notification explicitly. The excerpts below show only the final registration step after the omitted gate has completed, not code generation or sandboxing.
from math import ceil
from fastmcp import FastMCP
mcp = FastMCP("Eunomia")
def months_to_goal(target_pence: int, monthly_pence: int) -> int:
"""Calculate whole months needed to reach a savings target."""
if target_pence <= 0 or monthly_pence <= 0:
raise ValueError("amounts must be positive")
return ceil(target_pence / monthly_pence)
def register_validated_tool() -> None:
mcp.add_tool(months_to_goal)
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
function registerMonthsToGoal(server: McpServer): void {
server.registerTool("months_to_goal", {
description: "Calculate whole months needed to reach a savings target",
inputSchema: {
targetPence: z.number().int().positive(),
monthlyPence: z.number().int().positive(),
},
}, async ({ targetPence, monthlyPence }) => ({
content: [{
type: "text",
text: String(Math.ceil(targetPence / monthlyPence)),
}],
}));
}
MISSING CAPABILITY → GENERATE IN A SANDBOX → VALIDATE OR REJECT → REGISTER → NOTIFY WHERE CONFIGURED → RE-LIST → USE
Eunomia may synthesise a small calculator for a savings projection or “what-if” deposit scenario. It must never synthesise code that moves money or reads customer records; those tools remain human-written, reviewed and deliberately deployed.
A real finding worth knowing: Python can derive a tool's input schema from type hints (annotations that state the expected Python types), but the manifest produced for an unannotated parameter is FastMCP-version-dependent and must be inspected against the pinned package version. TypeScript types are erased at runtime, so a runtime schema must be supplied explicitly. In either language, exec and eval execute source text at runtime; passing generated text to them outside the omitted sandbox and validation gate would bypass the protection this design requires.
In the capstone:Eunomia's first release deliberately does not synthesise or register tools at runtime: its three capabilities and the two tools on its optional MCP server are written by people, reviewed, and shipped through the quality gate, so the advertised contract changes only through a release. If synthesis is added later, this lesson's rules hold: only low-risk calculator or formatting helpers, only a complete implementation may register one, and Lesson 48 checks every call against advertised schemas before execution. The boundary must be capability-based (generated code is technically denied powers it was not granted), not merely a warning in a prompt: the sandbox gives generated code no access to money movement or customer data in Eunomia, and no access to protected report destinations in Skill Reporter, which defers synthesis the same way.
Lesson 48
Dynamic Tool Schema Introspection for Runtime-Registered Tools
The problem: an agent can now discover old and newly synthesised tools, but discovery alone does not prove that the arguments it sends are valid. In Eunomia, malformed arguments can hit account-scoped or simulation-gated financial logic with unclear failures; in Skill Reporter, malformed arguments can reach report-generation or publish-policy tools and fail too late. Without a local checker, both systems push bad input into critical paths instead of stopping early with a repairable error.
Every manifest carries JSON Schema (a standard, written in JSON, that describes what data must look like, including field types and which fields are required). The client uses introspection (examining a description at runtime to learn its structure) to turn that advertised schema into executable validation before making a call.
Python and TypeScript use Pydantic / Zod (validation libraries for Python and TypeScript respectively, which reject data that does not match a declared shape and return clear errors). Here the declaration is not handwritten: the converter creates a dynamic model (a validation class or schema object built by code while the program runs). Valid arguments proceed to the server; invalid ones become a structured error the language model can use to repair its next attempt.
The converters below are deliberately incomplete sketches for a small flat subset. They do not preserve all JSON Schema semantics and must not be treated as production validation.
A SUPPORTED JSON SCHEMA SUBSET → A RUNTIME PYDANTIC OR ZOD CHECKER → VALID CALL, OR A STRUCTURED ERROR BEFORE FINANCIAL LOGIC RUNS
A converter sits on a trust boundary (the point where data moves from a less trusted component into a more trusted one). “It produced a validator” is not proof that the validator means the same thing as the server's schema; acceptance and rejection must be tested against the real manifest.
A real finding worth knowing: the sketches support only flat strings and numbers, plus Python integers. They omit booleans, arrays, objects, null, enumerations, bounds, patterns, multiple allowed types, nested objects, shared-definition references ($ref) and “one of these shapes” unions (anyOf). They also differ from JSON Schema over numeric-string coercion, unknown fields and optional versus required-but-nullable fields (fields that are required to exist but allowed to contain null). A client checker can therefore accept input the server rejects, or reject input the server accepts. Production code should use a version-pinned converter with parity tests, or validate directly against JSON Schema.
In the capstone:Eunomia registers no tools at runtime in its first release, so this lesson applies to the hosts that consume its optional MCP server: they turn the advertised lookupGuidance and queryCatalogue schemas into local tool definitions, while the server still validates every call against the same Zod schemas. A host may rely on its own conversion only with a complete, version-pinned validator and acceptance/rejection parity tests for every manifest entry, and tools registered at runtime as in Lesson 33 would need the same. Skill Reporter follows the same rule. The small converters above demonstrate the idea, not that guarantee.
Part II Through-Line
From One Shared Implementation to Safe Dynamic Tooling
These five lessons form one chain rather than five isolated techniques, and the chain applies to both Eunomia (fintech) and Skill Reporter. Lesson 6 creates shared MCP server foundations. Lesson 23 removes hardcoded tool lists. Lesson 32 adds session-aware live resource updates. Lesson 33 adds sandboxed runtime registration. Lesson 48 turns advertised schemas into client-side validation gates before calls. The result is one repeatable tool-platform pattern that can evolve without giving up explicit boundaries.
const partTwo = [
[6, "Tools share one server implementation", "Eunomia MCP server exists", "Skill Reporter MCP server exists"],
[23, "Agent discovers tools at runtime", "No hardcoded Eunomia tool list", "No hardcoded Skill Reporter tool list"],
[32, "Server routes live resource changes", "Session-aware balance and goal updates", "Session-aware report-ready updates"],
[33, "Validated tools register while running", "Sandboxed calculator synthesis", "Sandboxed report-helper synthesis"],
[48, "Discovered schemas require parity tests", "Complete schemas checked before calls", "Complete schemas checked before calls"],
] as const;
Part III
Memory & Retrieval
An AI agent is only as trustworthy as the information it can find and remember. This part moves from finding documents, through remembering conversations and connected facts, to keeping retrieval (finding relevant stored information for a question) correct when source material changes. Across all six lessons, Eunomia learns to search product and FAQ documents, retain what a customer has said, and support every factual claim about an account or product with current retrieved evidence rather than the model's memory.
The reading path is deliberate: Lessons 14 and 21 find information, Lessons 28 and 34 remember it, and Lessons 49 and 51 keep changing information correct and join search results to source-linked facts.
Dual-domain map for this part: every mechanism shown for Eunomia (fintech) is meant to transfer to Skill Reporter.
Fintech domain: product/FAQ retrieval, customer-memory recall, entity disambiguation, and rate-change index updates.
Skill Reporter domain: skill-catalogue retrieval, report-memory recall, skill/entity disambiguation, and skill-definition index updates.
Interlink chain: Lesson 14 hybrid retrieval + Lesson 21 graph facts, then Lesson 28 semantic memory + Lesson 34 entity memory, then Lesson 49 live index correctness, ending in Lesson 51 cross-representation agreement.
Lesson 14
Hybrid Search: Dense + Sparse Retrieval
The problem: meaning-only search can answer “what's the rate on the 95-day notice account?” with a different notice product that merely sounds similar. Exact-word search has the opposite weakness: it can miss “how long do I have to wait to get my money out?” because the customer never used the formal words “notice period.” A dependable fintech retrieval layer must understand both meaning and exact product language. Skill Reporter has the same requirement when users ask in plain language but the catalogue stores formal skill names and versioned tags.
Dense retrieval (search by meaning, where each passage becomes a long list of numbers and passages with similar meanings sit close together) handles everyday descriptions. That list is an embedding (a numeric fingerprint of what a piece of text means, produced by a model). Dense retrieval can connect “wait to get my money out” with a passage about a withdrawal notice period even when the words differ.
Sparse retrieval (classic keyword search that scores exact query words, with rare words receiving more weight), commonly implemented with BM25 (the standard formula for that keyword score), protects exact identifiers such as “95-day.” The dense branch searches a vector index (a store organised by meaning fingerprints); the sparse branch uses a tokenizer (a component that splits text into searchable terms). Each returns its top K (the highest-ranked K results). The two searches then need score fusion (combining two result lists into one final ranking).
The introductory baseline below divides each branch by its highest score before applying a weight. This max-score normalisation (scaling one result list by its largest observed score) makes the scales comparable for a small example, but it is sensitive to which candidates happen to be present and gives a one-result branch its full weight. Lesson 49 replaces it with rank-based RRF for the production design, and Lesson 51 consumes that fused retrieval output in its grounding check.
from collections import defaultdict
from typing import TypeAlias
Ranked: TypeAlias = list[tuple[str, float]]
def fuse_scores(dense: Ranked, sparse: Ranked) -> Ranked:
fused: defaultdict[str, float] = defaultdict(float)
for results, weight in ((dense, 0.6), (sparse, 0.4)):
if not results:
continue
peak = max(score for _, score in results)
if peak <= 0:
raise ValueError("branch scores must include a positive value")
for document_id, score in results:
fused[document_id] += weight * score / peak
return sorted(fused.items(), key=lambda item: item[1], reverse=True)
print(fuse_scores([("notice", 0.82)], [("notice", 12.4), ("fixed", 9.1)]))
type ScoredResult = { documentId: string; score: number };
function fuseScores(
dense: ScoredResult[],
sparse: ScoredResult[],
): ScoredResult[] {
const fused = new Map<string, number>();
for (const [results, weight] of [[dense, 0.6], [sparse, 0.4]] as const) {
if (results.length === 0) continue;
const peak = Math.max(...results.map(({ score }) => score));
if (peak <= 0) throw new Error("branch scores must include a positive value");
for (const { documentId, score } of results) {
fused.set(documentId, (fused.get(documentId) ?? 0) + weight * score / peak);
}
}
return [...fused].map(([documentId, score]) => ({ documentId, score }))
.sort((a, b) => b.score - a.score);
}
console.log(fuseScores([{ documentId: "notice", score: 0.82 }],
[{ documentId: "notice", score: 12.4 }, { documentId: "fixed", score: 9.1 }]));
ONE QUERY TAKES A MEANING PATH AND AN EXACT-WORD PATH → THE TWO RANKINGS ARE FUSED → ONE BALANCED RESULT LIST
Raw scores cannot be compared safely. Dense similarity commonly sits between 0 and 1, while a BM25 score can be 5, 20, or more. Adding them directly lets keyword search quietly drown out meaning search.
A real finding worth knowing: the TypeScript exercise required a real Qdrant server and did not have Python's built-in fusion retriever. In the verified run, both implementations still surfaced the same two target documents. That result supports the retrieval design for the tested data; it does not guarantee identical rankings across tokenizers or corpora.
In the capstone:Eunomia's guidance store can run hybrid search over its approved guidance passages behind lookupGuidance, so a customer reaches the right passage whether they quote a precise product or term name or describe their need in everyday language; product figures themselves come from the catalogue's structured filter. Skill Reporter uses the same hybrid pattern over its skill catalogue so a reporter can find the right skill whether they use exact names or plain-language descriptions.
Lesson 21
Knowledge Graph Construction
The problem: similarity search can find a passage that sounds relevant, but it cannot reliably answer “which accounts held at this bank pay monthly interest?” That question asks how products, banks, rates, and payment schedules are connected. Those connections must be extracted and stored in a directly queryable form. Skill Reporter faces the same graph need when linking skills to roles, regions, confidence bands, and report sections.
A knowledge graph (a network of things joined by labelled links) turns prose into explicit facts. Each entity (one distinct thing, such as a product, bank, or interest rate, represented as a node) is connected by a relationship or edge (a labelled, one-directional link between two entities). The smallest useful graph fact is a triple (subject → relationship → object), such as “Easy Saver → HAS_RATE → 4.1%.”
The extraction step asks a model for structured triples rather than a summary. Before storage, names are normalised so “Easy Saver,” “Easy-Saver account,” and “the Easy Saver” can become one node. Relationship direction must also be validated: “Easy Saver → HELD_AT → Partner Bank A” is meaningful, while the reversed edge claims that a bank is held at an account. The small example focuses on normalisation and provenance; it does not implement that domain validation. Each stored edge retains its source document, passage, and extraction time. That provenance makes the edge source-linked; it does not independently prove that the source is true.
from dataclasses import dataclass, replace
from datetime import datetime, timezone
import re
@dataclass(frozen=True)
class Triple:
subject: str
relation: str
object: str
source_document: str
passage_id: str
extracted_at: datetime
def normalise_entity(name: str) -> str:
cleaned = re.sub(r"[^a-z0-9 ]", " ", name.casefold())
words = [word for word in cleaned.split() if word not in {"the", "account"}]
return " ".join(words)
def add_triple(graph: set[Triple], triple: Triple) -> None:
graph.add(replace(triple, subject=normalise_entity(triple.subject),
object=normalise_entity(triple.object)))
graph: set[Triple] = set()
add_triple(graph, Triple("The Easy-Saver account", "HELD_AT", "Partner Bank A",
"product-sheet-42", "passage-7", datetime.now(timezone.utc)))
RAW PRODUCT TEXT → STRUCTURED TRIPLES → NAME NORMALISATION AND DEDUPLICATION → QUERYABLE ENTITIES AND LABELLED RELATIONSHIPS
A real finding worth knowing: the verified run extracted four triples and, when queried for one entity, traversed only its two outgoing edges. That demonstrates directed traversal on the tested graph; it does not establish that every model-extracted relationship is correct.
In the capstone:Eunomia's first release answers questions such as “which easy-access accounts are held at a different bank?” from the snapshot's banking-group field for each holding (read through readSnapshot) and the catalogue's access types (through queryCatalogue), not from a graph. A source-linked product graph like this one is deferred until questions need relationships the catalogue cannot express; when it arrives, it must follow source-linked edges instead of guessing from similar-sounding passages. Skill Reporter can build the equivalent graph over skills and reports under the same source-linked edge discipline before making claims.
Lesson 28
Semantic Conversation Memory
The problem: a customer may say “I'm saving for a house deposit” and return to that goal twenty messages later. A chat system that keeps only the latest few turns has already discarded it. The agent needs to recall an earlier turn because it is relevant, not merely because it is recent. Skill Reporter has the same failure mode when a reporter's earlier constraint (for example "UK-only roles" or "weekly summary format") is dropped mid-session.
A model can read only its context window (the maximum number of tokens it can consider at once; anything outside that limit is invisible). Sliding window memory (keeping only the last N messages and dropping the rest) controls that limit but forgets long-running goals. Semantic memory (storing past turns as embeddings, or meaning fingerprints, so they can be searched by meaning rather than position) lets the current message retrieve a relevant statement from much earlier in the conversation.
Relevance alone is not enough when a customer changes their mind. Recency weighting (giving newer memories a small ranking boost) helps a recent correction outrank an older, equally relevant preference. Similarity search (ranking stored memories by closeness of meaning) selects older turns, while prompt assembly (combining chosen memory with recent turns for the model) controls what is sent. The example stays within one conversation; cross-session retention additionally needs authenticated customer identity, consent, deletion rules, retention limits, and tenant isolation.
from dataclasses import dataclass
from datetime import datetime, timezone
from math import sqrt
from typing import Awaitable, Callable
@dataclass(frozen=True)
class Memory:
text: str
created_at: datetime
embedding: list[float]
embedding_model: str
def cosine_similarity(left: list[float], right: list[float]) -> float:
if len(left) != len(right) or not left:
raise ValueError("embedding dimensions must match and be non-empty")
left_norm = sqrt(sum(value * value for value in left))
right_norm = sqrt(sum(value * value for value in right))
if left_norm == 0 or right_norm == 0:
raise ValueError("embeddings must have non-zero magnitude")
return sum(a * b for a, b in zip(left, right)) / (left_norm * right_norm)
async def recall(query: str, memories: list[Memory], embedding_model: str,
embed: Callable[[str], Awaitable[list[float]]]) -> list[Memory]:
query_vector = await embed(query)
now = datetime.now(timezone.utc)
def score(memory: Memory) -> float:
if memory.embedding_model != embedding_model:
raise ValueError("embedding model mismatch")
similarity = cosine_similarity(query_vector, memory.embedding)
recency = 1 / (1 + max(0, (now - memory.created_at).days))
return similarity + 0.05 * recency
return sorted(memories, key=score, reverse=True)[:3]
interface Memory {
text: string;
createdAt: Date;
embedding: number[];
embeddingModel: string;
}
type Embed = (text: string) => Promise<number[]>;
function cosineSimilarity(left: number[], right: number[]): number {
if (left.length === 0 || left.length !== right.length) {
throw new Error("embedding dimensions must match and be non-empty");
}
const dot = left.reduce((sum, value, index) => sum + value * right[index], 0);
const leftNorm = Math.sqrt(left.reduce((sum, value) => sum + value * value, 0));
const rightNorm = Math.sqrt(right.reduce((sum, value) => sum + value * value, 0));
if (leftNorm === 0 || rightNorm === 0) throw new Error("embeddings must have non-zero magnitude");
return dot / (leftNorm * rightNorm);
}
async function recall(query: string, memories: Memory[],
embeddingModel: string, embed: Embed): Promise<Memory[]> {
const queryVector = await embed(query);
const score = (memory: Memory): number => {
if (memory.embeddingModel !== embeddingModel) throw new Error("embedding model mismatch");
const similarity = cosineSimilarity(queryVector, memory.embedding);
const ageDays = Math.max(0, (Date.now() - memory.createdAt.getTime()) / 86_400_000);
return similarity + 0.05 / (1 + ageDays);
};
return [...memories].sort((a, b) => score(b) - score(a)).slice(0, 3);
}
EVERY TURN ENTERS SEMANTIC MEMORY → A NEW MESSAGE RETRIEVES RELEVANT OLDER TURNS → THOSE MEMORIES JOIN THE LATEST TURNS IN THE MODEL PROMPT
A real finding worth knowing: a threshold of 0.75 silently returned no memories in the measured run. Relevant memories scored 0.4502 and 0.5513, so the exercise calibrated the threshold to 0.35; TypeScript reproduced those scores. The lesson is to calibrate against observed distributions rather than assume a universal cutoff.
In the capstone:Eunomia's first release keeps no semantic memory of a customer's goals or circumstances; each turn's facts come from a fresh snapshot frozen as evidence. If conversation memory is added later, this lesson's rule holds: memories only choose what to look up, and every product figure is still fetched fresh from product data. Skill Reporter applies the same rule: memory chooses retrieval context, but final report figures are re-fetched from current sources.
The problem: a customer says “my partner's ISA,” “the joint account,” and later “that one I opened last year.” The agent must decide whether each phrase points to something already known or introduces something new. A pile of disconnected notes cannot reliably support that decision or preserve how a fact changed. Skill Reporter needs the same entity resolution when users alternate between aliases like “that backend Rust track,” “the infra report,” and a formal skill identifier.
Entity memory (a running record of the specific people, accounts, and goals mentioned so far, together with facts about each) gives the conversation a stable set of things. Entity resolution (deciding whether a new phrase such as “the joint one” refers to an existing entry or a new one) connects each mention to that set. The resolver can use names, ownership, account type, and nearby conversation context, but uncertain matches should remain uncertain rather than being forced.
Changing facts need fact supersession (marking an older fact out of date when a new fact replaces it, instead of deleting or silently overwriting it). Every version also carries provenance (where and when the fact came from, so it can later be traced and checked). The small resolver below matches known aliases, creates a new entity when none match, and refuses an ambiguous match; production matching can add account type and conversation context without removing that ambiguity branch.
from dataclasses import dataclass, replace
from datetime import datetime
@dataclass(frozen=True)
class Entity:
entity_id: str
aliases: frozenset[str]
@dataclass(frozen=True)
class Fact:
entity_id: str
key: str
value: str
observed_at: datetime
source_turn: int
current: bool = True
def normalise_mention(text: str) -> str:
return " ".join(text.casefold().split())
def resolve_or_create(mention: str, entities: list[Entity],
new_entity_id: str) -> tuple[str, list[Entity]]:
target = normalise_mention(mention)
matches = [entity for entity in entities
if target in {normalise_mention(alias) for alias in entity.aliases}]
if len(matches) == 1:
return matches[0].entity_id, entities
if len(matches) > 1:
raise ValueError("ambiguous entity mention")
created = Entity(new_entity_id, frozenset({mention}))
return created.entity_id, [*entities, created]
def supersede(facts: list[Fact], new_fact: Fact) -> list[Fact]:
history = [replace(fact, current=False)
if fact.entity_id == new_fact.entity_id and fact.key == new_fact.key
else fact for fact in facts]
return [*history, replace(new_fact, current=True)]
A NEW MENTION IS EXTRACTED → RESOLVED TO AN EXISTING ENTITY OR MADE INTO A NEW ONE → CHANGING FACTS KEEP CURRENT AND SUPERSEDED VERSIONS WITH PROVENANCE
A real finding worth knowing: the TypeScript port reached a live structured-output schema rejection because a defaulted Zod field had been omitted from the schema's required list. Defaults in application code do not necessarily make a field optional to an external structured-output API; the generated schema must satisfy that API's rules.
In the capstone:Eunomia's first release does not keep a per-conversation entity graph. A reference such as “my other ISA” is resolved against the holdings in that turn's snapshot, each with its own holding reference, and a reference that cannot be resolved to one holding ends with a person rather than a guess. Any balance Eunomia repeats comes from the frozen snapshot with its as-of time, and the verifier rejects any figure that is not in it. Skill Reporter uses the same entity-memory pattern so references like “that other dashboard skill” resolve to one canonical skill ID before retrieval.
Lesson 49
Updating Search Indexes Safely with RRF
The problem: rebuilding an entire search index because one interest rate changed is slow and wasteful. Merely adding the new version is worse: the old rate remains searchable, so the agent can still quote withdrawn information. An update must remove precisely what became stale, add precisely what changed, and preserve fair hybrid ranking. Skill Reporter has the same correctness risk when one skill definition or demand tier changes but stale versions remain retrievable.
Search works on a chunk (a small passage cut from a larger document) rather than a whole product sheet. Cache invalidation (removing stored results that are no longer true so they cannot be served again) starts with a manifest that records every chunk owned by a document. A content hash (a short fingerprint calculated from a chunk's text) makes a text change overwhelmingly likely to produce a new ID; an occurrence key keeps identical repeated chunks distinct. Comparing the old and new manifests identifies unchanged chunks to keep, stale chunks to delete, and new chunks to index.
The update must apply to both the dense index (the meaning-based store) and sparse index (the exact-word store) as one atomic commit, so readers see either the old version or the new version rather than a partial mixture. Content-derived IDs do not replace ownership metadata: the old document manifest is what makes stale IDs discoverable.
The query side uses Reciprocal Rank Fusion, or RRF (merging ranked lists from each result's position rather than its raw score). Rank starts at 1. Each result earns 1 ÷ (k + rank) from each list, and those contributions are added; k is a smoothing constant (a value that limits how sharply scores fall by rank), commonly 60. Dense and keyword scores can live on completely different scales because RRF never compares them directly.
from collections import defaultdict
from hashlib import sha256
from typing import Protocol
Manifest = dict[str, str]
class IndexTransaction(Protocol):
def delete_from_both(self, chunk_id: str) -> None: ...
def upsert_into_both(self, chunk_id: str, text: str) -> None: ...
def commit(self, manifest: Manifest) -> None: ...
def content_id(document_id: str, occurrence: str, text: str) -> str:
digest = sha256(text.encode("utf-8")).hexdigest()[:12]
return f"{document_id}:{occurrence}:{digest}"
def replace_document(document_id: str, old_manifest: Manifest,
chunks: dict[str, str], transaction: IndexTransaction) -> Manifest:
new_manifest = {occurrence: content_id(document_id, occurrence, text)
for occurrence, text in chunks.items()}
old_ids, new_ids = set(old_manifest.values()), set(new_manifest.values())
for stale_id in old_ids - new_ids:
transaction.delete_from_both(stale_id)
for occurrence, new_id in new_manifest.items():
if new_id not in old_ids:
transaction.upsert_into_both(new_id, chunks[occurrence])
transaction.commit(new_manifest)
return new_manifest
def reciprocal_rank_fusion(rankings: list[list[str]], k: int = 60) -> list[str]:
scores: defaultdict[str, float] = defaultdict(float)
for ranking in rankings:
for rank, chunk_id in enumerate(ranking, start=1):
scores[chunk_id] += 1 / (k + rank)
return sorted(scores, key=lambda chunk_id: (-scores[chunk_id], chunk_id))
import { createHash } from "node:crypto";
type Manifest = Record<string, string>;
interface IndexTransaction {
deleteFromBoth(chunkId: string): void;
upsertIntoBoth(chunkId: string, text: string): void;
commit(manifest: Manifest): void;
}
function contentId(documentId: string, occurrence: string, text: string): string {
const digest = createHash("sha256").update(text).digest("hex").slice(0, 12);
return `${documentId}:${occurrence}:${digest}`;
}
function replaceDocument(documentId: string, oldManifest: Manifest,
chunks: Record<string, string>, transaction: IndexTransaction): Manifest {
const newManifest = Object.fromEntries(Object.entries(chunks).map(([occurrence, text]) =>
[occurrence, contentId(documentId, occurrence, text)]));
const oldIds = new Set(Object.values(oldManifest));
const newIds = new Set(Object.values(newManifest));
for (const staleId of oldIds) {
if (!newIds.has(staleId)) transaction.deleteFromBoth(staleId);
}
for (const [occurrence, newId] of Object.entries(newManifest)) {
if (!oldIds.has(newId)) transaction.upsertIntoBoth(newId, chunks[occurrence]);
}
transaction.commit(newManifest);
return newManifest;
}
function reciprocalRankFusion(rankings: string[][], k = 60): string[] {
const scores = new Map<string, number>();
for (const ranking of rankings) {
ranking.forEach((chunkId, index) => {
scores.set(chunkId, (scores.get(chunkId) ?? 0) + 1 / (k + index + 1));
});
}
return [...scores].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.map(([chunkId]) => chunkId);
}
UPDATE PATH: HASHES KEEP, DELETE, OR RE-INDEX PRECISE CHUNKS · QUERY PATH: DENSE AND SPARSE RANKS MERGE THROUGH RRF WITHOUT MIXING RAW SCORE SCALES
A real finding worth knowing: the verified update removed the stale chunk while leaving an unrelated chunk in place, directly demonstrating targeted eviction. The Python and TypeScript RRF scores also matched for the tested rankings. Those checks establish the intended behaviour for that case, while production still needs an atomic transaction or versioned index alias around publication.
In the capstone: when a savings rate changes, Eunomia publishes a new catalogue version, and any search index behind guidance lookup is staged and swapped atomically, so queries see either the complete old version or the complete new one. Each turn pins the catalogue version in its evidence bundle, so facts do not shift halfway through an answer. RRF keeps exact-name and meaning-based results balanced without hand-tuned score weights. Skill Reporter uses the same staged replacement model when skill definitions change.
Lesson 51
Combining Passage and Graph Retrieval
The problem: vector search can find a convincing passage from the wrong product, while a knowledge graph can confirm that it contains a relationship but does not contain the explanatory text a customer needs. “Sounds right” is not enough. A factual answer should require a matching passage and a source-linked graph relationship, and disagreement must stop the answer rather than invite a guess. Skill Reporter needs the same agreement rule so a report claim is published only when text evidence and graph facts both align.
RAG (Retrieval-Augmented Generation: having a model write from documents fetched at question time rather than from facts absorbed during training) supplies the passage. Graph-RAG (RAG that also checks a knowledge graph for explicit relationships) supplies a structured representation. Together they improve grounding (ensuring every factual claim can be traced to a specific retrieved source).
The central rule is cross-representation consistency (checking that a retrieved passage and a graph edge agree before using either). Both branches compare a shared canonical product ID, bank ID, and notice period rather than display names. Agreement shows that two representations of the source are consistent; it is not independent verification when both came from the same product sheet. Independent verification requires a separate authoritative source, such as a live product system or versioned source of record.
An entity link (the mapping from a passage mention to a graph entity) performs the join (matching records across the two representations). A mismatch or missing edge produces a decline or clarifying question and a review signal.
import asyncio
from dataclasses import dataclass
@dataclass(frozen=True)
class Evidence:
product_id: str
bank_id: str
notice_days: int
citation: str
@dataclass(frozen=True)
class GroundedNotice:
notice_days: int
passage_citation: str
graph_citation: str
async def grounded_notice(product_id: str) -> GroundedNotice:
passage, graph_fact = await asyncio.gather(
search_passage(product_id), lookup_graph(product_id))
if passage.product_id != graph_fact.product_id:
raise ValueError("product identity mismatch")
if passage.bank_id != graph_fact.bank_id:
raise ValueError("bank identity mismatch")
if passage.notice_days != graph_fact.notice_days:
raise ValueError("representations disagree on notice period")
return GroundedNotice(passage.notice_days, passage.citation, graph_fact.citation)
interface Evidence {
productId: string;
bankId: string;
noticeDays: number;
citation: string;
}
async function groundedNotice(productId: string): Promise<{
noticeDays: number;
passageCitation: string;
graphCitation: string;
}> {
const [passage, graphFact]: [Evidence, Evidence] = await Promise.all([
searchPassage(productId),
lookupGraph(productId),
]);
if (passage.productId !== graphFact.productId) throw new Error("product identity mismatch");
if (passage.bankId !== graphFact.bankId) throw new Error("bank identity mismatch");
if (passage.noticeDays !== graphFact.noticeDays) {
throw new Error("representations disagree on notice period");
}
return { noticeDays: passage.noticeDays, passageCitation: passage.citation,
graphCitation: graphFact.citation };
}
THE QUESTION RUNS THROUGH SEARCH AND GRAPH LOOKUP → BOTH REPRESENTATIONS MUST AGREE → AGREEMENT PRODUCES A CITED ANSWER; MISMATCH PRODUCES A SAFE DECLINE AND REVIEW FLAG
Run the passage lookup and graph lookup at the same time. Serial execution adds both latencies (the waiting time for each operation); parallel execution pays roughly for the slower branch. Python expresses this with asyncio.gather, while TypeScript uses Promise.all.
A real finding worth knowing: the TypeScript agent completed a verified two-hop graph traversal that the Python run did not, and its raw tool outputs preserved both hops. That is evidence about the observed execution path, not proof that every graph edge or source fact is independently correct.
In the capstone:Eunomia's first release grounds on a simpler rule: every figure and claim in an answer must come from the turn's frozen evidence bundle (snapshot, catalogue rows and guidance passages), and the verifier rejects anything else. Requiring a retrieved passage (Lesson 14) and a source-linked graph relationship (Lesson 21) to agree on canonical product, bank and notice data is deferred until a product graph exists; authoritative freshness still comes from the versioned product source. When evidence is missing or contradictory, Eunomia steps down to a person instead of answering from memory. Skill Reporter applies the same cross-representation check before stating which skill produced or supports a report claim.
Part III Through-Line
From Retrieval to Grounded, Current Facts
Part III is one chain across both domains. Lesson 14 fuses dense and sparse retrieval. Lesson 21 extracts graph facts from source text. Lessons 28 and 34 preserve and resolve conversational memory. Lesson 49 keeps indexes current as sources change. Lesson 51 joins passage and graph evidence so the agent answers only when both representations agree.
Part IV
Many Agents, One Goal (Multi-Agent Systems)
Parts I–III built one agent that can think, use tools and remember. This part begins where one agent stops being enough: when a decision needs a second opinion, a majority vote, faster independent work, a shared view of events, or protection against two agents overwriting the same data. Each lesson starts with the failure caused by working alone and adds the smallest multi-agent pattern that fixes it. Eunomia, a fintech savings-assistant AI agent, adopts those patterns one at a time, beginning with a worker and a separate quality auditor.
Dual-domain map for this part: every multi-agent coordination pattern shown for Eunomia (fintech) is meant to transfer to Skill Reporter.
Eunomia domain: worker/auditor hand-off, consensus voting on regulated-advice classification, concurrent balance/rate/goal lookups, pub/sub coordination, and arbitrated writes to a shared savings goal.
Skill Reporter domain: worker/auditor hand-off on generated skill reports, consensus voting on skill-demand classification, concurrent skill-catalogue/report-memory lookups, pub/sub coordination between report and notification agents, and arbitrated writes to a shared skill-definition index.
Interlink chain: Lesson 9 establishes worker→auditor review, Lesson 15 strengthens decisions with thresholded consensus, Lesson 18 reduces latency with concurrent specialists, Lesson 36 decouples coordination with events, and Lesson 45 protects shared writes from races.
Lesson 9
Multi-Agent Hand-Off & Verification
The problem: if Eunomia evaluates its own draft, the same assumptions that produced the answer can approve it, allowing risky or unsupported guidance through with high confidence. Skill Reporter has the same self-review bias when one model both writes and judges report quality.
The smallest useful separation is a worker agent (the agent whose job is to produce the first draft) followed by an auditor agent (a separate agent with different instructions whose only job is to approve or reject that draft). The worker is encouraged to solve the customer's problem; the auditor is encouraged to look for reasons the proposed answer should not be sent. Those are deliberately different jobs.
The connection between them is a hand-off (the moment one agent passes its output to another as structured data rather than loose chat text). In this pattern, the auditor receives the worker's generated title, stack and code, then returns a verdict schema (a fixed decision form such as approved: true/false and reasons: [...]). A fixed form matters because trusted application code can check a known structure directly.
QUESTION → WORKER DRAFT → INDEPENDENT AUDITOR VERDICT → APPROVE, RETRY WITH REASONS, OR USE A SAFE FALLBACK
The workflow uses one worker call followed by one auditor decision, with bounded retry and a safe holding reply if approval never arrives. Malformed, missing or ambiguous approval must never count as permission.
const eunomiaReply = await deliver(
"I have £400 left monthly; should I overpay my mortgage or top up ISA?",
eunomiaWorker,
eunomiaAuditor,
)
const skillReporterReply = await deliver(
"Should we publish a high-demand alert for Rust backend roles this week?",
skillReporterWorker,
skillReporterAuditor,
)
Separation only helps when it is real. Giving the auditor the worker's memory, prompt and incentives creates two names for nearly the same opinion, not an independent check.
Use the same review contract in both Python and TypeScript: worker draft, independent auditor decision, bounded retry, then safe holding reply if approval never arrives.
A real finding worth knowing: the separate auditor rejected five of ten generated examples in the Python run and six of ten in the TypeScript run. Those results show that a second pass can catch problems, but they do not establish how a retry loop or malformed verdict would behave. Application-side schema validation should therefore reject unreadable verdicts rather than letting a model certify its own output as valid.
In the capstone:Eunomia applies the worker–auditor split without a second agent: on the composed step the model drafts a plain explanation of holdings, products or guidance (never advice), and the code verifier acts as the auditor, checking every figure and claim against frozen evidence before a customer can see it; calibrated rubric judges in the quality suite audit tone offline. This hand-off is the base pattern on which every later lesson in this part builds. Skill Reporter applies the same hand-off before any generated skill report reaches a reporter.
Lesson 15
Multi-Agent Majority Voting
The problem: Eunomia can produce different outputs for the same prompt across runs, so one-shot decisions can accept unlucky variance. Skill Reporter faces the same instability in report scoring and recommendations unless agreement is measured across independent runs.
A swarm (a group of agents, often copies of the same agent, that receive the same task separately) turns one uncertain response into several responses. These responses can still share the same blind spots because they come from the same model and prompt. A consensus vote (choosing the answer that most agents gave instead of trusting any one agent) then selects the strongest shared result. This is useful for bounded decisions such as intent labels, risk categories or yes/no classifications; it is not a guarantee that the majority is correct.
Acceptance needs an agreement threshold (the minimum number of matching votes required before the system trusts a result, such as at least three of five votes). If agents can time out, a separate minimum-response rule should say how many must participate. Workers should return fixed labels whenever possible; treating free-form answers as equivalent can accidentally merge materially different amounts, currencies or risk categories. In Eunomia, labels might be regulated_advice, factual_account_query, and general_info. In Skill Reporter, labels might be high_demand_skill, emerging_skill, and low_signal. A tie must always produce “no winner” rather than depend on which item the program encounters first.
ONE TASK FANS OUT TO FIVE SEPARATE AGENTS → FIXED LABELS ARE VALIDATED → VOTES ARE TALLIED → THE AGREEMENT THRESHOLD ACCEPTS OR ESCALATES
The five agents must not copy one another's intermediate work, because then five votes merely repeat one initial mistake. Each submits a fixed final label without seeing the others' outputs. The tally accepts a unique winner only when that winner meets the configured agreement threshold; a tie or a winner with too few matching votes becomes an escalation or safe reply instead of a guessed result.
from collections import Counter
from typing import TypeVar
Label = TypeVar("Label", bound=str)
def consensus(answers: list[Label], minimum_matching_votes: int = 3) -> Label | None:
counts = Counter(answers)
highest = max(counts.values(), default=0)
winners = [
answer for answer, votes in counts.items() if votes == highest
]
if highest < minimum_matching_votes or len(winners) != 1:
return None
return winners[0]
fintech_votes = [
"regulated_advice",
"regulated_advice",
"factual_account_query",
"regulated_advice",
"general_info",
]
skill_reporter_votes = [
"high_demand_skill",
"high_demand_skill",
"emerging_skill",
"high_demand_skill",
"low_signal",
]
print(consensus(fintech_votes)) # regulated_advice
print(consensus(skill_reporter_votes)) # high_demand_skill
A majority is evidence of agreement, not proof of truth. If every agent shares the same bad source or misleading prompt, the whole swarm can agree on the same wrong answer.
This lesson uses deterministic fixed-label tallying in both Python and TypeScript: multiple agents vote independently, then application code applies one explicit threshold rule.
A real finding worth knowing: the same model and question produced confident but wrong FastMCP votes in the Python run, while the TypeScript run voted for the correct LangGraph answer. Multiple agents can repeat one systematic error, so agreement is not proof of truth. A deterministic tally can make the counting rule predictable, but it cannot repair bad evidence or correlated model mistakes.
In the capstone:Eunomia's first release does not run several voting agents on each message. The agreement-threshold idea appears as the routing policy's confidence threshold: a question-type classification below the threshold, including a possible request for regulated advice, goes to a person rather than being guessed, and the advice-line scenarios check that rule on every relevant change. Independent voting stays an option if a single classifier proves unstable. Skill Reporter follows the same threshold-then-person rule for skill-demand labels before drafting outbound reporting guidance.
Lesson 18
Concurrent Sub-Agent Workflows
The problem: Eunomia can serialize work that could run in parallel, increasing response time even when subtasks are independent. Skill Reporter has the same latency penalty when independent report stages are forced through one worker path.
A sub-agent (a smaller agent assigned one well-defined piece of a larger task) lets the system divide the job by responsibility. The planner uses fan-out / fan-in (sending independent pieces to several sub-agents at once, then gathering their results back in one place). Because the checks do not depend on each other, they can use concurrency (allowing several pieces of work to be in progress at the same time rather than waiting for each to finish).
When all available results return, an aggregator (the step that combines separate sub-agent results into one final answer) builds a coherent draft. In the sequential version, total waiting time is roughly the sum of every check. In the concurrent version, network waits overlap, so total time can be closer to the slowest single check plus the cost of starting and combining the work. This does not by itself prove that CPU work ran simultaneously.
SEQUENTIAL WORK ADDS EVERY WAIT; CONCURRENT WORK FANS OUT AND OVERLAPS NETWORK WAITS, THEN FANS IN AT AN AGGREGATOR THAT PRESERVES PARTIAL RESULTS
Concurrent execution changes failure handling. A single timeout must not erase two useful successes. Each sub-agent therefore returns either a value or a clearly marked error, and the aggregator is told exactly which evidence is missing. It may produce a cautious partial draft, request the missing lookup again or stop, but it may not describe incomplete evidence as complete.
Concurrency does not mean “ignore failures.” It means failures are isolated to the branch where they occurred, made visible, and handled when the results come back together.
Use the same concurrent fan-out/fan-in shape in both Python and TypeScript. Expect moderate latency improvement from overlapping waits, not linear speedup.
A real finding worth knowing: the Python run was about 20% faster with concurrent requests, while the repeated TypeScript comparison improved by about 11%. Both default asyncio.gather(...) and Promise.all(...) surface a branch failure instead of returning a complete array of successes. If an aggregator must retain partial results, each branch must catch and represent its own failure before those operations combine the results, as the wrappers above do.
In the capstone: when a question type needs more than one source, Eunomia's evidence planner can call readSnapshot, queryCatalogue and lookupGuidance at the same time, then freeze the results into one evidence bundle. Any answer built from that bundle still passes the verifier before the customer sees it. Skill Reporter uses the same fan-out/fan-in pattern to gather skill catalogue data, report memory, and policy notes in parallel before synthesis.
Lesson 36
Pub/Sub Agent Coordination
The problem: as Eunomia and Skill Reporter add specialized agents, direct peer-to-peer messaging creates brittle coupling and missed updates. Adding one agent can require rewiring many others, raising change risk and making responsibilities hard to reason about.
A message bus (a shared noticeboard to which agents post messages and from which agents read them instead of contacting one another directly) removes that web of direct one-to-one connections. The bus supports publish / subscribe, or pub/sub (a pattern in which agents publish messages to named topics and any agent subscribed to a topic receives them without the sender knowing who is listening). Lesson 9's worker and auditor are two of the agents whose messages now flow over this bus rather than being passed directly between them.
Each message is an event (a short, structured record that something happened, such as goal_updated). A real bus may deliver the same event more than once, so subscribers must make repeated delivery harmless. The in-memory set below suppresses a duplicate only when deliveries are sequential in one running process. It is not a general idempotency guarantee (a promise that repeating an operation has no additional effect): concurrent copies can both pass the check, a crash can occur after the audit but before the identifier is saved, and a restart clears the set. Stronger guarantees need durable atomic claim-and-complete state and a downstream operation designed for safe retries.
AGENTS PUBLISH STRUCTURED EVENTS TO TOPICS → THE MESSAGE BUS DECOUPLES SENDERS FROM RECEIVERS → SUBSCRIBERS PROCESS EVENTS AND HANDLE REPEATED DELIVERY EXPLICITLY
Decoupling lets a notification agent or audit log join later without changing the worker. It does not, however, create a saved history or a guaranteed delivery order. If an agent must recover older events, the system has to store them durably and send them again during recovery. The sample bus demonstrates routing only; it does not establish behavior for late subscribers, duplicates, delivery order or slow subscribers.
from typing import TypedDict
class DraftReady(TypedDict):
event_id: str
draft_id: str
processed_event_ids: set[str] = set()
async def on_draft_ready(event: DraftReady) -> None:
if event["event_id"] in processed_event_ids:
return
await audit(event["draft_id"])
processed_event_ids.add(event["event_id"])
async def publish_draft_ready(event: DraftReady) -> None:
await bus.publish("draft_ready", event)
interface DraftReady {
eventId: string
draftId: string
}
const processedEventIds = new Set<string>()
async function onDraftReady(event: DraftReady): Promise<void> {
if (processedEventIds.has(event.eventId)) return
await audit(event.draftId)
processedEventIds.add(event.eventId)
}
await bus.publish("draft_ready", event)
A bus shares news, not necessarily history. If an agent needs past events to rebuild its state, durable storage and explicit redelivery must be designed.
Use the same pub/sub contract in both Python and TypeScript, and ensure nested publications are explicitly awaited so downstream subscribers see complete event chains.
A real finding worth knowing: the Python demonstration created tasks without awaiting them and therefore needed an explicit wait for a nested publication to finish. The TypeScript promise chain naturally awaited its nested publication. That difference is about completion tracking in these implementations; it is not evidence for duplicate handling, late-subscriber behavior, delivery order or slow-subscriber behavior.
In the capstone:Eunomia's first release is one service with no separate agents, so it needs no message bus between them. The same decoupling appears at its edges: a turn records typed events through the TraceSink port and sends review items to the ReviewInbox port without knowing who consumes them. A bus carrying events such as draft_ready is deferred until separate agents or services need to coordinate. Skill Reporter uses the same event contracts so report-generation, review, and notification agents evolve independently.
Lesson 45
Central Write Arbitration for Concurrent Write Hazards
The problem: when Eunomia or Skill Reporter agents update shared records concurrently, one write can overwrite another without warning. This silent conflict can corrupt customer or reporting state unless update ordering and conflict checks are explicit.
This is a concurrent write hazard (the risk that overlapping writes to the same resource leave it wrong or internally inconsistent). It often appears as a race condition (a bug whose result depends on which operation happens to finish first, making it intermittent and difficult to reproduce). Both agents can read version 3, calculate different updates, and then save in succession; the second save overwrites the first even though both calls reported success.
An arbiter (one coordination component that receives write requests for a shared resource) gives participating writers one controlled entrance. It can keep a separate queue for each record so requests for one record are handled in order. The correctness boundary, however, is the shared store's atomic version check, also called optimistic locking (one indivisible store operation that writes only if the record still has the expected version). A local queue is only an efficiency measure: another arbiter replica or a writer that bypasses it can still race. A request rejected by the store must re-read the latest record, reconsider its change and retry with the new version. The arbiter does not replace the worker/auditor hand-off from Lesson 9 or the bus-based coordination from Lesson 36; it adds a third guarantee — that concurrent writes to one shared record cannot silently overwrite each other.
OVERLAPPING WRITES CAN LOSE DATA; THE SHARED STORE MUST CHECK THE EXPECTED VERSION AND WRITE ATOMICALLY, WHILE STALE REQUESTS RE-READ BEFORE RETRYING
The arbiter need not make the business decision itself. Its narrower job is to submit the expected version and complete replacement value to an atomic store operation. A local queue can reduce conflicts for requests that reach one process, and requests for different records can still proceed concurrently, but the store must reject stale versions even when writes arrive through another process.
from dataclasses import dataclass
from typing import Any
@dataclass(frozen=True)
class WriteRequest:
record_id: str
expected_version: int
change: dict[str, Any]
async def apply(request: WriteRequest) -> Record | Stale:
current = await store.read(request.record_id)
updated = {
**current.data,
**request.change,
"version": current.version + 1,
}
saved = await store.write_if_version(
request.record_id,
expected_version=request.expected_version,
value=updated,
)
return saved if saved is not None else STALE
One normal execution thread is not the same as freedom from races. Whenever an operation pauses to await input or output, another operation can read or write the same state.
The versioned-write design above is the operational model for this lesson: the store enforces an atomic expected-version check, stale writes are rejected, and callers must re-read before retrying.
A real finding worth knowing: a model can propose an execution plan, but the application still needs deterministic enforcement. The rule check must verify write ordering explicitly (for example, WRITE before INVALIDATE) and must reject stale versions at the store boundary.
In the capstone:Eunomia's first release is read-only, so no agent writes to a customer's savings goal and there is no shared write to arbitrate. When write actions arrive in a later release, this is the pattern they need: an arbiter coordinates concurrent requests, the shared store rejects stale versions atomically, and a check confirms the saved state matches what the customer was told. Skill Reporter applies the same arbiter-plus-atomic-check pattern to updates on shared skill-definition state.
Eunomia after Part IV: its first release separates drafting from checking, with the verifier as auditor (Lesson 9), sends a low-confidence classification to a person rather than trusting one uncertain run (Lesson 15), gathers separate evidence concurrently (Lesson 18), and decouples traces and review items through ports rather than direct references (Lesson 36). Shared writes through an arbiter backed by atomic store checks (Lesson 45) wait for the write actions of a later release. Nothing reaches the customer without passing the verifier, and no single component coordinates every concern. Skill Reporter runs the same five-lesson chain over its own worker, auditor, skill-demand labels, report/notification agents, and skill-definition store.
Part V
Keeping Agents Running (Resilience & Concurrency)
Building an agent that works once is only the beginning. A production agent must keep reaching a safe outcome—including refusal or handoff—when an upstream service slows down, a model becomes unavailable, generated code breaks, or two services wait on each other. These seven lessons build that resilience from controlled parallel work, through rate limits and circuit breakers, to deliberate fallbacks and distributed deadlock detection.
Dual-domain map for this part: each resilience control applies to Eunomia (fintech) and Skill Reporter the same way.
Interlink chain: Lesson 8 caps concurrent work, Lesson 29 caps outbound pace, Lesson 35 cuts failing dependencies, Lessons 50 and 56 route to safer alternatives, while Lessons 27 and 54 contain local execution and cross-agent stalls.
Lesson 8
Async Concurrency & Batch Processing
The problem: Eunomia often needs multiple independent checks before replying (balance, rates, goals, and recent transactions). Running those calls one by one makes the customer wait for avoidable latency. Skill Reporter has the same bottleneck when it gathers catalogue evidence, memory evidence, and policy evidence sequentially instead of in parallel.
Async (asynchronous code that can start a slow operation, do other work while it waits, and resume when the result arrives) lets independent calls overlap. That creates concurrency (several tasks making progress during the same period by taking turns whenever another task is waiting), rather than strict one-by-one execution. Put the independent requests into a batch (a group of requests launched together and collected as one set), then gather every outcome before composing the answer.
import asyncio
from collections.abc import Awaitable, Callable
async def run_batch(
items: list[str], fetch: Callable[[str], Awaitable[str]], limit: int = 3
) -> list[str | Exception]:
semaphore = asyncio.Semaphore(limit)
async def limited(item: str) -> str:
async with semaphore:
return await fetch(item)
return await asyncio.gather(*(limited(item) for item in items), return_exceptions=True)
ONE REQUEST → CONTROLLED PARALLEL CALLS → SETTLE EVERY RESULT → COMBINE WHAT SUCCEEDED AND EXPLAIN WHAT DID NOT
Unbounded concurrency merely replaces waiting with overload. A semaphore (a counter that permits only a fixed number of tasks to run at once) keeps a large batch from firing thousands of calls together. The useful result is not “everything succeeded”; it is a complete ledger of which calls succeeded and which failed, so the agent can still answer from the available facts.
A real finding worth knowing: the default “wait for all” helper in either language rejects the entire batch when one call fails. The other calls may continue in the background, but their results are never collected. Use the “settle all” variant so every call becomes an explicit success or failure, and put a concurrency cap in place before launching a large batch.
In the capstone:Eunomia's evidence planner runs the capability calls a question type needs with overlap, while a semaphore admits only three calls at once. Latency is therefore set by the longest call under that cap, rather than the sum of every call, and a missing source is recorded in the bundle so the answer sequence steps down instead of the whole turn failing, while a malformed source stops the turn safely before any model call. Skill Reporter uses the same capped fan-out to collect report evidence without saturating its dependencies.
Lesson 27
Self-Healing Code & Auto-Repair Loops
The problem: Eunomia can generate a savings-projection helper that looks correct but crashes on edge cases. Without an automatic repair loop, an operator must manually feed each crash back to the model. Skill Reporter faces the same operational drag when generated report-transformation code fails on real input variations.
A safe repair system runs generated code in a sandbox (an isolated environment with no access to real files, networks or customer data, and with strict time and memory limits). If the run fails, it captures the stack trace (the crash report showing which line failed and why) and starts a repair loop (run, capture the error, ask for a correction, then run again up to a fixed attempt limit).
async def repair_until_valid(code: str, attempts: int = 3) -> str:
last_error = ""
for attempt in range(attempts):
result = await run_in_sandbox(code, timeout_seconds=5)
if result.exit_code == 0 and acceptance_test(result.stdout):
return result.stdout
last_error = result.stderr or "acceptance test failed"
if attempt + 1 < attempts:
code = await repair_model(code=code, error=last_error)
raise RuntimeError(f"repair failed: {last_error}")
async function repairUntilValid(code: string, attempts = 3): Promise<string> {
let lastError = "";
for (let attempt = 0; attempt < attempts; attempt++) {
const result = await runInSandbox(code, { timeoutMs: 5_000 });
if (result.exitCode === 0 && acceptanceTest(result.stdout)) {
return result.stdout;
}
lastError = result.stderr || "acceptance test failed";
if (attempt + 1 < attempts) {
code = await repairModel({ code, error: lastError });
}
}
throw new Error(`repair failed: ${lastError}`);
}
GENERATE → RUN IN A LOCKED-DOWN SANDBOX → PROVE CORRECTNESS → REPAIR WITH THE ERROR, OR STOP AFTER A FIXED LIMIT
The decisive check is an acceptance test (a test written before generation that defines the correct result). A process exit code (the numeric status a program returns when it stops) can prove only that the program stopped without reporting an error; it cannot prove the answer is right. The loop must also terminate runaway child processes (subprocesses that outlive or ignore the parent operation's limit) when its time limit expires, although Python and TypeScript require different process-control details to do that reliably.
“Self-healing” does not mean unlimited retries or permission to run generated code on the host. It means a small, observable number of attempts inside a hostile-by-default sandbox, followed by a safe refusal.
A real finding worth knowing: a model may appear to repair a crash by wrapping the failing line in a catch-all that hides the error. The script then exits cleanly while returning the wrong answer. Count a repair as successful only when a real acceptance test passes, never merely because the crash disappeared. Also verify that the language-specific timeout path actually kills a runaway child process.
In the capstone:Eunomia's first release generates no code and calculates no projections at runtime; Part X keeps this code-repair theme outside the serving path. If generated savings-projection code is added later, it is repaired and rerun only inside a sandbox, and if the acceptance test still fails when the attempt limit is reached, Eunomia says it cannot calculate the projection right now rather than presenting a plausible but wrong number. Skill Reporter applies the same sandboxed repair loop to generated report-transformation code.
Lesson 29
Token Bucket Rate Limiting
The problem: concurrency makes Eunomia faster, but it can also burst model and upstream calls hard enough to hit provider limits during customer peaks. The result is avoidable 429 failures on valid requests. Skill Reporter sees the same quota spike risk during scheduled reporting windows unless outbound pace is controlled.
A rate limit (the maximum number of requests, or amount of model text, accepted during a time window) is commonly enforced with HTTP 429 (the standard “Too Many Requests” response). Rather than waiting to be rejected, the agent can pace itself with a token bucket (a container of request permits that has a fixed capacity, refills steadily, and makes a request wait when no permit is available). These permits are not the text tokens used to measure model input and output.
import asyncio
from time import monotonic
class TokenBucket:
def __init__(self, capacity: int, rate: float) -> None:
if capacity <= 0 or rate <= 0:
raise ValueError("capacity and rate must be positive")
self.capacity, self.rate, self.tokens = capacity, rate, float(capacity)
self.updated = monotonic()
self.lock = asyncio.Lock()
async def acquire(self) -> None:
while True:
async with self.lock:
now = monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return
delay = (1 - self.tokens) / self.rate
await asyncio.sleep(delay)
class TokenBucket {
private tokens: number;
private updated = performance.now();
constructor(private capacity: number, private ratePerSecond: number) {
if (capacity <= 0 || ratePerSecond <= 0) {
throw new RangeError("capacity and rate must be positive");
}
this.tokens = capacity;
}
async acquire(): Promise<void> {
for (;;) {
const now = performance.now();
const elapsed = (now - this.updated) / 1_000;
this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.ratePerSecond);
this.updated = now;
if (this.tokens >= 1) {
this.tokens -= 1;
return;
}
await new Promise((resolve) => setTimeout(resolve, ((1 - this.tokens) / this.ratePerSecond) * 1_000));
}
}
}
REQUESTS TAKE PERMITS FROM A FINITE BUCKET → THE BUCKET REFILLS STEADILY → EXCESS CALLS WAIT LOCALLY INSTEAD OF REACHING HTTP 429
Refill calculations must use a monotonic clock (a timer that only moves forward and is unaffected by corrections to the computer's calendar time). Capacity allows a small, intentional burst; refill speed controls the sustained rate. When no permit is available, these simple implementations make callers sleep and compete again; a separate first-in, first-out queue is needed when arrival-order fairness matters.
A real finding worth knowing: a bucket refilled from wall-clock time (calendar time that can jump when the system clock is corrected) can grant a flood of permits or stop refilling when that clock is corrected. Use a monotonic clock. Separately, a request-count bucket cannot enforce a provider's text-volume limit: a few very long prompts may still cause 429 responses, so model-text limits need their own weighted accounting (charging each request in proportion to the text volume it consumes).
In the capstone: when many customers ask Eunomia questions at once, a bucket inside the model gateway keeps model calls beneath the provider's accepted pace. Customers may wait briefly inside Eunomia, but these snippets do not guarantee first-in, first-out service; add a real queue when that fairness is required. Skill Reporter uses the same token-bucket pacing to avoid upstream quota spikes during reporting cycles.
The problem: when a dependency starts failing, Eunomia can keep calling it and waiting for timeouts, spreading slowdown across customer sessions. At the same time, cooperating agents can each wait for the other and deadlock. Skill Reporter has the same dual risk when report assembly depends on services that are failing or waiting on each other.
A cascading failure (one broken service making its callers slow or broken until the damage spreads through the system) is contained by a circuit breaker (a guard that counts failures and temporarily rejects new calls after a threshold). Its normal closed state passes calls through. Its open state fails immediately during a cool-down, and its half-open state (a cautious recovery state that admits one test request) decides whether normal traffic is safe again.
from collections.abc import Awaitable, Callable
from time import monotonic
class CircuitBreaker:
def __init__(self, threshold: int = 5, cooldown: float = 10) -> None:
self.threshold, self.cooldown = threshold, cooldown
self.failures, self.opened_at, self.probing = 0, 0.0, False
async def call(self, operation: Callable[[], Awaitable[str]]) -> str:
now = monotonic()
if self.failures >= self.threshold:
if now - self.opened_at < self.cooldown or self.probing:
raise RuntimeError("circuit open")
self.probing = True
try:
value = await operation()
except Exception:
self.failures += 1
self.opened_at, self.probing = now, False
raise
self.failures, self.probing = 0, False
return value
FAILURES TRIP THE BREAKER CLOSED → OPEN → ONE HALF-OPEN PROBE; TIMEOUTS AND FIXED ORDERING BREAK SIMPLE CROSS-AGENT WAITS
Circuit breakers contain calls to unhealthy dependencies; a deadlock (two or more workers each waiting for something held by another, so none can continue) needs a different guard: bounded waits, release on timeout, and one fixed ordering (a shared rule that every worker follows when acquiring several resources). These measures are deliberately simple. They prevent an indefinite hang even before the system gains the full distributed detector introduced in Lesson 46.
A real finding worth knowing: a naive half-open implementation often allows every request arriving at the recovery moment through, even though it intends to allow “the next request.” That surge can knock the recovering service down again. The half-open probe must be protected so one request is in flight (started but not yet completed) per process. A fleet-wide single probe requires a shared atomic store or distributed lease; production breakers also tag state generations so a late completion from an older generation cannot reset newer state.
In the capstone:Eunomia's model gateway keeps a circuit breaker per provider: after repeated failures it stops calling that provider for a cool-down and moves to the next one in the chain, or the answer steps down a step, so customers do not wait through repeated timeouts. A store that keeps failing makes /readyz report the instance unready. The first release has no cooperating agents that could wait on each other, so this lesson's wait-graph half is not needed yet. Skill Reporter mirrors this breaker discipline for report and policy services.
Lesson 37
Autonomous Model Cascades & Cost-Aware Escalation
The problem: Eunomia cannot run every request on the most expensive model without unsustainable cost, but routing all requests to a cheap model degrades quality on regulated or high-risk questions. Skill Reporter has the same trade-off: routine summaries are cheap, but high-stakes publication checks need stronger reasoning.
A model cascade (an ordered sequence of models from cheapest to most capable, tried until an answer passes) starts small and escalates only when necessary. After each attempt, a quality gate (an automatic, programmatic check that decides whether an answer is acceptable) either returns the answer or triggers escalation (sending the same task to the next, more capable model).
from collections.abc import Awaitable, Callable
Model = Callable[[str], Awaitable[dict[str, object]]]
class RetryableModelError(Exception):
pass
async def run_cascade(question: str, models: list[Model]) -> dict[str, object]:
failures: list[str] = []
for model in models:
try:
answer = await model(question)
except RetryableModelError as error:
failures.append(type(error).__name__)
continue
if quality_gate(answer):
return answer
raise RuntimeError(f"no model produced an acceptable answer ({len(failures)} unavailable)")
def quality_gate(answer: dict[str, object]) -> bool:
citations = answer.get("citations")
return (
isinstance(answer.get("text"), str)
and isinstance(citations, list)
and all(isinstance(citation, str) for citation in citations)
)
type Answer = { text: string; citations: string[] };
type Model = (question: string) => Promise<unknown>;
class RetryableModelError extends Error {}
async function runCascade(question: string, models: Model[]): Promise<Answer> {
let unavailable = 0;
for (const model of models) {
try {
const answer = await model(question);
if (qualityGate(answer)) return answer;
} catch (error) {
if (!(error instanceof RetryableModelError)) throw error;
unavailable += 1;
}
}
throw new Error(`no model produced an acceptable answer (${unavailable} unavailable)`);
}
function qualityGate(value: unknown): value is Answer {
if (typeof value !== "object" || value === null) return false;
const answer = value as Partial<Answer>;
return (
typeof answer.text === "string" &&
Array.isArray(answer.citations) &&
answer.citations.every((citation) => typeof citation === "string")
);
}
Only failures that the model adapter classifies as retryable should advance the cascade. Cancellation, authentication errors, and policy failures must propagate instead of being swallowed; retryable failures should be recorded for observability.
TRY THE CHEAP MODEL → CHECK THE OUTPUT → RETURN AN ACCEPTABLE ANSWER OR ESCALATE HARD CASES → FALL BACK SAFELY IF NO ATTEMPT PASSES
The relevant measure is cost per answer (the combined cost of every model attempted for one question, including rejected attempts). A cascade saves money only when the first model handles enough traffic and the gate is accurate enough to avoid needless escalation. Reliable gates inspect facts the program can verify, such as schema validity (whether the output has the required fields and value types), required fields, and whether cited figures match source data. The snippets demonstrate shape checks only; source-backed factual checks are still required before treating an answer as verified.
A model grading its own confidence is not an independent check. Confidence is generated text too, and a wrong answer can be delivered with complete certainty.
A real finding worth knowing: asking the cheap model “are you confident?” makes a poor quality gate because models can report high confidence on wrong answers. Program-verifiable checks are much stronger. A gate that is too strict creates the opposite failure: almost every question reaches the large model, so the cascade costs more than sending each question directly there.
In the capstone:Eunomia turns this into a cascade of answer modes rather than model sizes. “What is my balance?” is answered by a template from the frozen snapshot with no model at all; questions that need wording go to the composed step; and if a composed draft fails the objective gate (the verifier), Eunomia hands the customer to a person. Inside the composed step, the gateway's ordered provider chain handles the choice between providers. Skill Reporter uses the same gated fallback policy for report-quality checks.
Lesson 46
Distributed Deadlock Detection & Recovery
The problem: timeouts can break circular waits in Eunomia, but only after wasting the full timeout budget and without proving whether the system was truly deadlocked or just slow. As Eunomia spans more services, no single worker sees the full wait chain. Skill Reporter inherits the same visibility gap once report generation, validation, and publishing are distributed.
A distributed system (work spread across separate processes or machines that communicate over a network) needs a shared picture. Each worker reports waits to a wait-for graph (a live map whose dots are agents and whose arrow from A to B means “A is waiting for B”). Cycle detection (walking those arrows to find a path that returns to its starting point) can then identify a deadlock as soon as its final arrow appears.
The following snippets are single-process pseudocode for the cycle walk, limited to one active dependency per agent. A production distributed detector must apply edge updates atomically to a shared registry, support every simultaneous wait, attach an expiry to each edge, and remove edges on every exit path.
waits_for: dict[str, str] = {}
async def register_wait(agent: str, dependency: str) -> None:
waits_for[agent] = dependency
seen: set[str] = set()
current = agent
while current in waits_for:
if current in seen:
victim = min(seen, key=retry_cost)
waits_for.pop(victim, None)
await cancel_victim(victim)
return
seen.add(current)
current = waits_for[current]
async def stop_waiting(agent: str) -> None:
waits_for.pop(agent, None)
const waitsFor = new Map<string, string>();
async function registerWait(agent: string, dependency: string): Promise<void> {
waitsFor.set(agent, dependency);
const seen = new Set<string>();
let current: string | undefined = agent;
while (current !== undefined && waitsFor.has(current)) {
if (seen.has(current)) {
const victim = [...seen].sort((a, b) => retryCost(a) - retryCost(b))[0];
waitsFor.delete(victim);
await cancelVictim(victim);
return;
}
seen.add(current);
current = waitsFor.get(current);
}
}
function stopWaiting(agent: string): void {
waitsFor.delete(agent);
}
EACH AGENT REPORTS ITS ACTIVE WAIT → THE REGISTRY FINDS A CYCLE → ONE DELIBERATE VICTIM IS CANCELLED → THE REMAINING WORK CAN COMPLETE
Once a loop is found, victim selection (choosing which participant to cancel or restart so the rest can proceed) should consider retry cost and fairness. Always cancelling the same role can cause starvation (a worker being denied enough uninterrupted time to ever finish). Every registered edge also needs an expiry and must be removed on success, failure, cancellation, and timeout.
A real finding worth knowing: stale arrows create false deadlock alarms. An agent can finish or crash without removing its “I am waiting on X” entry, leaving a cycle that exists only in the registry. Give every entry an expiry time and run “stop waiting” on every exit path, including errors. Rotate or score victims as well; always choosing the same kind of agent can starve it indefinitely.
In the capstone:Eunomia's first release has no cooperating checks that can wait on each other, so distributed deadlock detection is not needed on its serving path; a per-turn budget and the one-ending-event rule already stop a turn from hanging. If separate checking services are added later, an event-driven detector can see the loop when the shared registry atomically accepts the closing edge, remove and cancel one selected side, and retry safely. Skill Reporter applies the same detector when report-synthesis and policy-validation branches create circular waits.
Lesson 50
Dynamic Agent Tool Fallback & Secondary Routing
The problem: Eunomia' primary data source can remain technically up while becoming too slow for a customer conversation. Waiting indefinitely for perfect freshness often harms trust more than a timely, clearly-labelled fallback. Skill Reporter faces the same decision when primary reporting data is slow during publication deadlines.
Latency (the time from sending a request to receiving its response) can be controlled with a routing deadline (an internal maximum wait before fallback begins). When the primary reaches that deadline, secondary routing (sending the work to a backup provider) chooses a faster source with known trade-offs, such as cached rather than live data. This 800-millisecond routing threshold is not itself a customer-facing service-level agreement.
START THE PRIMARY WITH A DEADLINE → TRIGGER FALLBACK AND REQUEST CANCELLATION AT THE DEADLINE → LABEL THE SECONDARY ANSWER'S FRESHNESS
The abandoned operation also needs cancellation (actively signalling slow work to stop so it releases connections, processing time, and cost). Racing a request against a timer changes which result the router uses; it does not necessarily stop the loser, so the abandoned promise or task must still be observed. Each primary breach should be logged and fed into the circuit breaker from Lesson 35, so repeated slowness eventually prevents wasteful primary attempts altogether. The secondary needs its own deadline and a refusal or handoff path; fallback is not permission to wait forever on a second dependency.
A real finding worth knowing: racing a slow request against a timer can trigger fallback at 800 milliseconds, but cancellation remains cooperative unless the client or transport enforces a hard timeout. A primary that ignores the signal may continue consuming connections and cost in the background. Observe its eventual completion, and use transport-level timeouts when the operation itself must stop at a wall-clock bound.
In the capstone: this lesson's fallback routing lives inside Eunomia's model gateway: when one provider misses its timeout, the gateway cancels the call and tries the next provider in the chain within the per-turn budget, and if the whole chain misses, the answer steps down to a person rather than leaving the chat waiting. Store data is not served from a stale cache in the first release; the snapshot's as-of time and the catalogue version in the evidence bundle say how fresh each fact is. Skill Reporter applies the same timeout-fallback chain and freshness disclosure on delayed report-data providers.
These protections reinforce one another: concurrency creates the bursts rate limiting controls; circuit breakers and secondary routing stop waits on unhealthy dependencies; graph-based detection improves on deadlock timeouts; and both repair loops and model cascades retry only until an objective check passes, then fall back safely. Together they help Eunomia respond safely when something upstream fails—including by refusing or handing off when no validated fallback exists.
Part VI
Security & Guardrails
A useful agent is not automatically a safe one. This part adds hard checks around replies, hostile prompts, generated patches, tool arguments, permissions, customer data, and human-review sampling. The theme throughout is simple: let AI propose, but make ordinary code, narrow authority, isolated storage, repeatable tests, and people decide what is allowed.
Dual-domain map for this part: every guardrail pattern shown for Eunomia is mirrored for Skill Reporter.
Skill Reporter domain: output guards on generated reports, injection interception, isolated red-team fuzzing, semantic payload validation for report tools, scoped permission tokens, tenant isolation, and deterministic human-review sampling.
Interlink chain: Lesson 13 blocks unsafe output, Lesson 20 blocks hostile inputs, Lesson 40 stress-tests those controls, Lessons 44 and 52 constrain tool authority, and Lessons 54 and 55 enforce tenant-safe retrieval and auditable human oversight.
Lesson 13
Programmatic Output Guardrails
The problem: Eunomia can draft a convincing financial reply that still leaks private account details, makes unsupported product claims, or phrases guidance in a way policy forbids. Asking another model to judge that draft only swaps one uncertain judgment for another. Skill Reporter has the same risk when generated report text can leak sensitive employer or candidate information.
The dependable final checkpoint is a programmatic guardrail (a rule written in ordinary code that checks an AI reply before it is sent). Each rule performs a deterministic check (a check that produces the same result whenever it receives the same input), so a known-bad draft cannot slip through because a model interpreted it differently this time. The small examples below choose to block rather than rewrite a failed draft.
Many first-line rules use pattern matching (searching text for known words, formats, or character sequences). Here the rules cover only one forbidden claim and one account-number shape; they are not general detectors for PII (personally identifiable information), account data, or unsafe fallback behaviour. The decision point must fail closed (block an action when a safety check fails or cannot finish). A checker timeout is therefore a blocked reply, not permission to send an unchecked one.
import re
from unicodedata import normalize
FORBIDDEN = (r"\bguaranteed return\b", r"\baccount \d{8}\b")
def check_output(draft: str) -> str:
canonical = " ".join(normalize("NFKC", draft).casefold().split())
violations = [rule for rule in FORBIDDEN if re.search(rule, canonical)]
if violations:
raise ValueError("reply blocked by output guardrail")
return draft
const forbidden = [/\bguaranteed return\b/u, /\baccount \d{8}\b/u];
export function checkOutput(draft: string): string {
const canonical = draft
.normalize("NFKC")
.toLocaleLowerCase("en-GB")
.replace(/\s+/gu, " ")
.trim();
if (forbidden.some((rule) => rule.test(canonical))) {
throw new Error("reply blocked by output guardrail");
}
return draft;
}
CUSTOMER MESSAGE → AI DRAFT → CODE-BASED CHECKS → SEND ONLY ON PASS; OTHERWISE BLOCK SAFELY AND RECORD A REDACTED AUDIT EVENT
A verified finding from the lesson: strict structured-output mode rejected the schema produced by z.boolean().default(false). The infrastructure-error branch also kept that failure distinct from a security block. The snippets above have a different, explicit limitation: Python case-folding and TypeScript locale-aware lowercasing are not identical, and neither normalizes punctuation.
In the capstone: every Eunomia draft passes code-based checks before it can reach the customer. The two rules shown here are only examples; production policy needs dedicated, tested detectors for PII, cross-customer account details, unsupported financial claims, and unsafe fallback behaviour. Skill Reporter applies the same deterministic output gate before publishing generated report text.
Lesson 20
AI Red Teaming & Attack Interception
The problem: Eunomia may follow a hostile prompt that asks it to ignore policy, expose hidden account data, or invoke a sensitive tool path. Discovering that weakness only when attacked in production is too late. Skill Reporter is equally exposed when injection attempts try to exfiltrate protected report inputs or bypass publication controls.
Red teaming (deliberately attacking your own system to discover security weaknesses) turns that risk into planned testing. Tests should include prompt injection (instructions designed to make an AI ignore or override the rules it was given) and a jailbreak (an attempt to persuade an AI to bypass its safety restrictions), not just malformed requests.
The first defence is attack interception (detecting and stopping a hostile request before it reaches sensitive data or tools). The snippets below demonstrate only a narrow first gate based on two regular expressions; regex matching is one layer, not sufficient attack detection. Replies and tool requests need separate final security checks because a message that passes the first gate can still lead to an unsafe action. Those later checks appear in the architecture diagram but are not implemented by these snippets.
import re
from unicodedata import normalize
ATTACKS = (r"ignore (all|previous) rules", r"show .*user.?s records")
def intercept_prompt(message: str) -> str:
canonical = normalize("NFKC", message).casefold()
if any(re.search(pattern, canonical) for pattern in ATTACKS):
raise PermissionError("hostile prompt blocked")
return message
async def handle_message(message: str) -> str:
return await run_agent(intercept_prompt(message))
HOSTILE TESTS → EARLY ATTACK DETECTOR → BLOCK OR PROCESS → FINAL CHECK ON BOTH REPLIES AND TOOL REQUESTS
A verified finding from the lesson: the tested detector blocked an obvious attack and allowed a legitimate request in both languages. Ambiguous and obfuscated prompts were not tested, so no broader detection claim follows from that result.
In the capstone:Eunomia is tested with prompt-injection and jailbreak attempts that try to expose another customer's account data, reveal PII (personally identifiable information), or trigger an unauthorized financial action. Every confirmed weakness becomes a repeatable security test. Skill Reporter keeps an equivalent injection/jailbreak corpus for skill-report workflows.
The problem: Eunomia defenders can hand-write only a small set of attack tests, while real attackers keep mutating wording, encoding, and strategy. Security needs broader automated exploration without giving generated tests or fixes direct production authority. Skill Reporter has the same need as report workflows become externally reachable.
Fuzzing (automatically trying many unusual or hostile inputs to find failures) expands a small seed library into a continuing search. An attacker agent (an AI assigned to generate and vary attacks against another system) tests an isolated target. A breach checker (a separate decision component that evaluates target responses against explicit evidence of a crossed boundary) decides whether an attempt succeeded.
After a verified breach, a patcher agent (an AI assigned to propose a defensive change after a verified failure) can draft a narrow guardrail change. That proposal must face both attack tests and a regression test (a test that ensures a fixed problem does not return and existing behaviour still works). Passing tests earns human review, never automatic deployment. The snippets below show only a minimal breach-detection core: three fixed variants and an exact response marker. The marker can misclassify a refusal that quotes it and miss a leak expressed without it; production verdicts need stronger evidence. The Python and TypeScript variant sets also differ, so shared test cases are required before comparing their behaviour. The diagram shows the larger attacker, patcher, test, and review architecture that is not implemented in these snippets.
from base64 import b64encode
from collections.abc import Awaitable, Callable
async def find_breach(
seed: str,
run_isolated: Callable[[str], Awaitable[str]],
) -> str | None:
variants = {seed, seed.swapcase(), b64encode(seed.encode()).decode()}
for attack in variants:
response = await run_isolated(attack)
if "PRIVATE_RECORD" in response:
return attack
return None
type IsolatedRunner = (prompt: string) => Promise<string>;
export async function findBreach(
seed: string,
runIsolated: IsolatedRunner,
): Promise<string | undefined> {
const variants = new Set([
seed,
seed.toUpperCase(),
Buffer.from(seed, "utf8").toString("base64"),
]);
for (const attack of variants) {
if ((await runIsolated(attack)).includes("PRIVATE_RECORD")) return attack;
}
return undefined;
}
ATTACKER VARIES TESTS IN ISOLATION → VERIFIED BREACH → PATCHER PROPOSES → SECURITY AND NORMAL-USE TESTS → HUMAN ALONE APPROVES
An automated patch is a candidate, not a decision. Keep production credentials out of the test environment and require a person to review the code, its evidence, and the behavior it might remove.
A verified finding from the lesson: eleven live attacks across the two languages found no breach. The Python patcher was then exercised with a simulated breach; the TypeScript patcher was not verified end to end. A negative attack run is useful evidence, not proof that no other attack can succeed.
In the capstone:Eunomia uses an isolated attacker-and-patcher loop to search for new ways to leak PII (personally identifiable information), cross customer boundaries, or request unauthorized actions, while tests and human approval remain mandatory before any proposed defense reaches production. Skill Reporter runs the same isolated attacker/patcher cycle against report-generation boundaries.
Lesson 44
Semantic Guardrails for FastMCP Tool Payloads
The problem: a Eunomia tool call can satisfy every schema field and type yet still be unsafe: it may target a forbidden resource, exceed policy limits, or point at another customer's account. Skill Reporter has the same semantic risk when payloads reference disallowed report sources, tenants, or publish scopes despite shape-valid JSON.
FastMCP (a framework for exposing application functions as tools that an AI agent can call) can validate the shape of a tool payload (the collection of argument names and values sent to a tool). Shape checking answers “is this a string?”; it does not answer “is this customer's string allowed to select that resource?”
That second question needs semantic validation (checking what supplied values mean and what effect they could have). Sensitive values should usually come from an allow-list (an explicit list of values or actions that are permitted, with everything else rejected), combined here with ownership and value-limit checks before real tool logic is reachable. If a richer payload later includes query text, filters, or nested values, those fields need their own validation; the examples below do not inspect fields they do not define.
from dataclasses import dataclass
ALLOWED_TABLES = {"balances", "transactions"}
@dataclass(frozen=True)
class ToolPayload:
table: str
account_id: str
limit: int
def validate_payload(payload: ToolPayload, owned_accounts: set[str]) -> None:
if payload.table not in ALLOWED_TABLES:
raise PermissionError("table is not allowed")
if payload.account_id not in owned_accounts:
raise PermissionError("account is not owned by caller")
if not 1 <= payload.limit <= 100:
raise ValueError("limit is outside the allowed range")
interface ToolPayload {
table: string;
accountId: string;
limit: number;
}
const allowedTables = new Set(["balances", "transactions"]);
export function validatePayload(
payload: ToolPayload,
ownedAccounts: ReadonlySet<string>,
): void {
if (!allowedTables.has(payload.table)) throw new Error("table is not allowed");
if (!ownedAccounts.has(payload.accountId)) throw new Error("account is not owned");
if (!Number.isInteger(payload.limit) || payload.limit < 1 || payload.limit > 100) {
throw new Error("limit is outside the allowed range");
}
}
VALIDATE PAYLOAD SHAPE → VALIDATE ITS MEANING → EXECUTE ONLY ALLOWED ARGUMENTS; MALFORMED OR DANGEROUS REQUESTS NEVER REACH THE TOOL
A verified finding from the lesson: the Python guard caught a transformed SQL-injection attempt (specially crafted input intended to change the query a tool executes). In TypeScript, the model refused the sensitive-table request before calling the tool, so the guard was verified separately rather than through that live path.
In the capstone:Eunomia validates each capability argument with domain rules (a minimum term no greater than the maximum, a rate filter within a realistic range), and no capability accepts a customer or account identifier at all, so a caller cannot substitute another customer's account; scope comes only from the verified token. Additional payload fields require additional checks. Skill Reporter applies the same semantic validation to report-query payloads before tools run.
Lesson 52
Cryptographic Tool Permission Scoping
The problem: Eunomia' sensitive tools cannot trust an agent request just because it sounds confident or includes a customer ID. They need cryptographic proof that a trusted authority approved this exact caller, action, resource, amount, and time window. Skill Reporter needs the same proof model for privileged report publication and distribution actions.
A digital signature (cryptographic proof that data was approved by the holder of a secret signing key and was not changed afterward) turns an approval into something the tool can verify. The signed permission token (a signed package describing exactly which action a caller may perform) travels with the tool request, but the signing key never does. These examples use a JWT (JSON Web Token, a standard signed claims format) and RS256 (an algorithm in which a private key signs and a corresponding public key verifies but cannot sign).
The verifier enforces the token's permission scope (the narrow set of tools, actions, resources, values, and time limits covered by an approval), comparing every claim with the requested operation. The exp claim is the expiry time. The jti claim is a unique token identifier used to stop a replay attack (reusing a valid past permission to repeat an action that should happen only once). A production replay store must atomically consume that identifier in shared storage and retain it until expiry, so concurrent workers and restarts cannot reuse it.
from typing import Protocol
import jwt
class ReplayStore(Protocol):
async def consume_once(self, jti: str, expires_at: int) -> bool: ...
async def verify_permission(
token: str,
public_key: str,
request: dict[str, object],
replay_store: ReplayStore,
) -> None:
required = ["tool", "caller", "action", "resource", "amount", "exp", "jti"]
claims = jwt.decode(
token, public_key, algorithms=["RS256"],
audience="eunomia-tools", issuer="eunomia-auth",
options={"require": required},
)
for field in ("tool", "caller", "action", "resource", "amount"):
if claims[field] != request.get(field):
raise PermissionError(f"scope mismatch: {field}")
if not await replay_store.consume_once(str(claims["jti"]), int(claims["exp"])):
raise PermissionError("permission token already used")
import { jwtVerify, type KeyLike } from "jose";
interface ReplayStore {
consumeOnce(jti: string, expiresAt: number): Promise<boolean>;
}
export async function verifyPermission(
token: string,
publicKey: KeyLike,
request: Record<string, unknown>,
replayStore: ReplayStore,
): Promise<void> {
const requiredClaims = ["tool", "caller", "action", "resource", "amount", "exp", "jti"];
const { payload } = await jwtVerify(token, publicKey, {
algorithms: ["RS256"], audience: "eunomia-tools", issuer: "eunomia-auth",
requiredClaims,
});
for (const field of ["tool", "caller", "action", "resource", "amount"] as const) {
if (payload[field] !== request[field]) throw new Error(`scope mismatch: ${field}`);
}
if (!(await replayStore.consumeOnce(payload.jti!, payload.exp!))) {
throw new Error("token already used");
}
}
TRUSTED SERVICE SIGNS A NARROW TOKEN → VERIFIER COMPARES EVERY CLAIM WITH THE TOOL REQUEST → EXECUTE ONLY IF ALL CHECKS PASS
A valid signature proves who signed the token and that it was not altered. It does not prove that the signed permission matches the action now being requested; the verifier must establish both facts.
A verified finding from the source lesson: its HMAC-scoped tool errors were absorbed into structured failure output rather than propagated as exceptions. The asymmetric JWT design above is a teaching extension, not the implementation verified by that exercise.
In the capstone:Eunomia's read-only first release applies this lesson only as a principle: least authority, with scope taken from the verified customer token and three capabilities that cannot act. Signed, per-action permission tokens are deferred to the write actions of a later release, where a sensitive action will run only when a token authorizes that exact action for the authenticated customer. Skill Reporter follows the same plan for privileged report operations.
Lesson 54
Distributed Vector Sharding & Tenant Isolation
The problem: Eunomia serves many customers through shared infrastructure. One missing tenant boundary can place one customer's records into another customer's retrieval path, logs, cache, or agent context before cleanup code can react. Skill Reporter has the same exposure across workspaces if tenant boundaries are not enforced at every retrieval and storage layer.
Vector search (finding records by comparing numerical representations of their meaning rather than matching only exact words) is powerful, but its nearest matches must stay inside the right security boundary. Each tenant (one customer or customer organization whose data must remain separate from every other customer's data) should be routed before search begins.
A shard (a physically or logically separate portion of a larger data store) can give each tenant its own index, records, and access policy. This supports tenant isolation (preventing one customer from reading, changing, or searching another customer's data), but the in-process maps below demonstrate only logical routing. They do not create independent storage or access-control boundaries. In production, the authenticated tenant must come from verified server-side identity claims—never the model or request body—and the data plane must enforce separate credentials or equivalent per-tenant authorization.
from typing import Protocol
class VectorShard(Protocol):
async def search(self, query: str) -> list[str]: ...
async def tenant_search(
authenticated_tenant: str,
requested_tenant: str,
query: str,
shards: dict[str, VectorShard],
) -> list[str]:
if requested_tenant != authenticated_tenant:
raise PermissionError("tenant mismatch")
shard = shards.get(authenticated_tenant)
if shard is None:
raise PermissionError("unknown tenant")
return await shard.search(query)
interface VectorShard {
search(query: string): Promise<string[]>;
}
export async function tenantSearch(
authenticatedTenant: string,
requestedTenant: string,
query: string,
shards: ReadonlyMap<string, VectorShard>,
): Promise<string[]> {
if (requestedTenant !== authenticatedTenant) throw new Error("tenant mismatch");
const shard = shards.get(authenticatedTenant);
if (!shard) throw new Error("unknown tenant");
return shard.search(query);
}
AUTHENTICATE → SELECT ONE TENANT ROUTE BEFORE SEARCH → QUERY ONLY THAT SHARD → RETURN SAME-TENANT RESULTS; PRODUCTION STORAGE MUST ENFORCE THE BOUNDARY
A verified finding from the lesson: storage isolation held, but the Python agent fabricated its self-reported tenant identifier. The TypeScript path avoided that bug by supplying trusted metadata explicitly. Security routing must therefore use verified server-side identity, not model-reported metadata.
In the capstone:Eunomia applies this lesson's isolation principle without per-tenant vector shards: every port call is scoped to the customer in the verified token, no customer data enters the shared guidance or catalogue indexes, and the evidence route answers another customer's turn with a 404. Per-tenant storage enforcement becomes required if customer documents are ever indexed. Skill Reporter mirrors this with strict workspace-level retrieval isolation.
Lesson 55
Deterministic Hash-Based Sampling for Review Queues
The problem: Eunomia operations can manually inspect only a fraction of interactions, especially around high-risk financial guidance. Naive random sampling chooses different records on every run, making audits irreproducible. Skill Reporter needs the same deterministic review sampling so publication-risk reviews are repeatable and defensible.
A cryptographic hash (a one-way calculation that gives the same fixed-length output for the same input, while a small input change normally gives a very different output that is hard to predict) can map each interaction into a numeric bucket. Deterministic sampling (selecting items by a repeatable rule rather than a new random choice on every run) sends buckets below a policy threshold for inspection. The threshold uses basis points: one basis point is one hundredth of one percent, so 10,000 basis points is 100%.
The input needs a stable identifier (a value that continues to identify the same item across retries and systems), plus an explicit policy version. Selected, safely redacted interactions enter a review queue (a list of selected interactions waiting for a person to inspect). The same identifier and policy reproduce the same result later.
from hashlib import sha256
def should_review(
interaction_id: str,
policy_version: str,
threshold_basis_points: int,
) -> bool:
if not 0 <= threshold_basis_points <= 10_000:
raise ValueError("threshold must be from 0 to 10,000 basis points")
policy = policy_version.encode("utf-8")
interaction = interaction_id.encode("utf-8")
stable_key = len(policy).to_bytes(4, "big") + policy + interaction
digest = sha256(stable_key).digest()
bucket = int.from_bytes(digest[:8], byteorder="big") % 10_000
return bucket < threshold_basis_points
import { createHash } from "node:crypto";
export function shouldReview(
interactionId: string,
policyVersion: string,
thresholdBasisPoints: number,
): boolean {
if (!Number.isInteger(thresholdBasisPoints) ||
thresholdBasisPoints < 0 || thresholdBasisPoints > 10_000) {
throw new Error("threshold must be from 0 to 10,000 basis points");
}
const policy = Buffer.from(policyVersion, "utf8");
const length = Buffer.alloc(4);
length.writeUInt32BE(policy.length);
const stableKey = Buffer.concat([length, policy, Buffer.from(interactionId, "utf8")]);
const digest = createHash("sha256").update(stableKey).digest();
const bucket = Number(digest.readBigUInt64BE(0) % 10_000n);
return bucket < thresholdBasisPoints;
}
STABLE ID + VERSIONED POLICY → FIXED HASH → NUMERIC BUCKET → REPEATABLE REVIEW DECISION, INCLUDING DURING A LATER AUDIT
A verified finding from the lesson: Python and TypeScript agreed exactly: over 50,000 identifiers the observed review rate was 0.1006, sampled counts were identical, and increasing the threshold produced a verified monotonic superset. Shared test vectors should preserve that agreement.
In the capstone:Eunomia's first release uses stable, hash-based selection on its quality runs: a reproducible share of passing scenario runs goes to human review, and every failure goes regardless of the sample, including any suspected PII (personally identifiable information) leak or cross-customer access. Live turns reach review through the explicit review route and through handoffs; hash-sampling live traffic is deferred to a later release. Skill Reporter uses the same deterministic sampling and mandatory-escalation rules for high-risk report outputs.
Part VII
Observability & Evaluation
A production agent needs more than a convincing demo. The team must be able to reconstruct every request, measure answer quality repeatedly, block harmful regressions, and prove that the whole customer journey still works. This part turns those needs into connected traces, versioned evaluations, browser tests, and trustworthy delivery gates for both Python and TypeScript.
Dual-domain map for this part: the same observability and eval controls apply to Eunomia and Skill Reporter.
Skill Reporter domain: the same trace, eval, judge, CI, browser, monorepo, and baseline-gating controls for report-generation flows.
Interlink chain: Lesson 7 provides trace evidence, Lessons 10 and 39 define and score eval quality, Lessons 47 and 48 enforce CI and browser evidence, Lesson 53 aligns repo-wide contracts, and Lesson 56 protects baselines from regression drift.
Lesson 7
OpenTelemetry & Agent Tracing
The problem: when Eunomia returns a slow, incorrect, or surprising savings answer, teams need to know exactly which model and tool steps ran and where delay or error started. Plain logs rarely reconstruct that full execution path. Skill Reporter has the same blind spot when report outputs are late or wrong and the team cannot trace where the pipeline diverged.
OpenTelemetry (a shared standard for creating and exporting operational records from software) gives the request a structured history. A trace (the complete structured record of one request as it moves through a system) begins at the incoming API call. Inside it, each span (one timed operation inside a trace, such as a model call or tool call) records a named piece of work, its duration, and whether it succeeded.
CUSTOMER REQUEST → API SPAN → AGENT SPAN → ORDERED MODEL AND TOOL CHILD SPANS → EXPORTER → INSPECTABLE TRACE STORE
The parent agent span owns child spans for the first model call, the savings-data lookup, and the final model call. Each span can carry safe operational details such as the operation name, model or tool name, elapsed time, and success state. It should not carry the customer's message, account number, balance, or any other private value. The completed trace must be inspected, not merely emitted, to confirm that its parent-child links match the order that really ran.
from collections.abc import Awaitable, Callable
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
tracer = trace.get_tracer("eunomia.agent")
async def run_agent(call_tool: Callable[[], Awaitable[str]]) -> str:
with tracer.start_as_current_span("agent.run") as agent_span:
agent_span.set_attribute("agent.version", "savings-v3")
with tracer.start_as_current_span("tool.savings_lookup") as tool_span:
try:
result = await call_tool()
except Exception as exc:
tool_span.set_attribute("tool.success", False)
tool_span.record_exception(exc)
tool_span.set_status(Status(StatusCode.ERROR))
raise
tool_span.set_attribute("tool.success", True)
return result
Context propagation (passing the trace identity from one operation to the next so related spans remain connected) matters when work crosses an asynchronous boundary (a point where work pauses or continues in another task). Python and TypeScript can export the same trace shape, but their libraries may manage the current span differently while work is paused and resumed. A test must therefore prove that later tool work remains beneath the correct request rather than assuming it does.
Tracing is diagnostic support, not part of the customer's transaction. Use an asynchronous batch exporter with a bounded queue and timeout; if capacity is exhausted or export fails, drop or report telemetry separately rather than blocking the customer request.
A real finding worth knowing: side-by-side Python and TypeScript implementations can both show successful tool spans while one language has silently disconnected those spans from the parent request during asynchronous work. Explicit context-propagation checks are required; a green tool span alone proves only that the tool ran.
In the capstone:Eunomia will use OpenTelemetry to connect every API request, model call, and capability call into one inspectable trace across its monorepo (one repository containing the service, its quality checks, its probes and its web client). Skill Reporter will publish the same trace shape so cross-domain investigations use one workflow.
Lesson 10
Evaluation-Driven Development
The problem: Eunomia can look convincing in demos while still failing common, ambiguous, or risk-sensitive customer requests. Without versioned expectations, prompt and policy tweaks become guesswork instead of measurable improvement. Skill Reporter has the same risk: report quality can drift silently unless every change is measured against saved evaluation cases.
Evaluation-Driven Development, or EDD (defining automated quality checks before or while building an AI feature) starts with user failures the team wants to prevent. Each desired behavior becomes an eval case (one saved input with explicit criteria for judging the resulting answer): the input, facts that must appear, behavior that is forbidden, and a scoring rule an engineer can explain.
EXPECTED BEHAVIOR BECOMES A VERSIONED DATASET → BOTH AGENTS RUN THE SAME CASES → SHARED SCORERS PRODUCE ONE COMPARISON REPORT → FAILURES DRIVE THE NEXT CHANGE
A dataset (a versioned collection of eval cases) should cover normal questions, ambiguous requests, unavailable tools, unsafe requests, and attempts to expose private information. The first cases should fail before the missing behavior is implemented. That failure proves the check can detect the problem; making it pass then becomes the feature's acceptance evidence.
from dataclasses import dataclass
@dataclass(frozen=True)
class EvalCase:
prompt: str
required: tuple[str, ...]
forbidden: tuple[str, ...]
def score(case: EvalCase, answer: str) -> bool:
normalized = " ".join(answer.lower().split())
has_required = all(term.lower() in normalized for term in case.required)
has_forbidden = any(term.lower() in normalized for term in case.forbidden)
return has_required and not has_forbidden
A scorer (code or a model that turns an answer into a result such as pass, fail, or a numeric score) should match the quality being measured. Required text, valid structure, and forbidden disclosures suit deterministic code. Clarity and relevance need judgment-based scoring. Both Python and TypeScript runners should receive identical cases and write a common report shape, while the readable case descriptions preserve the reason each test exists.
An eval suite is a product specification written as executable examples. If nobody can explain why a case exists, its failure will not guide a useful change.
A real finding worth knowing: the same visible answer can receive different results across language runners when one trims whitespace, parses structured output, or treats a missing field differently. Shared report schemas and normalization rules must be tested as carefully as the agent behavior.
In the capstone:Eunomia will be developed against a versioned eval suite that defines acceptable savings guidance before each feature is considered complete. Skill Reporter will use the same versioned-suite discipline for report-quality expectations.
Lesson 17
Logfire & Distributed Tracing
The problem: one Eunomia request can cross browser, API, agent runtime, and savings tools. Service-local logs may all be correct yet still fail to show which records belong to the same customer interaction or where latency accumulated. Skill Reporter has the same cross-service visibility problem across UI, orchestration, and reporting components.
A distributed trace (one connected record of a request that crosses multiple services or processes) extends the parent-child structure from Lesson 7 across network boundaries. Every service propagates the same trace ID (the shared identifier that links all spans belonging to one request) as part of W3C Trace Context (the standard HTTP headers used to connect tracing spans across services), usually in traceparent. Each hop creates a new span ID for its own work and forwards updated context. Browser-to-API propagation also requires tracing instrumentation and permission to send the cross-origin trace header.
FRONTEND → API → AGENT → SAVINGS TOOL, PROPAGATING W3C TRACE CONTEXT AND EXPORTING THEIR SPANS INTO ONE CROSS-SERVICE TIMELINE
Logfire (an observability platform used to collect, search, and visualize traces and related records) acts as the telemetry backend (the service that stores and displays traces, measurements, and structured logs). Python and TypeScript services export compatible OpenTelemetry data into it while preserving the relationships already created inside each process. One timeline can then separate frontend delay, API processing, model latency (the time an operation takes), and tool latency.
import httpx
from opentelemetry import propagate, trace
tracer = trace.get_tracer("eunomia.api")
async def fetch_savings(url: str) -> dict[str, object]:
with tracer.start_as_current_span("savings.request"):
headers: dict[str, str] = {}
propagate.inject(headers)
async with httpx.AsyncClient() as client:
response = await client.get(url, headers=headers)
response.raise_for_status()
return response.json()
Searchable fields should describe operations, versions, timings, and outcomes. Customer messages, account details, and other private data do not belong in the backend. Successful and failed requests can still be compared by status, error category, tool name, and duration without turning observability into a second customer-data store. Use an asynchronous batch processor with a bounded queue and export timeout. When the queue is full or the backend is unavailable, drop or separately report telemetry instead of blocking or failing the customer request.
A real finding worth knowing: if an outgoing request omits or corrupts W3C trace context, the receiving service may silently start a new trace. Both halves look valid in isolation, but the expected single timeline becomes two unrelated ones. Context propagation must therefore be verified at every HTTP (web request) and tool boundary.
In the capstone:Eunomia will send connected traces from its web client, service, model gateway, and capabilities through OpenTelemetry and its masking trace sink, so one savings conversation can be inspected as a single timeline. Logfire is one possible backend for the Python tooling; the TypeScript service exports plain OpenTelemetry. Skill Reporter will emit the same multi-package trace continuity for end-to-end report journeys.
Lesson 19
LLM-as-a-Judge Benchmarking
The problem: exact-text checks cannot judge whether Eunomia guidance is relevant, clear, and evidence-grounded for nuanced customer questions. Human review can judge this, but not at the pace of every code change. Skill Reporter has the same scaling issue when qualitative report quality needs continuous scoring.
LLM-as-a-judge (using a second language model to score another model's answer) provides a repeatable first pass. The judge receives the user's request, the evidence available to the agent, the candidate answer, and a rubric (a written scoring guide that defines what each score means). The rubric must describe observable qualities rather than vague goals such as “be good,” and the result must contain a structured score plus a short reason tied to evidence.
REQUEST + RELEVANT EVIDENCE + CANDIDATE ANSWER + RUBRIC → JUDGE MODEL → STRUCTURED RESULT → COMPARE WITH TRUSTED HUMAN LABELS → ACCEPT OR REVISE THE JUDGE SETUP
A benchmark (a fixed set of cases used to compare quality across versions) needs clear passes, clear failures, and difficult boundary cases. It must also probe order bias, preference for longer answers, leaked reference answers, and preference for wording similar to the rubric. The judge must not receive hidden hints about the expected score, because that would test hint-following rather than answer quality.
Calibration (checking automated scores against trusted human labels to learn whether the judge is reliable) happens before the judge is trusted in automation. Python and TypeScript judge clients run the same labelled examples and normalize their structured outputs into one report. In these abbreviated clients, prompt is assembled beforehand by a separately validated builder from the user request, relevant evidence, candidate answer, and rubric. Direct checks for safety, privacy, and required facts remain separate: a high clarity score can never cancel a prohibited disclosure.
import json
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
@dataclass(frozen=True)
class JudgeResult:
score: int
reason: str
async def judge_answer(call_judge: Callable[[str], Awaitable[str]], prompt: str) -> JudgeResult:
value = json.loads(await call_judge(prompt))
if not isinstance(value, dict):
raise ValueError("judge result must be an object")
score = value.get("score")
reason = value.get("reason")
if type(score) is not int or not 1 <= score <= 5:
raise ValueError("judge returned an invalid score")
if not isinstance(reason, str) or not reason.strip():
raise ValueError("judge returned an invalid reason")
return JudgeResult(score=score, reason=reason.strip())
interface JudgeResult {
score: number;
reason: string;
}
type JudgeClient = (prompt: string) => Promise<string>;
export async function judgeAnswer(callJudge: JudgeClient, prompt: string): Promise<JudgeResult> {
const value: unknown = JSON.parse(await callJudge(prompt));
if (typeof value !== "object" || value === null) throw new Error("invalid judge result");
const { score, reason } = value as Record<string, unknown>;
if (typeof score !== "number" || !Number.isInteger(score) || score < 1 || score > 5) {
throw new Error("invalid score");
}
if (typeof reason !== "string" || !reason.trim()) throw new Error("missing reason");
return { score, reason: reason.trim() };
}
A real finding worth knowing: a judge may reward a longer answer even when length is absent from the rubric. Calibration cases with equally correct short and long answers expose this verbosity bias, allowing the rubric or judge prompt to be corrected before the score becomes a gate.
In the capstone:Eunomia will use a calibrated judge model to score qualities such as relevance and clarity while retaining direct checks for required safety and privacy behavior. Skill Reporter will follow the same hybrid judge-plus-deterministic-check model.
Lesson 25
CI/CD Eval Gates
The problem: Eunomia evals do not protect production if they run only manually or inconsistently. Every proposed change needs the same automatic gate, and meaningful quality loss must be blocked before merge. Skill Reporter requires the same CI discipline so reporting regressions never ship by accident.
CI/CD (the automated process that builds, tests, and delivers software changes) runs the relevant checks for every pull request (a proposed set of code changes submitted for review before merging). An eval gate (an automated pass-or-fail decision based on evaluation results) turns the report into an enforceable decision instead of an optional attachment.
PULL REQUEST → BUILD → START CONTROLLED SYSTEM → RUN EVALS → REPORT → QUALITY DECISION, WITH INFRASTRUCTURE FAILURE KEPT DISTINCT FROM A PRODUCT PASS
The workflow first builds affected packages, starts the controlled test system, and selects cases based on the changed files. High-risk changes still take the full-suite path. It produces machine-readable results (structured data that software can parse reliably) for automation and a readable artifact for reviewers, including every failed case. New results are compared with an accepted baseline (a trusted earlier result used as the point of comparison) and a threshold (the minimum acceptable score or maximum permitted regression).
Average quality is not enough: one critical safety failure blocks the change even if every ordinary case passes. Model outages, network failures, and broken test infrastructure are reported as inconclusive (unable to establish product quality because the evaluation did not complete reliably) rather than mislabeled as product regressions or, worse, quality passes. Any exception requires an explicit recorded approval; the threshold is never quietly weakened to make a build green.
from typing import Literal, TypedDict
class EvalReport(TypedDict):
complete: bool
average_score: float
critical_failures: list[str]
GateDecision = Literal["pass", "fail", "inconclusive"]
def decide_gate(report: EvalReport, minimum_score: float) -> GateDecision:
if not report["complete"]:
return "inconclusive"
if report["critical_failures"] or report["average_score"] < minimum_score:
return "fail"
return "pass"
A real finding worth knowing: one language's eval command may exit successfully after recording failed cases while the other returns a failure code. The pipeline must derive its decision from the validated report and its critical-case results, not from command completion alone.
In the capstone: every Eunomia pull request will run the relevant evals automatically and will be blocked when savings-answer quality or a critical safety case falls below its required threshold. Skill Reporter pull requests will use equivalent blocking gates for report correctness and safety.
Lesson 26
Playwright End-to-End Verification
The problem: unit tests can prove isolated Eunomia functions while the real customer journey still fails at authentication, API wiring, streaming, or tool connectivity. The missing proof is a full browser-to-result path. Skill Reporter has the same end-to-end risk unless report-generation journeys are exercised through the actual UI and backend chain.
Playwright (a browser-automation tool that can click, type, and inspect a real web page) runs an end-to-end test, or E2E test (a test that exercises the complete user journey across the frontend and backend). The test starts the frontend, API, supporting services, and controlled model or tool dependencies, opens the actual chat page, and submits a savings question through the same field a customer uses.
PLAYWRIGHT DRIVES A REAL BROWSER THROUGH FRONTEND → API → AGENT AND TOOLS, THEN COLLECTS VISIBLE, NETWORK, SCREENSHOT, AND TRACE EVIDENCE
A locator (a stable rule for finding an element on a page) should use accessible roles (labels such as button or textbox exposed to assistive technology) or deliberate test identifiers (stable names added for automation), not screen coordinates or styling classes. The test waits for a visible completion state rather than sleeping for a guessed number of seconds. It then checks the final answer, tool-derived details, error states, and absence of private internal information. Where both agent variants exist, the same journey runs against the Python-backed and TypeScript-backed systems.
When a test fails, screenshots, console errors, failed network requests, and a trace artifact (a saved browser timeline containing actions, page state, and network evidence from a test run) make the failure reproducible. A small critical journey set belongs on pull requests; a broader suite can run on a schedule so feedback remains fast without abandoning coverage.
A real finding worth knowing: a streamed-answer test can pass locally and fail in automation when it waits a fixed number of seconds. Waiting for the page's real completion state takes more care to implement, but it remains reliable when machines, models, or networks run at different speeds.
In the capstone:Eunomia applies this lesson's principle — prove the real running system from outside — through an independent Python probe suite that calls the public HTTP routes instead of driving a browser. A probe submits a savings question, reads the complete typed event stream, checks that it ends with exactly one ending event, and uses the stub upstream's call counts to confirm the expected backend work. Skill Reporter will run the same outside-in proof for report workflows.
Lesson 30
Unified Monorepo Orchestration
The problem: when Eunomia frontend, API, tools, and evals drift across disconnected commands or package boundaries, one package can pass while silently breaking a dependent package. Local developer setups can mask these breakages until clean builds fail. Skill Reporter has the same integration fragility without unified monorepo contracts and shared verification steps.
A monorepo (one repository containing several related software packages) keeps the connected system under one versioned change. A workspace (the package-manager configuration that links local packages and manages their shared installation) defines the package boundaries and their declared dependencies. Source, tests, and build output stay inside the package that owns them; only genuinely common configuration belongs at the root.
ONE EUNOMIA MONOREPO → A SHARED TASK GRAPH ORDERS FRONTEND, API, TOOLS, AND EVAL WORK → LOCAL AND CI COMMANDS USE THE SAME GRAPH AND SAFE CACHE
A task graph (a map showing which build, test, and eval tasks depend on other tasks) compiles (translates source code into runnable output) shared tools before the API or eval runner imports them (loads their exported code). It can run only affected work for quick feedback while retaining one complete verification command. Local development and CI/CD use the same top-level commands, so the automation does not exercise a different system from the developer.
A cache (stored output that allows unchanged tasks to be reused instead of run again) is safe for deterministic builds and tests. Live eval results should not be cached when model behavior or external inputs can change, unless every input and version is captured. Shared schemas (strict descriptions of data shapes) and generated types (code-created type definitions) keep tool contracts aligned across API, eval, and frontend packages, while explicit dependency declarations (each package's list of required libraries) prevent a friendly local installation from hiding a broken isolated build (a build run with only that package's declared dependencies).
A real finding worth knowing: a TypeScript workspace import may work locally because a dependency was hoisted (installed in a shared parent location) into reach, then fail in an isolated build because the owning package never declared it. Python can hide the same defect when an undeclared module happens to exist in one developer's environment. Isolation tests expose both cases.
In the capstone:Eunomia will keep its service, quality suite, probes and web client in one repository so the event contract, the scenarios that depend on it and the client that reads it change together and are verified as one connected system. Skill Reporter will use the same monorepo contract discipline so shared schemas evolve safely across packages.
Lesson 56
Last-Approved Baseline Promotion for Eval Gates
The problem: comparing Eunomia to only the latest eval output is unsafe because that baseline may already include accepted or misclassified losses. Repeated small degradations can normalize bad quality. Skill Reporter has the same baseline-drift risk unless promotion always compares against a trusted reference artifact.
A regression (a measurable loss in behavior or answer quality) must be measured against a trustworthy baseline, not simply the nearest file in storage. Every report therefore records its code revision (the exact version of the code that produced it), dataset version, rubric version, threshold-policy version, completeness state, final gate decision, and any manual override with its approval evidence.
CURRENT CHANGE WALKS BACK PAST FAILED AND INCOMPLETE REPORTS → SELECTS THE NEAREST COMPATIBLE PASS → COMPARES CURRENT QUALITY → PROMOTES ONLY AFTER A SUCCESSFUL GATE
An ancestry walk (moving backward through earlier code revisions until a valid historical report is found) begins at the current change's parent and supplies reports newest-first along that ancestry. It rejects reports that are incomplete, did not pass their own gate, were manually overridden without approval evidence, or use incompatible dataset, rubric, or threshold-policy versions. The first remaining pass is therefore the nearest trusted comparison point, and the pull-request report displays both its revision and every rejection reason.
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Literal
@dataclass(frozen=True)
class Report:
revision: str
complete: bool
gate: Literal["pass", "fail", "inconclusive"]
dataset: str
rubric: str
threshold_policy: str
overridden: bool
override_approval: str | None
def select_baseline(
history_newest_first: Iterable[Report],
dataset: str,
rubric: str,
threshold_policy: str,
) -> Report:
for report in history_newest_first:
compatible = (
report.dataset == dataset
and report.rubric == rubric
and report.threshold_policy == threshold_policy
)
override_valid = not report.overridden or report.override_approval is not None
if report.complete and report.gate == "pass" and compatible and override_valid:
return report
raise LookupError("no compatible passing baseline")
The current result must satisfy fixed minimum requirements as well as stay within the permitted change from the baseline. Missing or corrupt history is an explicit policy state, never an excuse to compare against zero or pass automatically. Baseline promotion (marking a newly passing report as the trusted reference for future comparisons) happens only after the current gate succeeds, with coordination that prevents concurrent builds from promoting older results out of order.
The latest report is a fact about time; the trusted baseline is a fact about quality. They are not interchangeable.
A real finding worth knowing: Python and TypeScript implementations can select different historical reports when one treats a missing gate field as failure while the other treats it as merely absent. A shared report schema and explicit eligibility rules are necessary before both implementations can agree on the baseline.
In the capstone:Eunomia will gate every pull request against the last approved run manifest, a run that fully passed, never against whatever ran most recently, preventing an already-regressed run from becoming the new definition of acceptable quality. Skill Reporter will follow the same trusted-baseline rule for report-quality gates.
Lesson 57
Consecutive-Pass Promotion Windows for Eval Gates
The problem: a single green eval run can be luck, not stability. If Eunomia promotes on one pass, noisy runs can slip through as false confidence. Skill Reporter has the same risk when one-off passes are treated as release-ready evidence.
A promotion window (a required run count that must all pass before release) turns promotion into a stability check, not a moment-in-time check. Day 56 chooses the right baseline; Day 57 adds timing discipline: require consecutive passes and keep the same regression tolerance against the approved baseline on every run inside that window.
RECENT RUNS → CONSECUTIVE-PASS WINDOW + BASELINE TOLERANCE CHECK → PROMOTE ONLY WHEN THE WHOLE WINDOW IS STABLE
from dataclasses import dataclass
@dataclass
class EvalRun:
run_id: str
score: float
gate_passed: bool
def should_promote_after_window(
history: list[EvalRun],
approved_baseline_score: float,
window_size: int = 3,
max_regression: float = 0.02,
) -> tuple[bool, str]:
if len(history) < window_size:
return False, f"need {window_size} runs, got {len(history)}"
window = history[-window_size:]
failed = [run.run_id for run in window if not run.gate_passed]
if failed:
return False, f"window contains gate failures: {failed}"
for run in window:
drop = approved_baseline_score - run.score
if (drop - max_regression) > 1e-9:
return False, f"run {run.run_id} regressed {drop:.3f} > allowed {max_regression:.3f}"
return True, f"{window_size} consecutive passes within regression tolerance"
One passing run proves possibility. A consecutive-pass window proves stability.
A real finding worth knowing: strict floating-point comparisons can falsely block an exact-threshold case (for example 0.020000000000000018 > 0.02). Both implementations now use a tiny epsilon guard so equality at the threshold behaves consistently.
In the capstone:Eunomia's deploy approval only records a run's manifest as a candidate; the approved baseline moves to it only after a window of consecutive passing runs on main with tolerance-safe scores across the whole window. Skill Reporter uses the same rule so promotions are based on sustained quality, not a single lucky run.
Lesson 58
Model Retry Guard with Failure Classification
The problem: naive retry loops cause two failures in production: retrying fatal errors forever, and giving up too early on transient failures that would recover. Eunomia and Skill Reporter both need explicit retry rules with a hard budget.
A retry guard (a policy that decides whether a failed attempt is retried or stopped) classifies failures as transient or fatal, then applies a strict retry budget. Success stops immediately, fatal errors stop immediately, transient errors retry only while budget remains.
ATTEMPT RESULT → FAILURE CLASSIFICATION + RETRY BUDGET → SELECTIVE RETRY OR IMMEDIATE STOP
Retries are useful only when they are selective and bounded.
A real finding worth knowing: without explicit failure classification, different services interpret the same error differently and create inconsistent retry behavior. A shared failure taxonomy and budget rule keeps retry outcomes predictable across stacks.
In the capstone:Eunomia can recover from transient provider/tool issues without masking hard failures or creating runaway loops. Skill Reporter follows the same retry discipline for deterministic reliability.
Lesson 59
Stateful Evaluator Graph
The problem: when evaluation retry logic is hidden inside nested conditionals, operations teams cannot reliably explain why a run was approved, revised, or rejected. The real problem is deciding the next operational step from state, not just generating text. The graph exists to make control flow explicit: it owns step order, branch rules, and state updates.
LLMs still do useful work inside steps (for example, extracting entities and intent from the customer question), but they do not directly decide control flow. State-machine logic decides what happens next; model inference stays bounded inside each step.
Relationship to Lesson 5: same graph pattern, different scope. Lesson 5 applied stateful graph routing to general workflow paths. Lesson 59 applies stateful graph routing to evaluator operations and terminal decision states (`APPROVED` or `REJECTED`).
DRAFT → EVALUATING → APPROVED OR NEEDS_REVISION LOOP → REJECTED AT ATTEMPT CAP
from dataclasses import dataclass
from enum import Enum
class EvalState(str, Enum):
DRAFT = "draft"
EVALUATING = "evaluating"
NEEDS_REVISION = "needs_revision"
APPROVED = "approved"
REJECTED = "rejected"
@dataclass
class EvalContext:
attempt: int
max_attempts: int
score: float
threshold: float
state: EvalState = EvalState.DRAFT
def step(context: EvalContext) -> EvalContext:
if context.state == EvalState.DRAFT:
context.state = EvalState.EVALUATING
return context
if context.state == EvalState.EVALUATING:
if context.score >= context.threshold:
context.state = EvalState.APPROVED
return context
if context.attempt >= context.max_attempts:
context.state = EvalState.REJECTED
else:
context.attempt += 1
context.state = EvalState.NEEDS_REVISION
return context
if context.state == EvalState.NEEDS_REVISION:
context.state = EvalState.DRAFT
return context
The graph decides the operation. The model contributes inside the operation.
In the capstone:Eunomia and Skill Reporter use explicit evaluator states in the quality harness (snapshot, replay, assert, archive) so release decisions are traceable and replayable under retry pressure.
Lesson 60
Human-in-the-Loop Gate for High-Risk Actions
The problem: retry logic and evaluator routing still do not answer who is allowed to execute high-risk actions. Without an explicit gate, an agent can run side effects directly from model output. Eunomia and Skill Reporter need a deterministic approval boundary before execution.
The gate policy is explicit and auditable: low risk with high confidence can auto-approve, low confidence can auto-reject, and high-risk actions must remain pending until a human reviewer approves or rejects them.
ACTION PROPOSAL → DETERMINISTIC GATE → AUTO EXECUTE OR HUMAN REVIEW → EXPLICIT APPROVE/REJECT OUTCOME
if proposal.risk_tier == RiskTier.LOW and proposal.confidence >= 0.7:
return GateOutcome(status=GateStatus.AUTO_APPROVED, executed=True, reason="low risk and high confidence")
if proposal.risk_tier == RiskTier.HIGH and reviewer is None:
return GateOutcome(status=GateStatus.PENDING_REVIEW, executed=False, reason="human approval required")
if reviewer and reviewer.approved:
return GateOutcome(status=GateStatus.HUMAN_APPROVED, executed=True, reason="approved by reviewer")
return GateOutcome(status=GateStatus.HUMAN_REJECTED, executed=False, reason="rejected by reviewer")
Model output may propose high-risk actions. Only explicit human approval may execute them.
A real finding worth knowing: when "pending review" is represented as an explicit machine state, high-risk actions cannot execute accidentally while waiting for a reviewer decision. This removes hidden side effects from retry paths.
In the capstone:Eunomia's read-only first release has no high-impact side effects to gate at runtime; its human decision boundaries are the required reviewer on production deploys and the person at the bottom of the answer sequence. This per-action gate is deferred to the write actions of a later release, and Skill Reporter defers it the same way.
Lesson 61
Idempotent Approval Execution Ledger
The problem: human approval alone does not stop duplicate side effects when clients retry the same approved action. Without a once-only execution ledger, a network retry can submit the same high-risk transfer twice.
The control is deterministic: missing decisions block execution, rejected decisions block execution, first approved call executes, and every replay with the same approval id returns the original execution id without running side effects again.
APPROVAL DECISION → EXECUTION LEDGER (APPROVAL-ID KEY) → EXECUTE ONCE OR RETURN REPLAY
existing_execution_id = self._executions.get(approval_id)
if existing_execution_id is not None:
return ExecutionOutcome(
status=ExecuteStatus.DUPLICATE_REPLAY,
executed=False,
execution_id=existing_execution_id,
reason="already executed for this approval id",
)
side_effect()
execution_id = f"exec-{approval_id}"
self._executions[approval_id] = execution_id
Approval controls who may execute. Idempotency controls how many times execution may happen.
A real finding worth knowing: retrying the same approved request returned duplicate_replay and the original execution id while side effects stayed at one call.
In the capstone:Eunomia's read-only first release executes no high-risk actions, so it needs no execution ledger yet. When write actions arrive, Eunomia and Skill Reporter will pair this ledger with human approval so each high-risk action is both authorized and once-only.
Lesson 62
Request-Scoped Degradation Visibility
The problem: fallbacks keep the service running, but silent fallbacks hide risk. If classifier or retrieval failures are not captured per request, operators cannot explain why answer quality changed or why a rollout should pause.
The fix is a request-scoped degradation trace. Each degraded component writes a structured event with component name, reason, severity, and fallback path. The reply can still return safely, but degraded execution remains explicit and auditable.
A real finding worth knowing: one request can degrade in more than one component. Capturing only a single boolean loses incident detail and weakens release decisions.
In the capstone:Eunomia and Skill Reporter record request-scoped degradation events — each answer step tried and each provider fallback, per turn, through the trace sink — to connect runtime fallbacks to eval outcomes and operational triage.
Lesson 63
Bounded Agent Loop Budget & Step Authority
The problem: autonomous tool loops can overrun if there is no hard step cap, and they can still execute out-of-scope tools if authority is checked too late or not checked per step.
The fix is to enforce two controls at the same runtime boundary: a strict max_steps budget and a step-by-step tool authority check tied to request intent. The loop stops with an explicit reason: completed, budget exhausted, or authority denied.
for index, tool in enumerate(planned_tools):
step = index + 1
if step > max_steps:
return LoopOutcome(status=LoopStatus.BUDGET_EXHAUSTED, ...)
if not is_allowed(intent, tool):
return LoopOutcome(status=LoopStatus.AUTHORITY_DENIED, ...)
execute_tool(tool)
Bound autonomy is safer autonomy.
A real finding worth knowing: the same run can be both short and unsafe. A low step count does not prove safety if authority checks are not enforced at each step.
In the capstone:Eunomia's first release gives the model no multi-step tool loop: the service gathers the evidence, and on the composed step the model may request at most one more read-only capability call. That is this lesson's guard in its tightest form: a step budget of one, and only the three read-only capabilities allowed. If a longer loop is added later, Eunomia checks before each call that (1) it is still inside the max-step budget and (2) the tool is allowed for this question type by policy, and stops the loop if either check fails.
Lesson 64
Jev-Style Decision Layer for Agent Routing
The problem: forcing one intent choice on mixed high-risk prompts can produce confident-looking misroutes. In Eunomia, a wrong route can be worse than pausing for clarification.
The fix is a decision-first route layer: score all allowed intents, pick a typed route, attach a confidence score, and escalate to unknown when confidence is below threshold. In this lesson, the Jev pattern is demonstrated with a deterministic in-repo approximation so it is fully runnable offline: no external Jev API call is required for the benchmark.
def route_with_jev_confidence(message: str, min_confidence: float = 0.45) -> RoutedDecision:
raw = jev_style_raw_decision(message)
if raw.confidence < min_confidence and raw.intent != Intent.UNKNOWN:
return RoutedDecision(intent=Intent.UNKNOWN, confidence=raw.confidence, escalated=True)
return RoutedDecision(intent=raw.intent, confidence=raw.confidence, escalated=False)
FIXED INTENT OPTIONS → SCORED DECISION + CONFIDENCE → ROUTE ONLY IF ABOVE THRESHOLD; OTHERWISE ESCALATE
Before/after in this run: baseline keyword routing reached accuracy=0.73 with high_risk_misroutes=2. The Jev-style decision layer reached accuracy=1.00 with high_risk_misroutes=0, and it used one explicit escalation on a low-confidence mixed-intent case. On the current Eunomia eval corpus, the result is parity (1.00 → 1.00 accuracy, 0 → 0 high-risk misroutes), which means no demonstrated gain there yet and no regression.
Why substring checks rather than regex?
Python uses in; TypeScript uses includes(). These keep the keyword-to-score rules easy to read. Both substring checks and regex are deterministic. Substrings can create false matches: “balance” matches “balanced”, and “rate” matches “corporate”. Whole-word regex can prevent some of these mistakes, but neither approach understands negation or intent. These heuristic scores are not calibrated probabilities.
If using a real Jev API
This is an optional integration description, not implemented API behavior. No paid calls are made by the lesson. Through an approved gateway, send a server-side authenticated request to the documented TypeSafe POST /v1/systemone endpoint with model, state, and a questions.route Choice question whose criteria describe the allowed intents. Read and validate answers.route.choice and answers.route.confidence, then apply the local gate before policy and tool authorization. Re-evaluate the threshold: Jev confidence differs from our normalized keyword score. For sensitive requests, API failure means abstaining to unknown, not blindly trusting the keyword fallback. See the TypeSafe API reference and confidence documentation.
When uncertainty is high, refusing to guess is a safety feature.
In the capstone: decision-first routing becomes Eunomia's routing policy table: a typed question type plus a confidence threshold picks the starting answer step before any evidence is gathered, and a low-confidence or mixed high-risk message goes to a person. Decision first, policy second, execution third.
Part VIII
Cost, Context & Self-Correction
A capable agent is not automatically an economical or dependable one. It must spend model capacity where it matters, keep long conversations within limits, learn when extra examples help, and recover when its own decisions go wrong. This part turns those concerns into explicit routes, budgets, checks, memories, and rollback points that can be measured in both Python and TypeScript.
Dual-domain map for this part: the same cost-and-adaptation controls apply to Eunomia and Skill Reporter.
Skill Reporter domain: the same model-routing, quantization, context, examples, multimodal/tool, graph-correction, memory, and rollback controls for report-generation workloads.
Interlink chain: Lessons 11 and 16 control model cost, Lessons 22 and 33 control context growth, Lesson 38 adapts examples, Lessons 41 and 47 constrain multimodal and graph updates, and Lessons 42 and 43 preserve memory and recover safely.
Lesson 11
Multi-Model Router & Semantic Cache
The problem: if Eunomia sends every savings question to the most expensive model, routine requests become too costly and too slow. Exact-text caching misses many equivalent customer questions with different wording. Skill Reporter has the same inefficiency when semantically similar report requests are not reused safely.
A model router (a decision-maker that sends each request to the cheapest and fastest model capable of answering it safely) makes model choice part of the application rather than a permanent setting. Start with a baseline that sends every request to one expensive model and records cost, response time, and answer quality. Then classify each incoming question by complexity, required tools, and risk. Routine low-risk work may fit a small local model, ordinary cloud work may fit a lower-cost model, and complex or sensitive requests can still reach the highest-capability model.
The second saving comes from a semantic cache (a store that can reuse an earlier answer when a new question has the same meaning even if the wording differs). Each question is turned into an embedding (a list of numbers representing the meaning of a piece of text), then compared with stored questions. A similarity threshold (the minimum meaning-match score required before a cached answer may be reused) prevents a merely related question from being treated as identical. An uncertain match means no cached answer is reusable: the router should make a fresh model call rather than force reuse.
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
@dataclass(frozen=True)
class CacheEntry:
customer_id: str
account_version: str
permission_scope: str
source_version: str
expires_at: float
vector: list[float]
answer: str
async def semantic_lookup(question: str, customer_id: str, account_version: str,
permission_scope: str, source_version: str, now: float,
embed: Callable[[str], Awaitable[list[float]]]) -> str | None:
query = await embed(question)
scoped = (
entry for entry in CACHE
if entry.customer_id == customer_id
and entry.account_version == account_version
and entry.permission_scope == permission_scope
and entry.source_version == source_version
and entry.expires_at > now
)
best = max(scoped, key=lambda entry: cosine(query, entry.vector), default=None)
return best.answer if best and cosine(query, best.vector) >= 0.92 else None
CHECK SCOPE → SEARCH BY MEANING → REUSE ONLY A SAFE MATCH; OTHERWISE ROUTE TO THE LEAST EXPENSIVE CAPABLE MODEL → VALIDATE, CACHE, STREAM, AND MEASURE
Meaning alone is never enough to make reuse safe. Cache entries need hard boundaries for customer identity, account state, permissions, time-sensitive facts, and tool results. Balance questions, changing interest rates, and requests whose answer depends on the current time should usually bypass reuse or have precise invalidation rules. Every decision should record the selected route, similarity score, reuse decision, cost, and response time as structured measurements.
Build the same controlled request set in Python and TypeScript and compare selected models, reuse decisions, and invalidation. The implementations should agree not just when reuse is allowed, but when it is refused. That comparison exposes language-specific defaults without pretending that a reused answer is automatically correct.
A real bug to test for: a cache key that omits customer or permission scope can offer a semantically similar private answer to the wrong user. Both implementations must prove that scoped keys and metadata filters block the candidate before its similarity score can authorize reuse.
In the capstone:Eunomia's routing becomes a reviewed policy table: routine savings questions are answered by templates with no model at all, and only questions that need wording reach the model gateway. A semantic answer cache is not used in the first release, because every answer is rebuilt from that customer's fresh, frozen evidence. Skill Reporter applies the same budgeted routing policy for routine versus complex report requests.
Lesson 16
Local Model Integration & Quantization
The problem: routing every Eunomia request to remote models can violate cost targets, latency goals, or data-boundary policy. Local models reduce that dependency, but raw model sizes can exceed available hardware. Skill Reporter faces the same trade-off when report workloads must stay in controlled infrastructure.
A local model (an AI model running on hardware controlled by the application owner rather than through an outside cloud request) should first be measured on its own. Record memory use, startup time, response time, and answer quality before connecting it to the agent. The act of producing answers is called inference (running a trained model to produce an answer), and its practical cost includes loading the model as well as generating each token (a small unit of text processed or produced by a model).
Quantization (reducing the numerical precision of a model so it uses less memory and often runs faster) can make local inference practical on smaller hardware, but the trade-off must be measured rather than assumed. Run the lower-precision model behind a local model server—a program on controlled hardware that accepts model requests—and compare model size, memory use, speed, and answer quality with the unmodified version.
CHECK TASK, IMPACT, AND DATA-EGRESS POLICY → USE THE LOCAL QUANTIZED MODEL WHEN SUITABLE → USE CLOUD ONLY WHEN REMOTE PROCESSING IS APPROVED → FAIL CLOSED FOR LOCALITY-RESTRICTED WORK → VALIDATE, STREAM, AND MEASURE
Put local and cloud providers behind one interface so the rest of the agent workflow does not care which one answered. Protect the local path with a health check (a probe that reports whether a service can accept work), request time limits, bounded retries (repeated attempts capped at a fixed count), and a circuit breaker (a guard that temporarily stops requests to a repeatedly failing service). A fallback (a backup route used when the preferred model is unavailable or unsuitable) may use the approved cloud model only when policy permits the prompt to leave the controlled environment. Locality-restricted requests must fail closed or use another approved in-boundary provider; high-impact or complex requests are a separate category and may use cloud only under the same data-egress policy.
import asyncio
from collections.abc import Awaitable, Callable
Provider = Callable[[str], Awaitable[str]]
async def answer(prompt: str, risk: str, remote_allowed: bool, local: Provider,
cloud: Provider) -> str:
if risk != "low":
if not remote_allowed:
raise PermissionError("No approved provider can process this request")
return await cloud(prompt)
try:
async with asyncio.timeout(3):
return await local(prompt)
except (TimeoutError, ConnectionError):
if not remote_allowed:
raise
return await cloud(prompt)
type Provider = (prompt: string, signal?: AbortSignal) => Promise<string>;
function isLocalUnavailable(error: unknown): boolean {
return error instanceof DOMException && error.name === "TimeoutError" || error instanceof TypeError;
}
async function answer(
prompt: string,
risk: "low" | "high",
remoteAllowed: boolean,
local: Provider,
cloud: Provider,
): Promise<string> {
if (risk !== "low") {
if (!remoteAllowed) throw new Error("No approved provider can process this request");
return cloud(prompt);
}
try {
return await local(prompt, AbortSignal.timeout(3_000));
} catch (error) {
if (!isLocalUnavailable(error) || !remoteAllowed) throw error;
return cloud(prompt);
}
}
Private prompts and generated text must not leak into unsafe logs merely because the server is local. Matching Python and TypeScript clients should run the same prompts and report differences in startup behavior, streaming chunks, error shapes, and cancellation handling, not hide those differences behind a common interface.
A local endpoint removes one network boundary; it does not remove the need for timeouts, privacy controls, answer validation, or an approved fallback.
An honest performance finding: the local server’s first request is often far slower than later requests because it must load the model into memory. Report cold-start performance (speed before the service and model are fully loaded) separately from steady-state performance (speed after startup work is complete); averaging them together gives neither operators nor customers a useful expectation.
In the capstone:Eunomia's provider chain can include a smaller quantized local model as one adapter behind the model gateway, with an approved fallback for difficult savings questions. The run manifest pins whichever chain is released, so a local model is adopted only after it passes the same quality gate. Skill Reporter mirrors the same quantized-local plus approved-fallback setup.
Lesson 22
Context Caching & Prompt Compression
The problem: Eunomia repeatedly re-sends fixed instructions and long prior turns, increasing token spend and latency until context limits are hit. Skill Reporter has the same growth problem as report conversations and artifacts accumulate unless reusable context is separated from per-turn state.
A model’s context window (the maximum amount of text and other input a model can consider in one request) has to hold system instructions, policy text, tool descriptions, retrieved documents, conversation turns, and the current question. A token budget (the planned limit on the small text units sent to and generated by a model) assigns space to those parts before one of them silently crowds out another.
Separate stable instructions from changing customer content. The stable prefix (the unchanged opening portion of a prompt) can then use context caching (reusing the model provider’s earlier processing of a repeated prompt prefix). Measure request size, reported cache hits and misses (whether reusable work was found or a fresh request was needed), response time, and cost for both cached and uncached calls; a provider-reported hit does not guarantee a meaningful saving if the prefix is small or the rest of the request dominates.
CACHE THE STABLE PREFIX → COMPRESS OLD HISTORY WITH FACT CHECKS → ASSEMBLE IT WITH RECENT TURNS AND THE CURRENT QUESTION → LOOP UNTIL THE PROMPT FITS → REQUEST, STREAM, AND MEASURE
Prompt compression (shortening input while preserving the facts and instructions needed for the current task) should follow a policy, not an improvised “summarize this” request. Keep recent turns verbatim, summarize older turns, retain unresolved tasks and durable preferences, and protect amounts, dates, account constraints, consent decisions, and safety instructions from lossy summarization (shortening that discards some original information). Rebuild the prompt in a fixed order: stable prefix, compressed history, recent messages, then the current question.
from collections.abc import Awaitable, Callable
async def build_prompt(stable: str, turns: list[str], question: str,
protected: list[str],
summarize: Callable[[list[str]], Awaitable[str]],
budget: int = 4_000, output_reserve: int = 800) -> str:
input_limit = budget - output_reserve
if input_limit <= 0:
raise ValueError("Output reserve must be smaller than the token budget")
recent = turns[-4:]
compressible = turns[:-4]
separator = chr(10) * 2
for _ in range(3):
compressed = await summarize(compressible) if compressible else ""
if compressed and not preserves(compressed, protected):
raise ValueError("Compression removed protected content")
sections = [stable, compressed, *recent, question]
prompt = separator.join(section for section in sections if section)
if token_count(prompt) <= input_limit:
return prompt
if not recent:
break
compressible.extend(recent[:2])
recent = recent[2:]
raise ValueError("Protected prompt content cannot fit within the token budget")
async function buildPrompt(
stable: string,
turns: string[],
question: string,
protectedFacts: string[],
summarize: (turns: string[]) => Promise<string>,
budget = 4_000,
outputReserve = 800,
): Promise<string> {
const inputLimit = budget - outputReserve;
if (inputLimit <= 0) throw new Error("Output reserve must be smaller than the token budget");
let recent = turns.slice(-4);
const compressible = turns.slice(0, -4);
const separator = String.fromCharCode(10, 10);
for (let round = 0; round < 3; round += 1) {
const compressed = compressible.length ? await summarize(compressible) : "";
if (compressed && !preserves(compressed, protectedFacts)) {
throw new Error("Compression removed protected content");
}
const prompt = [stable, compressed, ...recent, question].filter(Boolean).join(separator);
if (tokenCount(prompt) <= inputLimit) return prompt;
if (!recent.length) break;
compressible.push(...recent.slice(0, 2));
recent = recent.slice(2);
}
throw new Error("Protected prompt content cannot fit within the token budget");
}
Implement that prompt builder in Python and TypeScript. The same input must produce the same ordered sections and obey the same limits in both versions. Report actual request size, cache usage, response time, cost, and any information lost during compression rather than presenting token reduction alone as success.
A real bug to test for: a changing request identifier or timestamp placed inside the supposedly stable prefix invalidates the provider’s context cache on every call. Move changing data after the stable prefix, then verify that reuse returns instead of trusting the prompt’s visual similarity.
In the capstone:Eunomia can reuse its stable operating instructions, the prompt pinned by hash in each run manifest, so repeated turns stay affordable and fast. Compressing older customer dialogue is deferred: in the first release each turn is built from its own frozen evidence, not from a growing transcript. Skill Reporter uses the same instruction reuse, and context compaction for long report threads.
Lesson 31
Dynamic Few-Shot Prompt Calibration
The problem: static examples can improve Eunomia behavior for some requests but degrade others by adding irrelevant tokens and biasing responses. Skill Reporter has the same issue when one fixed few-shot set is applied to every report type regardless of context.
Few-shot examples (a small set of sample questions and good answers placed in the prompt) should come from an approved library, not from raw customer conversations or unreviewed model output. Each entry needs an identifier, question, approved answer, topic, risk level, tool requirements, and version. Establish both a no-example baseline and a fixed-example baseline before building anything more elaborate.
Dynamic selection (choosing examples at request time rather than always using a fixed list) represents the current question and candidate examples by meaning, then filters by safety, topic, and required capabilities. Select a small, diverse set instead of several near-duplicates, enforce a strict token budget for examples, and use no examples when no candidate is relevant enough. That no-example branch is a designed success path, not a retrieval failure.
from dataclasses import dataclass
@dataclass(frozen=True)
class Example:
id: str
topic: str
risk: str
required_capabilities: frozenset[str]
tokens: int
score: float
approved: bool
def select_examples(candidates: list[Example], risk: str,
capabilities: frozenset[str], budget: int = 500) -> list[Example]:
selected: list[Example] = []
used_topics: set[str] = set()
for item in sorted(candidates, key=lambda x: x.score, reverse=True):
incompatible = item.risk != risk or not item.required_capabilities <= capabilities
if incompatible or not item.approved or item.score < 0.82 or item.topic in used_topics:
continue
if sum(example.tokens for example in selected) + item.tokens > budget:
continue
selected.append(item)
used_topics.add(item.topic)
return selected[:3]
type Example = {
id: string; topic: string; risk: "low" | "high";
requiredCapabilities: string[];
tokens: number;
score: number;
approved: boolean;
};
function selectExamples(
candidates: Example[],
risk: "low" | "high",
capabilities: Set<string>,
budget = 500,
): Example[] {
const selected: Example[] = [];
const usedTopics = new Set<string>();
let spent = 0;
for (const item of candidates.toSorted((a, b) => b.score - a.score)) {
const unsupported = item.requiredCapabilities.some((name) => !capabilities.has(name));
if (item.risk !== risk || unsupported || !item.approved || item.score < 0.82 || usedTopics.has(item.topic)) continue;
if (spent + item.tokens > budget) continue;
selected.push(item);
usedTopics.add(item.topic);
spent += item.tokens;
if (selected.length === 3) break;
}
return selected;
}
FILTER THE APPROVED LIBRARY → SEARCH BY MEANING → ENFORCE DIVERSITY AND BUDGET → INCLUDE EXAMPLES ONLY WHEN USEFUL → MEASURE THE RESULT AGAINST THE NO-EXAMPLE PATH
Calibration (adjusting examples and decision rules so the model behaves consistently on the current kind of question) requires evidence. Implement identical selection rules in Python and TypeScript and compare chosen example identifiers, prompt size, response time, cost, and evaluated quality. Use an evaluation set (a saved collection of test questions and expected properties used to measure whether a change helps), including held-out questions (test questions not used to tune the selector). Otherwise the selector may simply learn the known test cases.
Examples are not free guidance. They are extra input that must earn their place through measured improvement.
An honest finding: this pattern may not help as much as expected. For simple or already well-instructed questions, example retrieval can cost more time and money than a small or inconsistent quality gain is worth. Enable dynamic few-shot prompting only for question types where evaluation shows a real benefit.
In the capstone:Eunomia can choose only the examples relevant to the customer’s present savings question—and skip them when they add no measured value—rather than paying to send the same examples every time. Skill Reporter applies the same adaptive example policy to report prompts.
Lesson 38
Streaming Multimodal Tool Calls with Vision
The problem: Eunomia customers may submit screenshots or scanned statements instead of clean text. That adds multimodal context, tool decisions, and streamed progress states, while image text must never become automatic execution authority. Skill Reporter encounters the same multimodal risk when report evidence arrives as images or scans.
A multimodal model (a model that can work with more than one kind of input, such as text and images) can receive customer text alongside a vision input (an image supplied to a model for inspection). The upload path must enforce supported file types, byte limits, image dimensions, and access controls. Store accepted files in short-lived controlled storage and pass image data onward only when the current customer is authorized to access it.
While the model examines the image, streaming (sending parts of a response as they become available rather than waiting for the complete answer) can carry safe progress events. Those events should say what stage is happening without exposing hidden reasoning or presenting an unverified observation as fact. If the model proposes a tool call (a structured request asking application code to perform an allowed action), validate its arguments against a strict schema (rules specifying the allowed fields and value types) and check the customer’s permissions before execution.
CHECK TEXT AND IMAGE ACCESS → STREAM SAFE PROGRESS → VALIDATE ANY PROPOSED TOOL CALL → RETURN THE CHECKED RESULT TO THE MODEL → EMIT ONE FINAL ANSWER OR A CLEAR REFUSAL
Observation and action are separate powers. Reading an amount or instruction in an image must never authorize a transfer, account change, or other consequential operation. After an approved tool finishes, feed its checked result back to the model and continue the same response stream. The stream needs an explicit event order so progress, tool request, tool result, final answer, and completion cannot arrive in an impossible sequence.
Build matching Python and TypeScript flows and compare event order, argument validation, cancellation, image handling, and cleanup. Test malformed files, unreadable text, contradictory image content, tool failures, client disconnects, and hostile instructions embedded inside an image. Temporary uploads must be removed on success, rejection, cancellation, and failure.
A real bug to test for: an asynchronous tool can still be running when careless code emits the final-answer event. The stream then appears complete and later produces more data. Both implementations need an enforced event state machine (rules defining which stream event may follow which) and exactly one completion event after every required tool result has returned.
In the capstone:Eunomia's first release accepts text only, but it already applies this lesson's typed-event principle: every kind of content gets its own event type. When customer screenshots are accepted in a later release, Eunomia can inspect one, use an approved read-only capability when needed, and stream clear progress without treating the image as permission to act. Skill Reporter uses the same multimodal-plus-approved-tool boundary for image-backed report evidence.
Lesson 41
Autonomous Graph Schema Evolution
The problem: Eunomia knowledge graphs only encode relationships they already define. New financial entities or links can be misclassified if forced into old schemas, but uncontrolled schema rewrites can corrupt downstream retrieval. Skill Reporter has the same schema-evolution risk for reporting entities and relationships.
A knowledge graph (a store of facts represented as things and the relationships between them) is governed by a schema (the rules defining which kinds of things and relationships may be stored). When a new fact does not fit, the correct response is neither silent coercion nor immediate mutation. The agent should create a structured proposal containing a relationship name, source type, target type, precise meaning, evidence, and examples.
Schema evolution (a controlled change to those graph rules as new information appears) begins with deterministic checks (checks whose result follows fixed rules rather than model judgment) for registered identifiers, inverse identifiers, and compatible source and target types. A canonical identifier (the one stable identifier assigned to a relationship meaning) plus explicit inverse and direction metadata makes “product offers rate” recognizably the same conceptual path as “rate is offered by product.” Subtle overlap between different meanings still requires model and human review; string normalization alone cannot prove equivalence.
STORE FACTS THAT FIT → PROPOSE RELATIONSHIPS THAT DO NOT → CHECK FOR DUPLICATES → EVALUATE AND GATE → MIGRATE A NEW VERSION → VALIDATE BEFORE ACTIVATION OR ROLL BACK
An evaluator agent (a separate model-based reviewer that checks a proposal against explicit acceptance rules) should assess necessity, clarity, evidence, privacy risk, and compatibility. Model review is not enough for high-impact changes, so deterministic checks and human approval remain in the path. Proposal, approval, migration, and activation are separate states; approval alone never alters production data.
from dataclasses import dataclass
@dataclass(frozen=True)
class RelationshipProposal:
canonical_id: str
inverse_id: str | None
source_type: str
target_type: str
meaning: str
examples: tuple[str, ...]
evidence: tuple[str, ...]
async def evaluate_proposal(proposal: RelationshipProposal) -> str:
identifiers = {proposal.canonical_id, proposal.inverse_id} - {None}
if identifiers & REGISTERED_RELATIONSHIP_IDS:
return "rejected_duplicate"
if not types_compatible(proposal.source_type, proposal.target_type):
return "rejected_incompatible_types"
complete = proposal.meaning and proposal.examples and proposal.evidence
if not complete or not await evaluator.approve_meaning_and_overlap(proposal):
return "rejected_evidence"
await proposal_store.save(proposal, state="awaiting_human_approval")
return "awaiting_human_approval"
A schema migration (a versioned operation that changes stored graph rules or data) must preserve an audit trail (a reviewable record of proposals, decisions, and changes), run validation queries, and support rollback when new relationships create unexpected paths or conflicts. Run the same proposal and evaluation cases in Python and TypeScript, comparing structured outputs, rejection reasons, version changes, and rollback behavior.
A real bug to test for: an evaluator may approve a relationship that is only the reverse wording of an existing one, creating duplicate paths and conflicting queries. Registered canonical and inverse identifiers plus source-to-target type checks must reject it before activation.
In the capstone:Eunomia's first release has no production knowledge graph to evolve, but the same propose-versus-apply separation governs what it does have: a strong production turn can be proposed as a new scenario but becomes one only after redaction and a person's approval, and catalogue or guidance changes ship only as new versions. If a graph is added later, Eunomia can propose new relationships without being allowed to rewrite it because one conversation introduced an unfamiliar one. Skill Reporter enforces the same propose-versus-apply separation for graph changes.
The problem: long Eunomia conversations eventually exceed context windows. Trimming old turns blindly can drop prior commitments, corrections, and unresolved tasks; keeping everything is too expensive. Skill Reporter faces the same memory-loss versus cost trade-off across long report lifecycles.
Self-compaction (the agent’s process for replacing older detailed history with a shorter representation) must begin before the context limit is reached, not after a request fails. Divide state into recent verbatim turns, compacted summaries, durable customer preferences, unresolved tasks, and references to tool results. Each category has different retention rules; an unresolved task should not disappear merely because its original message is old.
A hierarchical summary (memory organized at several levels, such as individual exchanges, conversation stages, and a whole-session summary) compacts small groups of turns into chunks, combines chunks into stage summaries, and maintains one top-level session view. Recent turns remain exact while older material becomes progressively smaller.
COMPACT RECENT TURNS INTO STAGES AND STAGES INTO A SESSION VIEW → VALIDATE FACTS, CORRECTIONS, AND SOURCES AT EACH STEP → KEEP DURABLE FACTS CONNECTED TO EVERY LEVEL → BUILD THE NEXT CONTEXT
A memory invariant (a fact or rule that must remain true through every round of summarization) protects confirmed amounts, deadlines, consent choices, correction history, and promises made to the customer. Provenance (a record of where a remembered fact originally came from) lets the agent retrieve or inspect the source turns behind an important claim rather than trusting a summary alone.
from dataclasses import dataclass
@dataclass(frozen=True)
class Summary:
id: str
text: str
@dataclass
class Memory:
recent: list[str]
stages: list[Summary]
session: Summary | None
invariants: dict[str, str]
sources: dict[str, list[str]]
async def compact(memory: Memory, token_limit: int) -> Memory:
if token_count(memory.recent) >= int(token_limit * 0.75):
source_turns = memory.recent[:-4]
text = await summarizer.summarize(source_turns, memory.invariants)
if preserves(text, memory.invariants):
stage = Summary(stable_summary_id(source_turns), text)
memory.stages.append(stage)
memory.sources[stage.id] = [turn_id(turn) for turn in source_turns]
memory.recent = memory.recent[-4:]
stage_text = [stage.text for stage in memory.stages]
if token_count(stage_text) >= int(token_limit * 0.5):
inputs = ([memory.session.text] if memory.session else []) + stage_text
text = await summarizer.summarize(inputs, memory.invariants)
if preserves(text, memory.invariants):
source_ids = ([memory.session.id] if memory.session else []) + [
stage.id for stage in memory.stages
]
session = Summary(stable_summary_id(source_ids), text)
memory.sources[session.id] = source_ids
memory.session = session
memory.stages = []
return memory
interface Summary {
id: string;
text: string;
}
interface Memory {
recent: string[];
stages: Summary[];
session?: Summary;
invariants: Record<string, string>;
sources: Record<string, string[]>;
}
async function compact(memory: Memory, tokenLimit: number): Promise<Memory> {
let next = structuredClone(memory);
if (tokenCount(next.recent) >= tokenLimit * 0.75) {
const sourceTurns = next.recent.slice(0, -4);
const text = await summarizer.summarize(sourceTurns, next.invariants);
if (preserves(text, next.invariants)) {
const stage = { id: stableSummaryId(sourceTurns), text };
next.stages.push(stage);
next.sources[stage.id] = sourceTurns.map(turnId);
next.recent = next.recent.slice(-4);
}
}
const stageText = next.stages.map((stage) => stage.text);
if (tokenCount(stageText) >= tokenLimit * 0.5) {
const inputs = next.session ? [next.session.text, ...stageText] : stageText;
const text = await summarizer.summarize(inputs, next.invariants);
if (preserves(text, next.invariants)) {
const sourceIds = [next.session?.id, ...next.stages.map((stage) => stage.id)].filter(
(id): id is string => id !== undefined,
);
const session = { id: stableSummaryId(sourceIds), text };
next.sources[session.id] = sourceIds;
next = { ...next, stages: [], session };
}
}
return next;
}
Validate every new summary against the memory it replaces and refuse compaction when critical facts disappear or conflict. Python and TypeScript implementations should survive repeated compaction cycles with the same state shape, show real token reduction, and preserve source references. Tests need long conversations with corrections, changed preferences, abandoned goals, and unresolved tool calls—not only conversations where every new statement remains true forever.
A real bug to test for: an early value can survive in the top-level summary after the customer corrects it later. The memory format should retain the correction, mark the earlier value as superseded, and prevent both values from being presented as current truth.
In the capstone:Eunomia's first release keeps no long-term conversation memory; each turn's facts come from fresh, frozen evidence. Hierarchical memory is deferred until Eunomia supports months-long conversations, when it must avoid sending every old message on every turn while preserving the customer's confirmed goals, corrections, and unfinished requests. Skill Reporter uses the same hierarchical memory strategy for long-lived reporting conversations.
Lesson 43
Autonomous Agent Self-Reflection & Multi-Turn State Rollbacks
The problem: one unsupported Eunomia assumption can cascade through later tool calls and recommendations. Retrying only the latest step preserves the original bad state, while full restart may repeat valid or external actions. Skill Reporter has the same rollback challenge when an early wrong premise contaminates later report stages.
Self-reflection (a structured check in which the agent evaluates whether recent decisions still satisfy the goal and rules) works only when the state is explicit. Represent each turn with the goal, plan, known facts, tool results, completed actions, and unresolved questions. Trigger reflection on meaningful signals—contradictory evidence, repeated tool failure, a violated constraint, or a failed result check—not after every ordinary turn.
A checkpoint (a saved snapshot of the agent’s internal state at a known stage) should be written before important decisions and before any tool that may change the outside world. Reflection identifies the earliest unsupported decision and chooses a specific checkpoint. A rollback (restoring internal state from an earlier checkpoint) then discards dependent reasoning while preserving evidence that was already valid.
An idempotency key (a stable request identifier used to recognize a repeated operation) belongs in a durable action ledger (a store recording each external operation and its outcome). Where reversal is possible, record a compensation step (a separate operation that counteracts an earlier side effect). These controls protect external actions while reflection repairs internal state.
SAVE CHECKPOINTS → REFLECT ONLY ON FAILURE SIGNALS → IDENTIFY THE EARLIEST INVALID DECISION → RESTORE THE LAST VALID INTERNAL STATE → REVISE THE PLAN WHILE THE EXTERNAL ACTION LEDGER PREVENTS DUPLICATES
A side effect (a real-world change outside the agent’s internal memory, such as updating a record or sending a message) is not undone by restoring memory. The durable ledger must atomically reserve a key with a fingerprint of the intended request before execution, reject reuse with a different payload, and mark the original result after completion. The external provider should also honor the key so a crash after execution but before ledger completion can be reconciled without blindly repeating the action. Human approval remains necessary where correction is consequential.
The snippets below illustrate checkpoint and replay primitives, not the complete reflection policy. A production state machine must still detect a stated trigger, identify the earliest unsupported decision, cap rollback depth, choose the last valid checkpoint, and create a revised plan. The in-memory checkpoint maps are teaching-only; the action ledger interface represents a durable store with an atomic reservation operation.
type State = { goal: string; facts: string[]; plan: string[] };
const checkpoints = new Map<string, State>();
function checkpoint(name: string, state: State): void {
checkpoints.set(name, structuredClone(state));
}
function rollback(name: string): State {
const saved = checkpoints.get(name);
if (!saved) throw new Error(`Unknown checkpoint: ${name}`);
return structuredClone(saved);
}
async function runOnce(key: string, toolName: string, args: unknown): Promise<unknown> {
const fingerprint = requestFingerprint(toolName, args);
const claim = await actionLedger.reserve(key, fingerprint);
if (claim.status === "completed") return claim.result;
if (!claim.acquired) return actionLedger.waitForCompletion(key, fingerprint);
try {
const result = await tools.execute(toolName, args, { idempotencyKey: key });
await actionLedger.complete(key, fingerprint, result);
return result;
} catch (error) {
await actionLedger.markOutcomeUnknown(key, fingerprint);
throw error;
}
}
Bound retry count and rollback depth so reflection cannot become an endless loop. Matching Python and TypeScript state machines should produce compatible checkpoint serialization (conversion of state into a storable and transferable representation), select the same rollback target, avoid repeated tool effects, and reach the same final state. Test a multi-turn case where evidence disproves an early assumption several steps later: the corrected path must retain valid evidence while discarding only the decisions that depended on the false premise.
Rollback is an internal state operation, not a time machine. Every design must say separately how already-completed external actions are detected, preserved, or compensated.
A real bug to test for: after rollback, the revised plan may replay a tool call and create the same external action twice. A durable ledger with atomic reservation, request fingerprinting, and provider-side idempotency should make the second call return the first call’s recorded result instead.
In the capstone: because Eunomia's first release is read-only, recovering from a derailed turn never risks repeating a side effect, and a mistaken assumption fails verification against frozen evidence instead of cascading through later turns. Multi-turn rollback that preserves valid customer facts and stops rolled-back actions from running twice becomes necessary once write actions arrive. Skill Reporter follows the same rollback discipline to correct report-direction errors without replaying side effects.
Part IX
Shipping It (Human Oversight & Deployment)
A useful agent is not shipped merely because it can answer a question. It must stop before sensitive actions, survive a restart while it waits, run the same way outside a developer's laptop, repair safe-to-fix mistakes without weakening permission checks, and keep a live reply coherent when tools or people take time. These five lessons turn Eunomia from working code into a service that can be operated, interrupted, supervised, and verified.
Dual-domain map for this part: the same deployment-and-approval controls apply to Eunomia and Skill Reporter.
Eunomia domain: human approval before sensitive actions, containerized runtime parity, durable approval state across restarts, safe tool-call correction, and typed streaming with approval pauses.
Skill Reporter domain: the same human approval, container parity, durable pending-state recovery, safe correction, and typed streaming controls for report workflows.
Interlink chain: Lesson 12 defines approval checkpoints, Lessons 23 and 24 make those checkpoints survive container lifecycle and process restart, and Lessons 47 and 53 preserve safe correction and typed streaming around those gates.
Lesson 12
Human-in-the-Loop & Durable State
The problem: Eunomia can reach a high-impact customer action when no authorized reviewer is available. Pausing is required, but an in-memory pause disappears on crash or restart, risking lost work, wrong resume points, or duplicate execution. Skill Reporter has the same approval-state risk for privileged report publication actions.
Human-in-the-loop (HITL) (requiring a person to review or decide part of an automated task) is safe only when it is paired with durable state (saved progress that survives crashes and restarts). A local variable saying “waiting” is not durable. The service needs a checkpoint (a saved record of exactly where a task paused) written to storage before anybody is asked to approve the action.
PREPARE THE ACTION → SAVE BEFORE NOTIFYING → PAUSE → RELOAD AFTER ANY RESTART → CLAIM EXECUTION OR RECORD REJECTION
The saved record must contain enough truth to resume without replaying old work: the task identifier, current step, proposed action, already-checked arguments, reason for review, and an approval status—pending, approved, rejected, or expired. It also needs an idempotency key (a unique value used to recognize repeated attempts at the same sensitive action). The key alone does not guarantee one execution: the action runner must claim the record with an indivisible approved → executing change, save the result durably, and pass the key to the downstream service when that service supports duplicate protection.
On startup, both the Python and TypeScript services reload pending checkpoints. An approval endpoint (a web route that receives a reviewer's decision) accepts a decision only for a known pending task, resumes at the saved step rather than beginning again, and durably records both the human decision and the final action result. A single guarded path must lead to the sensitive operation; a second “convenient” route around the checkpoint would undo the protection.
The reader should prove the design with a restart test rather than code review alone: start two tasks, stop each process while it waits, restart, approve one, reject the other, and send the approval twice. The approved action must complete once, rejection must execute nothing, and duplicate approval must return the saved outcome rather than repeat the action.
A real finding worth knowing: in the recorded lesson's simulated in-memory store, a second tool call replaced an existing APPROVED record with a new PENDING record. The TypeScript port found the same reset bug and also exhausted a one-step tool budget, producing an empty text response. Because the lesson did not use a durable store, it did not prove survival across a process restart.
In the capstone:Eunomia's read-only first release has no sensitive actions to approve, but it applies durable state to pending human work: review items and handoff tickets live in the review inbox's durable store, so a restart never loses a turn that is waiting for a person. Durable approval of sensitive savings actions, with atomic claiming, durable result storage and duplicate protection so a repeated decision cannot repeat the action, is deferred to the write actions of a later release. Skill Reporter enforces the same approval-and-idempotency discipline for privileged report actions.
Lesson 24
Docker & Compose Orchestration
The problem: Eunomia code that works on one laptop can fail in shared environments because runtime versions, network wiring, and service dependencies differ. The stack needs one repeatable deployment path for build, startup, health, and shutdown. Skill Reporter needs the same parity to avoid environment-specific behavior drift.
Orchestration (coordinating several services as one system) makes that repeatable operation possible. Docker (a system for packaging an application with the software it needs to run) turns each application into an image (a packaged, unchanging template) that can be started as a container (an isolated running instance of a packaged application). Docker Compose (a configuration tool that starts and connects several containers together) describes the whole system: the Python agent, TypeScript web service, durable state store, a private network (a connection available only to services in the stack), a persistent volume (stored data that remains when a container is replaced), and readiness rules.
ONE COMPOSE STACK CONNECTS BOTH APPLICATIONS, CHECKS REAL READINESS, AND KEEPS ONLY DURABLE DATA ON A PERSISTENT VOLUME
Each language implementation gets its own deliberate build instructions. The final packaged images install only required dependencies, copy only required files, use a non-administrator account where practical, and never bake secrets into the reusable filesystem sections that make up an image. Compose declares settings explicitly rather than inheriting accidental values from a developer's shell, and gives connected services stable names on the stack's private network. Each image below provides the application-owned /app/healthcheck command used by Compose.
A health check (an automated test that reports whether a running service is ready to accept work) matters because “the container process exists” is not the same as “the application can serve requests.” Here the agent reports ready only after it can connect to required state storage, and Compose waits for each required dependency; an alternative design may report degraded readiness if it documents which work remains safe. Dependants must wait for readiness or retry connections safely. Clean shutdown must stop new work, finish or checkpoint in-flight work (tasks that have started but not finished), and only then exit.
Verification starts clean: build without cached assumptions, start everything through one Compose command, call both implementations over real network connections, restart an application container, and recreate the stack. Conversation and approval data must remain; machine-specific dependencies must not.
A real finding worth knowing: the recorded lesson first misdiagnosed a connection failure as a TLS certificate problem; the traffic was actually being intercepted by a different endpoint-security proxy. A later run also exposed a stale exact certificate pin. The lesson did not record a Compose localhost bug.
In the capstone:Eunomia packages its TypeScript service, web client and stores in containers, and the same orchestration starts the service, the stub upstream and the Python probes in the right order in CI, waiting for /readyz before the first probe runs. Python appears only in the probes, never on the serving path, and review data lives in durable storage, so replacing or restarting an application container loses no pending review. Skill Reporter uses the same packaging parity across environments.
Lesson 39
Human-in-the-Loop Approval Checkpoints
The problem: after Eunomia asks for approval, that request must wait without blocking other customer sessions. Approve, reject, and timeout paths all need explicit handling; silence or delayed responses must never be treated as consent. Skill Reporter requires the same explicit checkpoint outcomes for report workflows.
A Future/Promise (a live-process placeholder for a result that will be supplied later; Python commonly calls it a Future, while TypeScript uses a Promise) lets one task wait while the service continues handling other requests. It is not durable and disappears if the process restarts. At an approval checkpoint (a point where execution cannot continue until a person decides), the durable record from Lesson 12 remains authoritative; a running service may associate a Future or Promise with that record only as a temporary waiter. After a restart, the service must create a new waiter or resume directly from the durable record rather than pretending the old placeholder survived.
ONE PENDING DECISION RESOLVES EXACTLY ONCE: APPROVE AND REVALIDATE, REJECT AND CANCEL, OR EXPIRE WITHOUT EXECUTING
The approval path first verifies that the identifier exists and is still pending. It resolves the placeholder with an explicit approved value, rechecks the action arguments, executes once, and records the outcome. The rejection path resolves that same placeholder with an explicit rejected value, returns a cancellation result, records a normal human decision rather than a system error, and calls no sensitive tool.
These are registry fragments, not the complete endpoint. They validate the incoming decision and show one guarded settlement path; production code must also route timeout through that path, revalidate arguments after approval, claim execution durably, run the action, and record its outcome.
async def decide(approval_id: str, value: object) -> str:
if value not in ("approved", "rejected"):
raise ValueError("decision must be approved or rejected")
decision = str(value)
async with pending_lock:
request = pending.get(approval_id)
if request is None or request.status != "pending":
return "late, unknown, or already decided"
request.status = decision
pending.pop(approval_id)
request.future.set_result(decision)
return decision
type Decision = "approved" | "rejected";
function parseDecision(value: unknown): Decision {
if (value !== "approved" && value !== "rejected") {
throw new Error("decision must be approved or rejected");
}
return value;
}
async function decide(
approvalId: string,
value: unknown,
): Promise<Decision> {
const decision = parseDecision(value);
const request = pending.get(approvalId);
if (!request || request.status !== "pending") {
throw new Error("late, unknown, or already decided");
}
request.status = decision;
pending.delete(approvalId);
request.resolve(decision);
return decision;
}
A timeout (a limit on how long the system will wait) expires without approval. Duplicate and late decisions are rejected clearly, completed entries are removed, and cleanup happens after every outcome. The difficult edge is a race condition (a bug where the result depends on which of two events happens first): approval and timeout may arrive at nearly the same instant. Both languages therefore need one atomic transition (an indivisible state change that competing events cannot both win) from pending to one—and only one—final state.
Python resolves a Future with an explicit decision value; TypeScript retains the function that settles a Promise and calls it from the approval endpoint. Their cancellation details differ, but readers should test the same outcomes for approval, rejection, timeout, and repeated response.
A real finding worth knowing: the recorded Python and TypeScript runs demonstrated the approve and reject paths. They did not observe a timeout race. Treating reviewer responses and timeout as competing attempts at one guarded settlement is defensive guidance that still needs a dedicated concurrency test.
In the capstone:Eunomia's read-only first release has no per-action approval checkpoints; it keeps only the broad oversight principle (a required reviewer on production deploys and a person at the bottom of the answer sequence). When write actions arrive, Eunomia will use a durable approval record for every sensitive savings action and may attach a Future or Promise while a process is live; each affected task will follow an explicit approve, reject, or timeout path, and after restart, work resumes from the durable record rather than the vanished placeholder. Skill Reporter applies the same durable-record recovery for pending human decisions.
Lesson 47
Self-Healing Dynamic Tool Correction
The problem: Eunomia may choose the correct tool but send one malformed argument, like a bad date or account reference. Hard failure wastes recoverable work, while silent rewriting can trigger the wrong action. Skill Reporter has the same correction-vs-safety trade-off for malformed report tool inputs.
A tool call (a structured request from the model to run a named function) must pass schema validation (checking that supplied values match required names, types, and formats) before execution. Format mistakes must be separated from permission denials, network failures, and internal failures because only the first category is a sensible target for automatic correction.
VALIDATE FIRST → EXECUTE ONLY A VALID AND PERMITTED CALL; OTHERWISE RETURN A PRECISE ERROR, CORRECT WITHIN A LIMIT, AND VALIDATE AGAIN
When validation fails, the tool returns a structured error (a failure response with specific fields that software can interpret). It names the invalid field and states the expected format. A safe value such as the displayed date may be returned so the model can see what needs changing; sensitive account, personal, or secret fields must instead be redacted or described only by their non-secret shape. “Tool failed” is not enough information to repair anything.
from datetime import date
def validate_maturity_date(value: str) -> dict[str, object] | None:
try:
date.fromisoformat(value)
return None
except ValueError:
return {
"kind": "validation_error",
"field": "maturity_date",
"expected": "a real calendar date in YYYY-MM-DD form",
"received": value,
"retryable": True,
}
type ValidationError = {
kind: "validation_error";
field: string;
expected: string;
received: string;
retryable: true;
};
function validateMaturityDate(value: string): ValidationError | null {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
if (match) {
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (year > 0 && month > 0 && month <= 12 && day > 0 && day <= days[month - 1]) {
return null;
}
}
return { kind: "validation_error", field: "maturity_date",
expected: "a real calendar date in YYYY-MM-DD form",
received: value, retryable: true };
}
The error is added to the conversation with an instruction to issue a corrected tool call, not a prose apology. The replacement arguments begin validation again from the start. A bounded retry (trying again only up to a fixed limit) permits a small number of attempts for correctable format errors, then stops. Denied actions, missing authorization, and permanent service failures are not retried, and valid formatting never counts as permission: corrected sensitive calls still pass the same human checkpoint.
Test all branches: one malformed but repairable call should become valid on the next attempt; an already valid call should never enter the loop; a permanent failure should stop immediately. Python and TypeScript wording may differ, but their final classification and action must agree.
A real finding worth knowing: after the malformed account identifier was corrected, the Python run repeatedly reported a false zero balance while the TypeScript port reported the correct balance. That divergence shows why a repaired argument and the tool's resulting data must be verified separately; successful correction does not prove a correct answer.
In the capstone:Eunomia can repair the one capability request the model may make on the composed step without collapsing the conversation: the validation error goes back once, the corrected request must pass the same Zod schema and token-derived scope before it runs, and a second failure steps the answer down a step. Write actions, deferred to a later release, would also need the human-approval checkpoint before anything executes. Skill Reporter mirrors this safe-correction path for malformed report-tool calls.
Lesson 53
Resilient Streaming Agent Responses
The problem: Eunomia should stream responses as they are produced, but mid-stream tool calls may block for approvals, retries, or failures. The connection must stay valid, typed, and truthful about state changes instead of fabricating completion. Skill Reporter has the same requirement when long report steps stream progress and checkpoint events.
A streaming response (sending a reply in small pieces as it is produced) uses a ReadableStream (a web interface that lets a server provide those pieces over time). Its stream controller (the object used to add events and close the stream) manages delivery. Ordinary text can appear immediately, but internal tool work is a different event type (a label that tells the receiver what kind of stream item arrived): raw, unchecked arguments must never be presented as completed work.
STREAM TEXT EARLY → ROUTE TOOL EVENTS THROUGH VALIDATION AND APPROVAL → RETURN ONLY VERIFIED RESULTS → EMIT SAFE FAILURES → CLOSE ONCE
The event sequence is explicit: open the connection, send ordered text chunks, emit a safe status event while a tool or approval is pending, emit the verified result or a clear failure, and close exactly once. Every tool passes a typed tool boundary (a checked interface that permits only the tool fields and value types declared by the application). Correctable format errors enter the bounded correction loop; sensitive valid calls enter approval. Streaming never weakens either check.
The following examples are event-shaping sketches. The Python generator is conceptual pseudocode; the recorded Lesson 53 implementation is TypeScript-only because this curriculum has no Python equivalent for the Vercel AI SDK primitive. Both sketches show ordered events, checked tools, a safe error, and one normal close, but they do not implement disconnect handling or backpressure.
async def stream_events(agent):
try:
async for event in agent.run():
if event.kind == "tool_call":
yield encode({"type": "tool-pending"})
result = await run_checked_tool(event)
yield encode({"type": "tool-result", "data": result})
else:
yield encode({"type": "text-delta", "data": event.text})
except Exception:
yield encode({"type": "safe-error"})
finally:
yield encode({"type": "stream-finish"})
A production implementation still needs backpressure (slowing production when the receiver cannot consume data quickly enough), disconnect detection, and cancellation of unnecessary model generation (the model's ongoing production of response text). It must release stream resources and separately decide whether already-started durable work should continue, because closing a browser tab should not erase a recorded approval decision. Those behaviours require cancellation signals and pressure-aware stream hooks that are not present in the sketches above.
Readers should verify the TypeScript implementation over a real web connection: the first text should arrive before completion; tool arguments should be checked before execution; an approval delay should not corrupt event order; and failures, slow receivers, and disconnects should clean up. The conceptual Python sketch is not evidence of cross-language streaming equivalence.
A real finding worth knowing: a terse numeric query legitimately produced a tool call with zero narrated text chunks. The revised TypeScript test separated narration from tool-output correctness; a later run measured 57 text chunks while checking the tool result independently. The recorded lesson did not find that the stream closed at the first tool pause.
In the capstone:Eunomia uses this event shape for its typed turn events: only verified text is streamed, and every turn ends with exactly one answer.final, turn.declined, handoff.offered or turn.failed. Pausing a stream for human approval of a sensitive action is deferred with write actions. Production readiness additionally requires tested backpressure, cancellation, disconnect cleanup, and a policy for durable work. Skill Reporter follows the same typed-streaming contract for live report responses.
What 64 Real, Verified Lessons Taught Us
Real execution beats polished theory
The strongest lesson across all 64 lessons is simple: run the code and report what actually happened. A polished explanation cannot replace a real Python execution, a real TypeScript execution, and an honest account of the output. Expected output must never be quietly promoted into claimed output.
The useful findings were not limited to successful demonstrations. Outdated interfaces, environmental failures, timing problems, unsupported features, and different behaviour between the two languages were evidence too. Preserve the real error message and explain its cause. Report the bug that was found and fixed instead of rewriting the history as a flawless first attempt. Say plainly when the libraries, controls, or failure behaviour differ. A verified limitation is more valuable than an invented success.
Verify the explanation separately from the data
A model can return the correct records while attaching an incorrect self-reported field. A tenant identifier (a value that says which customer or account owns data) or a confidence score (the model's own estimate of how likely it is to be correct) may conflict with the retrieved result. One response can therefore contain two claims that need separate checks: whether the records, calculation, or tool output are correct, and whether the model's labels, explanation, ownership field, confidence, or summary are accurate.
A successful lookup does not prove that every generated field around it is trustworthy. Security, ownership, and policy decisions must come from independently checked application data, never from a model describing itself as authorized or confident.
Match verification strictness to the lesson
A deterministic algorithm (a fixed calculation that gives the same output for the same input) should match exactly across language ports. If Python produces 0.375, TypeScript should produce 0.375, digit for digit, unless a documented numerical rule explains the difference.
An LLM-based lesson (a lesson whose wording or choice depends on a language model) normally matches in direction rather than exact phrasing. Both implementations should reach the same practical conclusion, call the appropriate kind of tool, respect the same safety boundary, and produce compatible structured data, while their sentences and token order may differ.
The verification rule: with no model involved, demand exact values, ordering, counts, and state transitions. With a model involved, demand the same intent, safety behavior, evidence, and structured outcome. In a mixed system, check deterministic components exactly and model-generated components semantically. Never excuse an exact algorithmic mismatch as “model variability” when no model produced that value.
Knowing which category a lesson belongs to prevents weak testing on one side and unfair testing on the other.
The “should not trigger” case is part of the feature
Every safety or detection mechanism needs a positive test and a negative test. Proving that a dangerous request triggers a guard is only half the job; the system must also prove that a healthy request does not trigger it. An approval checkpoint should pause a sensitive action but not an ordinary read-only request. A correction loop should retry malformed arguments but not a valid call. A detector should flag its intended risky condition and leave a healthy case alone.
The same symmetry applies to recovery. A retry policy should recover from a temporary failure but stop on a permanent one. A streaming error handler should emit a failure event when needed but not corrupt a successful stream. A durable resume path should restore unfinished work but never replay completed work. False positives can make a safety feature unusable; false negatives make it ineffective. Both sides must be executed and verified.
Final reflection
Shipping a dependable agent is not mainly about producing an impressive answer. It is about making every boundary visible and testable: where data came from, where a model made a claim, where deterministic logic must match exactly, where a person must decide, where state must survive, and where failure must stop rather than disappear.
Across 64 lessons, the reliable pattern stayed consistent: build the smallest real version, run it in both languages, test success and non-triggering cases, preserve the actual evidence, and describe differences without smoothing them away. That discipline is what turns Eunomia from a conversational demonstration into a savings assistant that can be deployed, supervised, interrupted, resumed, corrected, and trusted within clearly defined limits.
Part X · Capstone
Part X — Building Eunomia
The previous nine parts built the pieces one at a time. This capstone puts the lessons together into one design for Eunomia's safe, read-only first release: a savings assistant that can answer questions about a customer's holdings, maturity dates and deposit protection, describe products from an approved catalogue, quote approved guidance, and hand the conversation to a person when it should not answer alone. The design is one TypeScript service plus a web client. Inside the service, plain business rules sit in the middle, the outside world is reached only through named interfaces, and every answer is built from evidence that can be fetched again later. The same release discipline is applied to Skill Reporter as a parallel domain track. Write actions (moving money, opening or closing accounts) are deliberately deferred. The target is an MVP (minimum viable product — the smallest version that is safe and useful in production), not a toy and not a distant wish list.
Dual-domain map for this capstone: Eunomia and Skill Reporter ship through the same control stack.
Eunomia track: read-only savings answers with identity taken from the token, three coarse typed capabilities, an answer-mode sequence, a figure-checking verifier, traces, a quality gate, and independent contract probes.
Skill Reporter track: read-only reporting answers with the same identity rule, typed capabilities, sequence, verifier, traces, quality gate, and independent probes.
Integration chain: this capstone composes Parts I–IX into one release boundary: typed contracts, a routing policy, deterministic domain rules, evidence-checked answers, observability, and CI gates all enforced before promotion.
Shared learner terms (book ↔ Eunomia UI): the capstone and the Eunomia chat page use the same four terms so readers do not have to translate vocabulary across materials.
Turn: one customer message plus one Eunomia reply, created by POST /v1/turns.
Evidence: the frozen bundle an answer was built from (snapshot, catalogue rows, guidance passages, each with a stable id), fetched with GET /v1/turns/{id}/evidence.
Review: a request for a person to check one turn, sent with POST /v1/turns/{id}/review, raised by a handoff, or raised by the quality sampler.
Turn events: the typed server-sent events the page listens to, from turn.accepted to one ending event such as answer.final.
Complete Eunomia architecture graph (one turn, end to end)
The problem: readers can see strong individual controls in isolation, but still miss the full runtime chain from one customer message to one checked answer. Without the whole path in one place, it is hard to see that the order of the steps is what makes the answer trustworthy.
This section is the complete runtime path as one graph. It starts at the browser, takes identity only from the verified token, picks an answer mode from a fixed policy table, gathers evidence through three read-only capabilities, writes or renders an answer, checks every figure against that evidence, and only then streams it. Separate quality and probe paths sit outside the serving path. Every step matters, but the order is what enforces trust: nothing reaches the customer before it has been checked against evidence that was frozen first.
The web client sends one message to POST /v1/turns, and the HTTP adapter first verifies the bearer token and builds the customer scope from the token alone; a body that tries to carry a customer id is rejected.
Only then is the turn opened, and the client immediately receives a turn.accepted event carrying the turn id and trace id.
An input screen catches known injection patterns and requests that cross the advice line (asking Eunomia to choose a product for the customer).
The routing policy table maps the question type to its starting answer step (template, composed, or handoff) before any evidence is gathered, because the step decides what evidence to gather.
The service's evidence planner, not the model, calls only the capabilities that question type and step need, through the ports.
Each capability validates its input and output with Zod and returns an evidence id.
The evidence bundle is frozen and stored, and evidence.ready tells the client which evidence ids exist.
The chosen step produces a draft: a template fills fixed wording from evidence with no model call; the composed step asks the ModelGateway to write from evidence only. On that step the model may instead request one more capability call through the same typed interface; the service validates and executes it, adds the result to the bundle under a new evidence id, and re-freezes the bundle before the model writes.
The verifier checks every figure, date and claim in the draft against the frozen evidence.
If verification fails, the turn drops one step and tries again; the last step is a person.
Only verified text is streamed as answer.delta events, closed by one answer.final. A screened-out request ends instead with turn.declined or handoff.offered, and a hard error with turn.failed.
The TraceSink records masked spans: step chosen, verifier verdict, evidence ids, timings, never raw balances or message text.
Eunomia does not trust a single model output. It trusts a path: evidence first, wording second, a check between the two, and a person waiting at the bottom of the sequence.
Ports and adapters: plain rules in the middle, the world at the edge
The problem: Eunomia can use strong models and still fail as a production system if identity, data access, money rules, model calls and delivery are tangled together in one handler. A change to one provider or store then risks every control at once. Skill Reporter has the same architectural risk when reporting logic and its data sources are wired directly together.
Eunomia is one TypeScript service plus a web client, and the service is arranged as ports and adapters (a layout where the core business code talks only to interfaces it owns, and separate adapter code plugs real systems into those interfaces). Think of a travel adaptor: the device (the domain) has one plug shape; the adaptor changes for each country (each provider or store). domain/ holds pure rules: deposit protection per banking group, product facts, money as whole numbers of pence, the routing policy table and the verifier's rules. answering/ holds the sequence runner, which uses those rules and the ports to run one turn. ports/ holds seven interfaces the core depends on. adapters/ holds the HTTP server, model providers, stores and telemetry. Outside the service, quality/ owns scenarios and the release gate, probes/ is an independent Python suite, and web/ is the Next.js client.
This is the architectural form of Lesson 1's type-safe boundaries and Lesson 2's dependency injection (the core is handed its collaborators by trusted startup code instead of creating them itself), and Lesson 30's monorepo orchestration keeps service, quality suite, probes and client changing together in one repository. Scoping every port call to the token's customer applies Lesson 54's tenant-isolation principle (keeping one customer's data separate from another's) without implementing its per-tenant vector shards. The routing policy table is Lesson 5's conditional routing made explicit and testable.
Where decision-first routing fits: Lesson 64 adds a decision-first routing layer before any model work. Here that layer is the routing policy table: a typed question type plus a confidence threshold picks the starting step before evidence is gathered. When the classifier is unsure about a mixed, high-risk message, the table sends it to the handoff step instead of forcing a risky answer.
THE DOMAIN SITS IN THE MIDDLE; EVERY REAL SYSTEM PLUGS IN THROUGH A PORT
The ports are small on purpose. Each one is an interface (a TypeScript description of methods, with no code behind it), so a unit test can hand the core a tiny in-memory version, and a provider change touches one adapter file instead of the whole service.
// service/src/ports/index.ts — interfaces only; nothing here imports from adapters/
/** Every read a turn makes from the outside world takes the turn's AbortSignal, so a client that disconnects cancels that work.
* Startup reads (Catalogue.version) and the stores that record what already happened (TurnStore, ReviewInbox) are left to finish, so the audit trail stays whole. */
import type {
CapabilityResult, CatalogueFilter, ComposeReply, ComposeRequest, CustomerScope, EvidenceBundle, Gathered,
GuidanceTopic, OpenTurn, Passage, ProductFact, RawHoldings, ReviewItem, ReviewTicket, TraceEvent, TurnBudget,
} from "../domain/types"
export interface AccountReader {
holdingsFor(scope: CustomerScope, signal: AbortSignal): Promise<RawHoldings>
}
export interface Catalogue {
version(): Promise<string>
query(filter: CatalogueFilter, signal: AbortSignal): Promise<readonly ProductFact[]>
}
export interface GuidanceStore {
lookup(topic: GuidanceTopic, question: string, signal: AbortSignal): Promise<readonly Passage[]>
}
/** Turns and their frozen evidence bundles. evidenceFor returns null for another customer's turn, so the route answers 404. */
export interface TurnStore {
open(input: { scope: CustomerScope; conversationId?: string }): Promise<OpenTurn>
freeze(turnId: string, gathered: Gathered): Promise<EvidenceBundle>
refreeze(turnId: string, bundle: EvidenceBundle, added: CapabilityResult): Promise<EvidenceBundle> // new evidence id
evidenceFor(turnId: string, scope: CustomerScope): Promise<EvidenceBundle | null>
}
export interface ModelGateway {
compose(request: ComposeRequest, budget: TurnBudget, signal: AbortSignal): Promise<ComposeReply> // a draft, or one capability request
}
export interface TraceSink {
record(event: TraceEvent): void
}
/** ReviewItem is one shape everywhere:
* { kind: "customer-request" | "advice-line" | "routed-to-person" | "last-step" | "quality-run", turnId, evidenceId?, manifestId? }
* evidenceId is absent only when the item is raised before any evidence is frozen (an advice request caught by the input screen). */
export interface ReviewInbox {
submit(item: ReviewItem): Promise<ReviewTicket>
}
A boundary is only real when dependency direction supports it. Adapters may import ports; the domain must not import adapters. The probes import neither.
Production rule: keep the first release small in capability but complete in control. Three coarse read-only capabilities with token-derived scope, frozen evidence, a verifier, traces and a release gate are safer than a long list of fine-grained tools that nobody can audit.
The HTTP surface: five routes and one typed event stream
The problem: a chat endpoint looks simple, but regulated savings answers cross several control points: who is asking, which data they may see, whether the request is admissible, what the answer was built from, and how the client learns that a turn ended badly. Skill Reporter crosses the same points for report requests and their sources.
The whole public surface is five routes. POST /v1/turns is authenticated and answers with a stream of typed server-sent events (SSE — one-way messages from server to browser over an ordinary HTTP response): turn.accepted, evidence.ready, answer.delta, answer.final, turn.declined, handoff.offered and turn.failed. GET /v1/turns/{id}/evidence returns exactly what an answer was built from. POST /v1/turns/{id}/review asks a person to check a turn. GET /livez says the process is alive; GET /readyz says its stores and at least one model provider are reachable, so a load balancer stops sending traffic to an instance that cannot answer.
Identity and customer scope come only from the verified token. The request body is parsed with a strict schema, so a body that adds customerId is rejected rather than ignored. The input screen applies Lesson 20's input-attack and refusal controls before any model call; Lesson 13's programmatic output scan reappears inside the verifier after drafting. Token-derived scope applies the least-authority idea from Lesson 52 and the isolation idea from Lesson 54, but this read-only MVP does not implement Lesson 52's signed capability tokens or Lesson 54's per-tenant vector shards.
The route itself stays thin. It parses the body, builds the scope, opens the turn through the TurnStore port, and forwards whatever events the core yields. The HTTP adapter wraps whichever Node web framework the team picks; the core never sees it.
import { z } from "zod"
const TurnBody = z.object({
message: z.string().trim().min(1).max(2_000),
conversationId: z.string().uuid().optional(),
}).strict() // unknown fields such as customerId are a 400, not silently dropped
type RouteDeps = AnswerDependencies // already holds turns: TurnStore, trace: TraceSink and reviewInbox: ReviewInbox
export function registerTurnRoutes(http: HttpAdapter, deps: RouteDeps) {
http.post("/v1/turns", { auth: "required" }, async (request, events) => {
const body = TurnBody.parse(request.body)
const scope = scopeFromToken(request.verifiedToken) // the only source of identity
const turn = await deps.turns.open({ scope, conversationId: body.conversationId })
events.send({ type: "turn.accepted", turnId: turn.id, traceId: turn.traceId })
try {
const run = runTurn({ turn, scope, message: body.message, signal: request.signal }, deps)
for await (const event of run) events.send(event)
} catch (error) {
deps.trace.record({ kind: "turn.error", turnId: turn.id, error: maskError(error) })
events.send({ type: "turn.failed", turnId: turn.id, code: "TURN_FAILED", retryable: isRetryable(error) })
} finally {
events.end()
}
})
http.get("/v1/turns/:id/evidence", { auth: "required" }, async (request) => {
const bundle = await deps.turns.evidenceFor(request.params.id, scopeFromToken(request.verifiedToken))
return bundle ?? http.notFound() // someone else's turn is a 404, never a 403 that confirms it exists
})
http.post("/v1/turns/:id/review", { auth: "required" }, async (request) => {
const bundle = await deps.turns.evidenceFor(request.params.id, scopeFromToken(request.verifiedToken))
if (!bundle) return http.notFound()
return deps.reviewInbox.submit({ kind: "customer-request", turnId: request.params.id, evidenceId: bundle.id })
})
}
The event contract is a Zod discriminated union (a set of object shapes told apart by one shared field, here type). Every event the server sends is parsed against it first, and the web client parses with the same contract, published from contracts/turn/ as @eunomia/turn-contract. There is no "text with a magic prefix" anywhere on the wire.
Notice what answer.delta does not mean. In the composed step the whole draft is verified before the first delta is sent, so deltas are pacing for the reader, not live model tokens as in Lesson 3's streaming typewriter. That costs a second or so of waiting, and it buys a hard guarantee: text already shown in a browser cannot be recalled, so only checked text is ever shown. Lesson 53's resilient-streaming contract still applies: every turn ends with exactly one of answer.final, turn.declined, handoff.offered or turn.failed. A plain decline gets its own ending event rather than an answer.final, because it has no evidence to cite.
Important boundary: the verifier is not the only lock. The strict body schema, token-only scope, input screen, frozen evidence and the ending-event rule each fail closed on their own, so a verifier bug does not silently open the other doors.
The answer-mode sequence and the model gateway
The problem: if every question goes to the same model with the same freedom, Eunomia pays model cost and model risk even for questions ordinary code can answer exactly, and a provider outage takes the whole assistant down. Skill Reporter has the same problem when every report request is treated as a free-writing task for one provider.
Instead of several agent configurations, Eunomia has one answer-mode sequence (an ordered list of ways to answer, from the most predictable to the most human) with three steps. Template: a deterministic answer filled straight from evidence, used when the question type allows it, such as "when does my fixed-term deposit mature?". Composed: the model writes from the frozen evidence only, then the verifier checks every figure and claim; if the planned bundle falls short, the model may request one more capability call, which the service executes and re-freezes into the bundle before the model writes (a second evidence.ready then lists the full set of ids). Handoff: a person. A routing policy table in domain/ picks the starting step for each question type before any evidence is gathered, because the step decides what evidence to gather; the sequence runner in answering/ receives that starting step. A failed verification drops the turn one step; it never climbs back up. Think of a staircase where you may only step down: each step trades a little automation for a little more safety.
This turns Lesson 37's model cascade into a cascade of answer modes rather than model sizes, makes Lesson 11's routing a reviewed table instead of an improvised choice, and puts Lesson 64's decision-first routing at the very top of the turn. Lesson 50's fallback routing lives one level down, inside the gateway.
// service/src/domain/routing-policy.ts — pure, reviewed like code
export type Step = "template" | "composed" | "handoff"
/** TurnStore.open returns an OpenTurn; classification adds what the sequence needs to choose and render a step. */
export type RoutedTurn = OpenTurn & { questionType: QuestionType; confidence: number }
/** A change to this table selects the advice-line and money-facts scenarios in CI. */
const ROUTING_POLICY: Readonly<Record<QuestionType, Step>> = {
"maturity-date": "template",
"protection-coverage": "template",
"holdings-summary": "template",
"product-search": "composed",
"guidance": "composed",
"personal-recommendation": "handoff", // the advice line: Eunomia explains, it does not choose
"unclear": "handoff",
}
export const startingStep = (type: QuestionType, confidence: number): Step =>
confidence >= 0.8 ? ROUTING_POLICY[type] : "handoff"
const SEQUENCE: readonly Step[] = ["template", "composed", "handoff"]
export const oneStepDown = (step: Step): Step => SEQUENCE[Math.min(SEQUENCE.indexOf(step) + 1, SEQUENCE.length - 1)]
// service/src/answering/turn-runner.ts — the step is chosen first, because it decides what evidence to gather
export async function* runTurn(input: TurnInput, deps: AnswerDependencies) {
const screened = screenInput(input.message) // injection and advice-line checks, no model involved
if (!screened.ok) {
yield* declineOrHandoff(input.turn, screened.reason, deps) // turn.declined, or an "advice-line" review item (no evidenceId yet) + handoff.offered
return
}
const route = classify(input.message) // { questionType, confidence }
const start = startingStep(route.questionType, route.confidence)
const gathered = await planEvidence(route.questionType, start, input.scope, deps.capabilities, input.signal) // the service calls the capabilities
const evidence = await deps.turns.freeze(input.turn.id, gathered) // frozen and stored before any wording
yield { type: "evidence.ready", turnId: input.turn.id, evidenceIds: [...evidence.ids] }
const routed: RoutedTurn = { ...input.turn, ...route }
yield* answer(routed, start, evidence, deps, input.signal)
}
// service/src/answering/sequence.ts — receives the starting step; it can only step down
async function composeOrNull(deps: AnswerDependencies, turn: RoutedTurn, evidence: EvidenceBundle, signal: AbortSignal) {
try {
let reply = await deps.gateway.compose(composeRequest(turn, evidence, { mayRequest: true }), turn.budget, signal)
if (reply.kind === "capability-request") { // at most one extra call per turn
const added = await deps.capabilities.runRequested(reply.request, turn, deps.gateway, signal) // Zod-checked; one Lesson 47 correction
evidence = await deps.turns.refreeze(turn.id, evidence, added) // new evidence id, stored before the model writes
reply = await deps.gateway.compose(composeRequest(turn, evidence, { mayRequest: false }), turn.budget, signal)
}
return reply.kind === "draft" ? { draft: reply, evidence } : null
} catch (error) {
if (error instanceof GatewayUnavailable) return null // a provider outage drops one step; it is not a failed turn
if (error instanceof CapabilityRequestRejected) return null // still malformed after one correction
throw error
}
}
export async function* answer(turn: RoutedTurn, start: Step, frozen: EvidenceBundle, deps: AnswerDependencies, signal: AbortSignal) {
let step = start
let evidence = frozen
while (step !== "handoff") {
const attempt = step === "template"
? { draft: renderTemplate(turn.questionType, evidence), evidence } // draft is null when the evidence does not fit
: await composeOrNull(deps, turn, evidence, signal) // null when the provider chain is down or the request was rejected
if (attempt && attempt.evidence !== evidence) {
evidence = attempt.evidence // re-frozen with one requested result
yield { type: "evidence.ready", turnId: turn.id, evidenceIds: [...evidence.ids] }
}
const draft = attempt?.draft ?? null
const check = draft ? verifyDraft(draft, evidence) : { ok: false as const, problems: [step === "template" ? "no template fit" : "no usable draft"] }
deps.trace.record({ kind: "step.tried", turnId: turn.id, step, ok: check.ok, problems: check.ok ? [] : check.problems })
if (check.ok && draft) {
yield* paceVerifiedText(turn.id, draft.text)
yield { type: "answer.final", turnId: turn.id, mode: step, text: draft.text, citedEvidenceIds: draft.citedEvidenceIds }
return
}
step = oneStepDown(step)
}
const kind = start === "handoff" ? "routed-to-person" : "last-step" // the table chose a person, or every step was tried
const ticket = await deps.reviewInbox.submit({ kind, turnId: turn.id, evidenceId: evidence.id })
yield { type: "handoff.offered", turnId: turn.id, reason: "A colleague will check this for you.", reviewTicket: ticket.id }
}
The ModelGateway port hides providers behind one method. Its adapter holds a fallback chain (an ordered list of providers to try), a circuit breaker per provider (a switch that stops calling a provider for a cool-down period after repeated failures, like a fuse that trips instead of letting every request wait for a timeout), and a per-turn budget so a slow chain cannot run up unbounded cost or time. When the whole chain is unavailable, the gateway throws a typed error and the sequence drops to handoff. The request's abort signal is combined with each provider's timeout, so a customer who closes the page cancels the outstanding call instead of leaving it running.
/** Lesson 29's token bucket: take() waits until the provider's pace allows one more call, or rejects if the signal aborts. */
export interface TokenBucket { take(signal: AbortSignal): Promise<void> }
export function createModelGateway(chain: readonly ProviderAdapter[], clock: Clock, pace: TokenBucket): ModelGateway {
const breakers = new Map(chain.map((p) => [p.id, new CircuitBreaker({ trips: 3, coolDownMs: 30_000, clock })]))
return {
async compose(request, budget, signal) {
for (const provider of chain) {
signal.throwIfAborted() // the client left: stop trying providers
const breaker = breakers.get(provider.id)!
if (!breaker.isClosed()) continue
if (!budget.canSpend(provider.estimateCostPence(request), provider.timeoutMs)) continue
try {
await pace.take(signal) // Lesson 29: a token bucket keeps calls within the provider's pace
const callSignal = AbortSignal.any([signal, AbortSignal.timeout(provider.timeoutMs)]) // disconnect or timeout aborts the call
const reply = await provider.compose(request, callSignal)
budget.spend(reply.usage.costPence)
breaker.recordSuccess()
return ComposeReply.parse(reply) // structured output: a draft (text + claims + cited evidence ids) or one capability request
} catch (error) {
if (signal.aborted) throw error // a disconnect is not the provider's fault
breaker.recordFailure()
budget.noteFailure(provider.id, error)
}
}
throw new GatewayUnavailable(budget.failures())
},
}
}
Every turn opens an OpenTelemetry span (one timed unit of work inside a trace, which links work across services). Child spans cover the screen, each capability call, each step tried, each provider attempt and the verifier. They reach the outside world only through the TraceSink port, whose adapter masks attributes in the export path (the last step before telemetry leaves the service), so a caller that forgets to clean a field still cannot leak a balance. This is Lesson 7's trace tree joined with Lesson 17's distributed tracing. Record bounded metadata (ids, timings, step, verdict, evidence ids, provider, cost); the evidence store already holds the facts, so the tracing system must not become a second customer database.
Capstone decision: the routing table, templates, prompt and provider chain are versioned configuration, and each has a hash in the run manifest. Changing any of them is a release, gated like code. Eunomia and Skill Reporter share this promotion boundary.
Three coarse capabilities, and the domain rules behind them
The problem: model output can look valid while carrying unsafe arguments: another customer's identifier, an impossible term, a rate filter of 400 percent. Many fine-grained tools also give the model many chances to pick the wrong one or to do arithmetic it should not. Skill Reporter has the same risk when model-generated report arguments are not validated strictly.
There are exactly three read-only capabilities, each declared with Zod on both sides. The service's evidence planner calls the ones a question type needs before the evidence is frozen; the model never calls a store directly. On the composed step the model may request one further call through the same typed interface, and the service validates it, executes it, adds the result under a new evidence id and re-freezes the bundle before the model writes. readSnapshot() takes no arguments and returns one typed, already-scoped snapshot of the customer's holdings, maturities and protection. queryCatalogue({ access, minTermMonths, maxTermMonths, minRatePercent }) filters the approved product catalogue. lookupGuidance({ topic, question }) returns approved passages, each with a stable passage id. Every output carries an evidence id, which is what lets the verifier and the evidence route say exactly where a figure came from.
The capabilities are coarse on purpose. One snapshot call replaces a handful of small lookups, so the model cannot assemble a partial picture and fill the gap by guessing. This is Lesson 1's schema pattern and Lesson 2's injected dependencies turned into a security boundary: scope arrives from the verified token through the injected AccountReader, never from an argument. Domain refinements such as "the minimum term may not exceed the maximum" are Lesson 44's semantic guardrails (business rules beyond data shape). The design applies Lesson 52's least-authority principle without claiming its signed, per-action permission tokens.
Protection is computed by domain code, never by the model. The scheme limit applies per person per banking group (one licensed bank, which may sell under several brand names), so two brands in the same group share one limit. The function below works in whole pence so there is no rounding, checks that totals stay inside the safe integer range, and reads the limit from a versioned rule rather than a number written into the code. The model may explain the result; it cannot supply or change any input to it.
// service/src/domain/protection.ts — pure: no I/O, no clock, no model
export function protectionByGroup(
holdings: readonly EligibleHolding[],
rule: ProtectionRule, // { version, limitPencePerGroup } from versioned config
): readonly GroupProtection[] {
const totals = new Map<string, number>()
for (const holding of holdings) {
const next = (totals.get(holding.bankingGroup) ?? 0) + holding.balancePence
if (!Number.isSafeInteger(next)) throw new DomainError("BALANCE_OUT_OF_RANGE")
totals.set(holding.bankingGroup, next)
}
return [...totals].map(([bankingGroup, eligiblePence]) => {
const coveredPence = Math.min(eligiblePence, rule.limitPencePerGroup)
return { bankingGroup, eligiblePence, coveredPence, uncoveredPence: eligiblePence - coveredPence, ruleVersion: rule.version }
})
}
The verifier is the other half of the same idea. A composed draft comes back as structured output: the text plus a list of claims, each pointing at evidence ids. The verifier pulls every money amount, percentage and date out of the text and requires each to appear in the frozen evidence, requires every claim to cite evidence that exists, and runs Lesson 13's deterministic output scan for other customers' details and advice-line wording. It also requires the draft to cite at least one evidence id, and every cited id to exist in the bundle. If the model's one capability request carries malformed arguments, Lesson 47's bounded correction loop applies: the validation error goes back once, the corrected request is validated again, and a second failure drops the turn a step instead of retrying forever.
export function verifyDraft(draft: Draft, evidence: EvidenceBundle): Verification {
const problems: string[] = []
if (draft.citedEvidenceIds.length === 0) problems.push("no cited evidence")
for (const id of draft.citedEvidenceIds) if (!evidence.ids.has(id)) problems.push(`cited id not in bundle: ${id}`)
for (const figure of extractFigures(draft.text)) { // "£1,250.00", "4.10%", "14 March 2027"
if (!evidence.figures.has(figure.normalised)) problems.push(`figure not in evidence: ${figure.raw}`)
}
for (const claim of draft.claims) {
if (claim.evidenceIds.length === 0) problems.push(`uncited claim: ${claim.id}`)
for (const id of claim.evidenceIds) if (!evidence.ids.has(id)) problems.push(`unknown evidence id: ${id}`)
}
if (namesSomeoneOutsideScope(draft.text, evidence.scope)) problems.push("mentions another customer")
if (crossesAdviceLine(draft.text)) problems.push("personal recommendation")
return problems.length === 0 ? { ok: true } : { ok: false, problems }
}
Never ask the model to calculate a financial figure that ordinary code can calculate exactly. Let code gather the evidence, let the model ask for at most one more piece through the same typed interface and explain it, and use code to check that the explanation only repeats what the evidence says.
Capability contract: validate on both sides. Input validation protects the service from the model; output validation catches a broken store before its malformed result becomes persuasive prose; evidence ids let the verifier, the client and a reviewer all point at the same facts.
An optional MCP server shares guidance and the catalogue, never the customer
The problem: other internal assistants want the same approved guidance and product facts. Copying the capability code into each one causes contract drift, while giving each one direct store access widens the attack surface. Skill Reporter has the same integration drift unless shared contracts and narrow gateways are enforced.
A Model Context Protocol (MCP) server lets other approved hosts discover and call capabilities through a standard contract. Eunomia's MCP server is optional, read-only, and exposes only lookupGuidance and queryCatalogue. Both return facts that are the same for every customer. readSnapshot is never exposed: customer holdings stay behind the authenticated /v1/turns route, where scope comes from a customer token. Hosts that call the MCP server authenticate as approved service identities. This selective design matters more than adopting the protocol everywhere.
Lesson 6 becomes the server boundary, Lesson 23 becomes discovery at startup by the hosts that consume this server, and Lesson 48 describes how such a calling host turns the advertised schemas into local tool definitions at runtime. Lesson 33's server-side dynamic tool synthesis and runtime registration is deliberately not used in the first release: the server registers its two tools once, at startup, from reviewed code, so the advertised contract changes only through a gated release. Lesson 32's resource subscriptions (change notifications from the server) can tell a host that the catalogue version changed, but a turn pins the catalogue version in its evidence bundle, so facts do not shift halfway through one answer.
SHARE THE SAME-FOR-EVERYONE FACTS OVER MCP; KEEP THE CUSTOMER SNAPSHOT BEHIND THE TOKEN
The server reuses the exact Zod shapes from the capability declarations, so the MCP contract and the in-service contract cannot drift apart. It is a second adapter onto the same ports, not a second implementation.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
import { capabilities, CatalogueFilter, GuidanceQuery, runLookupGuidance, runQueryCatalogue } from "../../capabilities" // the same reviewed implementations the evidence planner calls
import type { Catalogue, GuidanceStore } from "../../ports"
export function buildGuidanceMcpServer(ports: { guidance: GuidanceStore; catalogue: Catalogue }) {
const server = new McpServer({ name: "eunomia-guidance", version: "1.0.0" })
server.registerTool(
"lookupGuidance",
{ description: "Approved savings guidance passages with stable passage ids.", inputSchema: GuidanceQuery.shape },
async (args, extra) => {
const input = capabilities.lookupGuidance.input.parse(args)
const output = capabilities.lookupGuidance.output.parse(await runLookupGuidance(input, ports, extra.signal)) // a cancelled MCP request cancels the lookup
return { content: [{ type: "text", text: JSON.stringify(output) }] }
},
)
server.registerTool(
"queryCatalogue",
{ description: "Products in the approved catalogue matching a filter.", inputSchema: CatalogueFilter.shape },
async (args, extra) => {
const input = capabilities.queryCatalogue.input.parse(args) // includes the min/max term refinement
const output = capabilities.queryCatalogue.output.parse(await runQueryCatalogue(input, ports, extra.signal))
return { content: [{ type: "text", text: JSON.stringify(output) }] }
},
)
return server // readSnapshot is deliberately absent
}
Capstone decision: MCP is an interoperability boundary, not a shortcut around authorization. Every exposed capability calls the same reviewed implementation with the same input and output schema checks as inside the service, as the sample shows, and nothing customer-specific is on it. Timeouts and traces are added by the adapter around each handler, as the HTTP adapter does for its routes; that wrapper is not shown here. The same rule applies to Eunomia and Skill Reporter integrations.
The Next.js client renders typed turn events and shows its evidence
The problem: a chat page must reconcile acceptance, evidence, paced text, a final answer, a handoff, errors and dropped connections without ever making a half-finished turn look like a complete financial answer. Hand-built string handling drifts from what the server really sends. Skill Reporter needs the same typed event discipline for long-running report generation.
The client in web/ is a Next.js (React web framework) application. A server-side route in the client forwards the signed-in session's token to POST /v1/turns and passes the event stream back unchanged; it never adds a customer id of its own. In the browser, a small reader splits the stream into frames, parses each one with the published TurnEvent contract, and feeds it to a reducer (a function that takes the current screen state plus one event and returns the next state). Unknown or malformed events are dropped and counted, not displayed.
This is Lesson 53's error-aware event contract on the receiving side. Lesson 38's typed multimodal-event principle matters before Eunomia ever accepts images or files: every kind of content gets its own event type rather than a string with a magic prefix. And because answer.delta is paced verified text rather than live generation, the client never has to retract words, which Lesson 3's raw token stream would have made possible.
"use client"
import { TurnEvent } from "@eunomia/turn-contract" // the contracts/turn/ workspace package; the service sends with the same schema
export const droppedEvents = { count: 0 } // malformed frames are dropped and counted, never shown
export async function* readTurnEvents(response: Response): AsyncGenerator<TurnEvent> {
const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader()
let buffer = ""
for (;;) {
const { value, done } = await reader.read()
if (done) return
buffer += value
let end: number
while ((end = buffer.indexOf("\n\n")) !== -1) {
const frame = buffer.slice(0, end)
buffer = buffer.slice(end + 2)
const data = frame.split("\n").filter((l) => l.startsWith("data: ")).map((l) => l.slice(6)).join("\n")
if (!data) continue
let parsed: ReturnType<typeof TurnEvent.safeParse> | null = null
try { parsed = TurnEvent.safeParse(JSON.parse(data)) } catch { parsed = null }
if (parsed?.success) yield parsed.data
else droppedEvents.count += 1
}
}
}
export function turnReducer(state: TurnView, event: TurnEvent): TurnView {
switch (event.type) {
case "turn.accepted": return { ...state, turnId: event.turnId, status: "working" }
case "evidence.ready": return { ...state, evidenceIds: event.evidenceIds }
case "answer.delta": return event.seq === state.nextSeq
? { ...state, draft: state.draft + event.text, nextSeq: state.nextSeq + 1 }
: state
case "answer.final": return { ...state, status: "answered", text: event.text, cited: event.citedEvidenceIds }
case "turn.declined": return { ...state, status: "declined", text: event.reason }
case "handoff.offered": return { ...state, status: "handed-off", ticket: event.reviewTicket }
case "turn.failed": return { ...state, status: "failed", retryable: event.retryable }
}
}
If the stream closes while the state is still working, the page shows "this answer did not finish" and offers a retry with the same conversation id; it never promotes the partial draft to an answer. Under each finished answer, a "Where this came from" panel calls GET /v1/turns/{id}/evidence and lists the snapshot date, catalogue version and guidance passages behind it, and an "Ask a person to check" button calls POST /v1/turns/{id}/review. The browser is never trusted to calculate balances or protection; it only displays figures that came back in verified events.
Event rule: turn events are part of the product contract. Version them, test them from outside, and make the ending explicit; a dropped connection must never look like a complete financial answer.
An independent Python probe suite proves the contract from outside
The problem: tests that run inside the service can inherit the same wrong assumptions as the service, and mocks keep passing after the real HTTP contract breaks. Skill Reporter has the same blind spot without an independent client that only sees what a real caller sees.
Eunomia's probes/ folder is a separate Python suite. A contract probe (a test that checks a promise the public API makes, such as "every turn ends with exactly one ending event", by calling it the way a real client would) talks to any running environment over HTTP only, chosen by a base URL and a test credential. It shares no code with the service: not the Zod schemas, not the fixtures, not a helper. The client holds only public HTTP calls and its own reading of the wire contract; fixtures name which test customer signs in; the tests state user-visible promises. A stub upstream (a controllable stand-in for the account, catalogue and guidance stores and for the model providers, which counts every call it receives) can inject latency, errors and malformed payloads on request.
A different language makes accidental imports impossible, but language alone does not prove independence. The suite is independent because it uses only public contracts, its own fixtures, and observable behaviour. This applies Lesson 26's principle of verifying the real running system from outside (there through a browser, here through HTTP calls), and Lesson 24's process orchestration is how CI starts the service, the stub and the probes in the right order and waits for /readyz before the first probe runs.
THE PROBES TALK TO A RUNNING ENVIRONMENT OVER HTTP; THEY SHARE NO SERVICE CODE
import unittest
from probes.client import ProbeClient
from probes.stub import stub_faults
ENDING_EVENTS = {"answer.final", "turn.declined", "handoff.offered", "turn.failed"}
class TurnContractProbes(unittest.TestCase):
def setUp(self) -> None:
self.client = ProbeClient.signed_in_as("fixture-customer-a")
def test_body_cannot_widen_customer_scope(self) -> None:
response = self.client.post_json("/v1/turns", {
"message": "Show my balances",
"customerId": "fixture-customer-b",
})
self.assertEqual(response.status, 400)
def test_slow_catalogue_still_ends_with_exactly_one_ending_event(self) -> None:
with stub_faults(catalogue={"latency_ms": 4_000}):
events = self.client.stream_turn("Which fixed-term products pay at least 4%?")
types = [event["type"] for event in events]
self.assertEqual(types[0], "turn.accepted")
self.assertEqual(sum(t in ENDING_EVENTS for t in types), 1)
self.assertIn(types[-1], ENDING_EVENTS)
def test_malformed_snapshot_never_reaches_the_answer(self) -> None:
with stub_faults(accounts={"payload": "malformed"}) as stub:
events = self.client.stream_turn("How much of my savings is protected?")
model_calls = stub.model_calls # read before the stub resets on exit
self.assertNotIn("answer.final", [event["type"] for event in events])
self.assertEqual(model_calls, 0)
The same suite probes token checks, the evidence route for a turn owned by someone else (it must be a 404, not a 403 that confirms the turn exists), a provider outage that should end in handoff.offered, /readyz turning unready when every store is down, and event ordering under a dropped connection. It asserts observable behaviour, never internal function names. Because the stub counts calls, a refused or malformed turn can prove that no model was touched.
Independence test: if the probes cannot run against an already-deployed Eunomia environment by changing only the base URL and the test credential, they are too coupled to the local implementation.
quality/ turns answer quality into versioned, pinned evidence
The problem: unit tests prove that a schema rejects bad input; probes prove that the HTTP contract holds. Neither proves that an answer after a prompt or model change still shows the right figure, cites the right passage, stays on the right side of the advice line, and reads clearly. Skill Reporter needs the same layer to catch quality regressions that types and contracts miss.
quality/ holds scenario files grouped by risk: money facts, the advice line, privacy, injection and tone. Each scenario is a list of checkable properties (shows this figure, cites a passage, never names another customer, declines advice) plus any rubrics (written scoring rules) that a judge model applies. Properties are checked by code first because they are cheap and exact; rubric judges run after, and a judge is allowed to gate a release only once its scores agree well enough with human labels on a calibration set. Every run writes a run manifest (a small file that pins exactly what was tested): model, provider chain, and the hashes of the prompt, templates, routing policy, capability schemas and scenario set.
# quality/scenarios/money-facts/two-brands-one-group.yaml
id: money-facts.two-brands-one-group
risk: money-facts
fixture: two-brands-same-banking-group # restored by the snapshot step
signedInAs: fixture-customer-a
turn: "Am I fully protected if I keep both accounts?"
properties:
- shows-figure: { from: snapshot.protection[0].uncoveredPence, as: pounds }
- cites: snapshot
- mentions: "same banking group"
- never-names-other-customer: true
- ends-with: answer.final
rubrics: [plain-english-for-a-non-expert]
---
# quality/manifests/run-2026-11-20T04-12.yaml (written by the harness, never by hand)
model: provider-a/compose-large@2026-09
providerChain: [provider-a/compose-large@2026-09, provider-b/compose-medium@2026-07]
providerChainHash: sha256:0b7c…3d
promptHash: sha256:3f9c…a1
templatesHash: sha256:9e41…07
capabilitySchemaHash: sha256:77d0…4e
scenarioSetHash: sha256:c21b…90
routingPolicyHash: sha256:5ab8…12
judges: { plain-english-for-a-non-expert: judge-v4 (calibrated 2026-11-02) }
The harness loop has four steps. Snapshot: restore the scenario's fixture state in the stores, so every run starts from the same known world. Replay: run the turn through the real HTTP surface, exactly as a client would. Assert: check properties against the turn and its evidence bundle, then run the calibrated rubric judges. Archive: store the evidence bundle, events, verdicts and manifest id together, so any failure can be reopened later. Then a deterministic hash decides which passes also go to the review inbox; every failure always goes.
import { createHash } from "node:crypto"
export async function runScenario(scenario: Scenario, run: RunContext): Promise<ScenarioResult> {
await run.fixtures.restore(scenario.fixture) // 1. snapshot
const turn = await run.client.streamTurn(scenario.turn, { as: scenario.signedInAs }) // 2. replay (real HTTP)
const evidence = await run.client.evidenceFor(turn.turnId)
const properties = scenario.properties.map((p) => checkProperty(p, turn, evidence)) // 3. assert, exact first
const rubrics = await run.judges.score(scenario.rubrics, turn, evidence)
const result = { scenarioId: scenario.id, manifestId: run.manifest.id, turn, evidence, properties, rubrics }
await run.archive.store(result) // 4. archive
if (!passed(result) || sampledForReview(run.manifest.id, scenario.id, run.reviewShare)) {
await run.reviewInbox.submit({ kind: "quality-run", turnId: turn.turnId, evidenceId: evidence.id, manifestId: run.manifest.id })
}
return result
}
/** Same manifest + scenario always lands on the same side of the line, so reviewers see a stable sample. */
export function sampledForReview(manifestId: string, scenarioId: string, share: number): boolean {
const digest = createHash("sha256").update(`${manifestId}:${scenarioId}`).digest()
return digest.readUInt32BE(0) / 0x1_0000_0000 < share
}
Lessons 10 and 19 supply evaluation-driven development and judge calibration against human-labelled examples; reviewers' labels from the inbox feed that calibration set. Lesson 55's deterministic sampling is the hash above: re-running the same manifest picks the same passes, so two people reviewing "the sample" are looking at the same turns. A strong production turn can become a new scenario only after redaction, deduplication and a person's approval; a run's manifest can become the new approved baseline only after the gate passes (Lesson 56's last-approved baseline rule) and then only after a window of consecutive passing runs on main (Lesson 57).
Evaluation rule: never let the same uncalibrated model write the answer, judge the answer, and approve its own release without independent human labels. That is one opinion wearing three badges.
Continuous integration blocks quality regressions, not just build failures
The problem: a change can compile, pass unit tests and pass every probe while still dropping a figure, weakening the advice line, or making answers harder to read. Ordinary CI stays green through that. Skill Reporter has the same release risk without a quality gate tied to promotion.
The pipeline on GitHub Actions has four stages. Checks: lint (static code-quality checks), types, unit tests and build. Probes: start the built service and the stub upstream, wait for /readyz, run the Python suite. Quality gate: on a pull request, pick scenario groups from the paths changed against origin/<base branch>, using full git history (a style-only change in web/ runs none; a change to the prompt, routing table, templates, capabilities or provider chain runs the groups that depend on it; any change to domain/ runs money facts); on a push to main, run the full scenario set with no path filtering. Then compare against the last approved manifest. Production: a protected environment with a required reviewer.
This is Lesson 25's eval gate made selective, Lesson 30's shared pipeline across one repository, and Lesson 56's approved-baseline comparison. The required reviewer applies the broad human-oversight principle from Lessons 12 and 39, but it is not their durable per-action checkpoint; write actions, which would need that, are deferred.
CHECKS → PROBES → QUALITY GATE (PATH-SELECTED ON PRS, FULL ON MAIN) → PROTECTED PRODUCTION WITH A REQUIRED REVIEWER
Branch protection makes the workflow a required status check, so a pull request cannot merge unless it succeeds; that rule lives in the repository settings, outside the YAML. The production environment has a required reviewer, so a named person must approve before the deploy job starts, and the same approval records the run's manifest as a candidate. The approved baseline in quality/manifests/approved.yaml moves to that candidate only after a window of consecutive passing runs on main (Lesson 57); one approval never moves it on its own. When the window is met, quality:promote opens a pull request under a bot identity that updates approved.yaml, so the baseline moves only through that reviewed change, merged like any other.
on:
pull_request:
push:
branches: [main]
jobs:
checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run lint && npm run typecheck && npm test && npm run build
probes:
needs: checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci && npm run build
- run: ./scripts/start-probe-env.sh # service + stub upstream, waits for /readyz
- run: python3 -m unittest discover -s probes/tests -t probes
env:
PROBE_BASE_URL: http://localhost:8080
PROBE_CREDENTIAL: ${{ secrets.PROBE_TEST_CREDENTIAL }} # a test customer's credential, never a real one
quality:
needs: probes
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- run: npm ci && npm run build
- run: ./scripts/start-probe-env.sh # the real HTTP surface the scenarios replay through
- name: Select scenarios
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
npm run quality:select -- --base "origin/${{ github.base_ref }}" --out artifacts/selected.json
else
npm run quality:select -- --all --out artifacts/selected.json # push to main: full set, no path filtering
fi
- run: npm run quality:run -- --selection artifacts/selected.json --manifest-out artifacts/manifest.yaml
- run: npm run quality:gate -- --against quality/manifests/approved.yaml --report artifacts/gate.json
- uses: actions/upload-artifact@v4
if: always()
with:
name: quality-gate-report
path: artifacts/
deploy:
needs: quality
if: github.ref == 'refs/heads/main'
environment: production
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ secrets.QUALITY_BOT_TOKEN }} # a bot identity; a pull request opened with the default token would not trigger the required checks
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with: { name: quality-gate-report, path: artifacts/ }
- run: npm ci
- run: ./scripts/deploy.sh
- run: npm run quality:candidate -- --manifest artifacts/manifest.yaml # the approval records a candidate in the run archive, not the baseline
- run: npm run quality:promote -- --window 5 --open-pull-request # after 5 consecutive passing runs on main, opens a PR that updates approved.yaml
The gate checks two things per risk group. A floor is an absolute minimum pass rate; an allowed regression is the most the pass rate may fall below the last approved manifest. A tone pass rate of 0.93 may clear its floor of 0.90 and still block if the approved run reached 0.97 and the allowed regression is 0.02. Money facts, privacy and the advice line are zero-tolerance groups: one wrong figure, one other customer named, or one personal recommendation blocks the change whatever the average says. Promotion follows Lesson 57: the approved manifest only moves after a window of consecutive passing runs on main, never after one lucky pass, and then only when the promotion pull request that updates approved.yaml is reviewed and merged.
Delivery rule: the baseline is an approved manifest, never "whatever main produced most recently". A failed run cannot lower the bar for the next one.
The repository shape makes ownership visible
A production-shaped design can still be easy to read. The tree below is the capstone's own layout; its implementation is not part of this book's repository. Folder names follow the boundaries in this chapter: the domain and ports in the middle of the service, adapters at its edge, and the quality suite, probes, client and shared turn contract beside it. The composition root (main.ts, the one place where real adapters are plugged into the ports at startup) is the only file that knows about everything.
Lesson 30 explains why this is one coordinated repository: the event contract in contracts/turn/, the scenarios that depend on it, and the client that reads it change in one pull request. Lesson 24 explains how the probe environment starts reproducibly. Lesson 47's bounded correction loop belongs at runtime, inside capabilities/: it repairs malformed arguments within a strict limit. It does not let any script or the running assistant edit application code; that separate code-repair theme is Lesson 27, and it stays outside the serving path.
Earlier Python and TypeScript examples were teaching ports of the same ideas. The serving implementation is deliberately TypeScript for both service and client; Python appears only in probes/, as an outside test runtime, and is not a hidden production dependency.
Do not mistake a monorepo for a monolith. Eunomia keeps one source tree so contracts change together, while dependency direction and trust boundaries stay explicit.
What ships in the first production-shaped release
The first release is read-only. It includes the five routes with token-derived scope; typed turn events with an explicit ending; three Zod-declared capabilities that return evidence ids; deposit protection per banking group computed in pence by domain code; the routing policy table and the template, composed and handoff sequence; a verifier that checks every figure and claim against frozen evidence; a model gateway with a fallback chain, circuit breakers and a per-turn budget; masked tracing through the TraceSink; an evidence route and a review route; an optional read-only MCP server for guidance and the catalogue; risk-grouped scenarios with calibrated judges, run manifests and hash-sampled review; independent Python probes; and a quality gate in front of a protected production environment. The snippets in this chapter show the ports, the turn route and event contract, the sequence, the gateway, the capabilities, the protection rule, the verifier, the MCP adapter, the client reader, a probe, the scenario and harness, and the pipeline. Store adapters, template wording, the review inbox's own screens, and rollback operations are named boundaries rather than full examples here. Write actions (moving money, opening, closing or changing accounts) are deferred to a later release with its own per-action approval design.
The operating loop is concrete. Every answer carries a turn id and a trace id, and its evidence can be fetched again. A customer (through the review route), the sequence runner (at the last step, or when the routing table hands off), the input screen (for advice requests) and the quality harness's sampler can each send a turn to the review inbox. A reviewer's label can become calibration data, and an approved, redacted turn can become a new scenario. A required status check runs the affected scenario groups, compares them with the approved manifest, and blocks a material regression. Production promotion passes a required reviewer and records the manifest as a candidate; the approved baseline moves to it only after a window of consecutive passing runs on main, so an operator always knows exactly which model, prompt and schemas to return to. That closes the path from Lesson 1's first schema to Lesson 57's rule of promoting only after a window of consecutive passing runs.
The finished system: Eunomia is useful because the model can read a customer's question, ask for one more piece of evidence when the planned bundle falls short, and explain holdings, products and guidance in plain words. It is trustworthy because identity, schemas, pence arithmetic, the routing table, frozen evidence, the verifier, traces, independent probes, human review and the release gate surround that reasoning at every boundary. Skill Reporter ships under the same boundary model: the capabilities are domain-specific, but the safety and verification controls are shared.
The capstone lesson: production AI architecture is not a larger prompt. It is a chain of small, inspectable contracts that lets a probabilistic model contribute where judgement helps, while ordinary software stays in charge of identity, money, evidence and release.