01 — Fundamentals & harness
Goal
↓
Context
↓
Model
↓
Policy
↓
Action
↓
Observation
↓
Stop or repeat
Agent
A system that selects actions toward a goal using feedback.
Example: Find a failing test, inspect code, fix it and rerun tests.
Common mistake: A single model call need not be an agent.
Autonomy
The extent to which a system selects its own actions.
Example: Choose which tests to run within a fixed budget.
Common mistake: More autonomy is not inherently better.
Workflow
A predefined sequence or graph of operations.
Example: Lint, test, then publish a report.
Common mistake: A workflow can contain agents.
Agent harness
Software that manages model-driven execution.
Example: Build context, validate tool calls and record results.
Common mistake: The model is not the entire harness.
Runtime
The machinery and environment executing an agent.
Example: A worker process with a tool dispatcher.
Common mistake: Runtime and harness overlap; terminology varies.
Agent loop
Repeated decision, action and observation until termination.
Example: Inspect a test failure and revise a patch.
Common mistake: Always bound the loop.
Orchestration
Coordination of steps, tools and agents.
Example: Run review after implementation.
Common mistake: It can be deterministic.
Provider abstraction
A common interface for model providers.
Example: Swap model adapters while keeping task logic.
Common mistake: Capabilities and behavior are not interchangeable.
02 — Domain-specific agents
Domain goal
↓
Relevant data + skills
↓
Restricted tools
↓
Domain evals
Domain specialization
Configure knowledge, capabilities and constraints for a field.
Example: A Vue repository assistant knows local conventions.
Common mistake: Fine-tuning is optional.
Data
Information available to the agent.
Example: Repository files and approved documentation.
Common mistake: Access does not imply correctness.
Domain evals
Cases and criteria tailored to the domain.
Example: Check that patches pass tests and follow conventions.
Common mistake: Generic benchmarks cannot establish local usefulness.
Schedules
Time-based triggers for execution.
Example: Run dependency review each Monday.
Common mistake: A schedule is not an agent loop.
Channels
Interfaces for interacting with an agent.
Example: Web, Slack or Discord.
Common mistake: Channels are not model providers.
Connections
Configured access to external services.
Example: An authenticated issue tracker integration.
Common mistake: A connection must have scoped credentials.
03 — Context & memory
Sources
↓
Select relevant information
↓
Context window
↓
Model
↓
Update state
Context
Information supplied to the model for a particular call.
Example: Current issue, selected files and tool schemas.
Common mistake: Not all stored information is in context.
Context engineering
Select, structure and prioritize context.
Example: Retrieve only relevant repository conventions.
Common mistake: More context can reduce quality.
State
Current execution information.
Example: Task ID, pending tests and remaining budget.
Common mistake: State is not necessarily long-term memory.
Working memory
Temporary information used during a task.
Example: A list of files already inspected.
Common mistake: May live outside the context window.
Episodic memory
Records of prior events or experiences.
Example: A previous failed migration and its outcome.
Common mistake: Past success does not guarantee future success.
Semantic memory
Stored facts or generalized knowledge.
Example: The project uses Vue 3.
Common mistake: Facts can become stale.
Progressive disclosure
Load details only when relevant.
Example: Read skill metadata first, then its instructions.
Common mistake: Do not assume every framework loads skills identically.
Context inheritance
Passing selected parent context to another execution.
Example: Give a reviewer the patch and requirements.
Common mistake: Do not blindly copy all parent messages or secrets.
04 — Tools, skills, rules & hooks
Model proposes
↓
Pre-tool hook
↓
Permission check
↓
Tool
↓
Post-tool hook
↓
Observation
Tool
Callable operation with an input/output contract.
Example: read_file(path) returns file content.
Common mistake: A tool is not a procedure.
Function calling
Structured model request to invoke a callable operation.
Example: Request run_tests with a suite name.
Common mistake: The runtime executes it, not the model itself.
Skill
Reusable task guidance and supporting resources.
Example: A code-review procedure with scripts and references.
Common mistake: A skill is not necessarily executable.
Project instructions
Repository-specific guidance, often in AGENTS.md or framework-specific files.
Example: Use TypeScript and run lint before review.
Common mistake: File names and precedence vary.
System prompt
High-priority model instructions.
Example: Act as a repository assistant.
Common mistake: Not a hard security boundary.
Rules & policies
Constraints on permitted behavior.
Example: Deny writes outside the workspace.
Common mistake: Enforce hard rules in software.
Hook
Callback triggered at a lifecycle event.
Example: Validate arguments before a tool call.
Common mistake: Function, prompt and agent hooks are framework-specific.
Sandbox
Restricted execution environment.
Example: Run tests without access to production credentials.
Common mistake: Isolation requires explicit configuration.
Computer use
Interaction through graphical interfaces.
Example: Inspect a rendered application in a browser.
Common mistake: Treat page content as untrusted.
Skill directory
code-review/
SKILL.md
scripts/
references/
assets/
Skill directory: code-review/SKILL.md (metadata and instructions), scripts/ (helpers), references/ (supporting knowledge), assets/ (templates). Optional folders; load relevant resources progressively.
05 — MCP, A2A & interoperability
Agent host
↓
MCP client
↓
MCP server
↓
External service
MCP
Model Context Protocol: standardized interaction between hosts/clients and servers.
Example: Discover and call an issue tracker tool.
Common mistake: MCP is not an agent runtime.
MCP server primitives
Tools, resources and prompts exposed by a server.
Example: Read a document resource or invoke search.
Common mistake: These have distinct semantics.
MCP client capabilities
Client-side capabilities can include sampling and roots, depending on negotiation.
Example: A server requests model sampling from a supporting client.
Common mistake: Roots are not a security sandbox.
Discovery
Discover supported capabilities and available operations.
Example: List server tools before selecting one.
Common mistake: Discovery does not grant permission.
A2A
Agent-to-Agent protocol for interoperable agent communication.
Example: Send a task to a separately deployed reviewer.
Common mistake: Not required for local delegation.
Agent Card
Machine-readable agent discovery and capability metadata.
Example: Advertise review skills, endpoint and authentication.
Common mistake: Metadata is not proof of competence.
Protocol boundary
Separate service integration from agent coordination.
Example: Use MCP for repository access and A2A for remote review.
Common mistake: They can coexist.
A2A versus local delegation
A2A connects independent agent services; local subagents can use ordinary function calls or queues.
06 — Composition & multi-agent architectures
Orchestrator
↓
Specialist agents
↓
Structured results
↓
Integration
Composition
Assemble independent modules with defined responsibilities.
Example: Combine retrieval, testing and review modules.
Common mistake: Can occur within one agent.
Inheritance
Reuse or extend configuration or behavior from a base.
Example: A reviewer inherits shared coding conventions.
Common mistake: Context accumulation is not identical to software inheritance.
Subagent
Delegated agent with a scoped task.
Example: Review only security-sensitive changes.
Common mistake: Delegation need not use A2A.
Routing
Select a suitable model, tool or agent.
Example: Route database questions to a SQL specialist.
Common mistake: Routing errors need evaluation.
Planning
Choose or revise a sequence of actions.
Example: Inspect, patch, test, review.
Common mistake: Plans may fail and need revision.
ReAct
Pattern interleaving reasoning and actions with observations.
Example: Search, inspect evidence, then search again.
Common mistake: Does not require exposing private reasoning.
Reflection
Review an output and propose improvements.
Example: Inspect a patch against requirements.
Common mistake: Self-review is not independent evidence.
Consensus
Combine multiple agent judgments under a decision rule.
Example: Vote on whether a patch is acceptable.
Common mistake: Agreement is not proof of correctness.
Handoff contract
Structured input and output for delegation.
Example: Pass patch, scope, budget and expected report schema.
Common mistake: Avoid unrestricted context sharing.
07 — Durable execution & reliability
Execute
↓
Persist checkpoint
↓
Failure?
↓
Resume safely or finish
Durable execution
Persist progress so work can recover after interruption.
Example: Resume a review after worker restart.
Common mistake: Persistence alone does not prevent duplicate effects.
Checkpoint
Saved recoverable execution state.
Example: Record completed tests and pending actions.
Common mistake: Checkpoint before consequential transitions.
Idempotency
Repeated operation has the same intended effect.
Example: Use an idempotency key when creating a ticket.
Common mistake: Retries are not automatically safe.
Retry
Bounded repeat after a recoverable failure.
Example: Retry a temporary API timeout with backoff.
Common mistake: Do not blindly retry irreversible actions.
Fallback
Alternative when the preferred operation fails.
Example: Use cached documentation and disclose its age.
Common mistake: Fallback may reduce quality.
Budget
Limits on cost, tokens, time or actions.
Example: Stop after 20 tool calls or a fixed spend.
Common mistake: Budget exhaustion is not task success.
Termination
Explicit success, failure or stop conditions.
Example: Return when tests pass or report unresolved failures.
Common mistake: Never equate a final message with completion.
Human approval
Explicit authorization before consequential actions.
Example: Ask before merging a patch.
Common mistake: Approval should bind to the specific action.
Least privilege
Grant only necessary access.
Example: Read-only production credentials for diagnosis.
Common mistake: Prompt instructions cannot replace permissions.
08 — Agent evaluation & observability
Eval cases
↓
Agent harness
↓
Output + trace
↓
Graders
↓
Metrics
↓
Improvement
Trace
Recorded execution events and relationships.
Example: Tool calls, timings and outcomes.
Common mistake: Not a transcript of hidden reasoning.
Observability
Ability to understand system behavior from telemetry.
Example: Locate a slow retrieval call.
Common mistake: Logs alone do not establish quality.
Task success
Whether the requested outcome was achieved.
Example: Patch passes acceptance tests.
Common mistake: Fluent answers can still fail.
Trajectory evaluation
Assess the sequence of observable actions.
Example: Check that no unauthorized tool was called.
Common mistake: A valid final result can hide unsafe actions.
Cost and latency
Resources and elapsed time consumed.
Example: Measure tokens, API charges and wall-clock time.
Common mistake: Compare under equivalent conditions.
Regression evaluation
Detect degradation against prior behavior.
Example: Rerun a frozen golden set after a skill change.
Common mistake: Avoid tuning on the holdout.
Failure analysis
Classify failures to identify improvements.
Example: Distinguish retrieval failure from reasoning failure.
Common mistake: Do not blame the model by default.
09 — Decision-making & uncertainty
Uncertainty
↓
Compare evidence value and cost
↓
Choose action
↓
Observe
↓
Reassess
Epistemic action
Action intended to improve knowledge or reduce uncertainty.
Example: Inspect test results before claiming a fix.
Common mistake: Not every action is epistemic.
COMPUTE
Further internal computation or reasoning.
Example: Compare two candidate fixes.
Common mistake: Reasoning cannot create independent evidence.
RETRIEVE
Acquire existing information.
Example: Read API documentation.
Common mistake: Retrieved sources may be stale.
OBSERVE
Measure the current environment.
Example: Inspect actual test output.
Common mistake: Observations can be noisy.
INTERVENE
Change a controlled condition to learn its effect.
Example: Run an isolated experiment with a feature flag.
Common mistake: Requires authorization and safe isolation.
PREFERENCE
Elicit user priorities or constraints.
Example: Ask whether speed or compatibility matters more.
Common mistake: Preferences are not factual evidence.
ACT
Execute an outcome-directed action.
Example: Apply an approved patch.
Common mistake: Separate learning from consequential execution.
Stopping criterion
Decide when further information is not worth its cost or risk.
Example: Stop when acceptance criteria pass and residual risk is acceptable.
Common mistake: Confidence alone is insufficient.
Value of information
Expected decision improvement from acquiring evidence.
Example: Run a cheap test before an expensive deployment.
Common mistake: Estimates are uncertain; this is a research framing.
Quotes & Key Insights
❞Harnesses are deterministic software that harnesses the non-deterministic results produced by models in pursuit of a desired objective.
Handwritten quotation; attribution unverified.❞Specialize the system, not necessarily the model.
Synthesized principle.❞The model provides intelligence. The harness turns intelligence into capability. The eval harness provides evidence of performance.
Synthesized principle.❞Do not assume a model failure until you have investigated the harness.
Synthesized principle.❞Experience is what happened. Knowledge is what we learned. A skill is how we apply what we learned.
Synthesized engineering principle.❞A larger memory does not necessarily make an agent smarter. Better memory selection might.
Synthesized engineering principle.❞An agent can improve its behaviour without changing its model.
Synthesized engineering principle. End-to-end example: repository agent
Explore Context Engineering & Memory in Chapter 10.
Receive issue → load project instructions and relevant skill → inspect repository through scoped tools → propose patch → run sandboxed tests → delegate review if useful → request approval before merge → record trace and evaluate outcome.
Example acceptance criteria: tests pass, no unauthorized writes, requirements met, cost within budget. If evidence is insufficient, report the unresolved issue instead of claiming success.
Back to contents ↑
10 / AGENT MEMORYContext Engineering & Memory
Agent memory helps a system use past information to make better decisions today. Context engineering decides which information the model sees now.
Based on handwritten notes on long-term memory and CoALA; implementation guidance and examples are explanatory additions.
01 — Memory fundamentals
Current taskGoal and constraints
↓
Select memoryRelevant facts and experiences
↓
Working contextInformation available to the model
Agent memory
Information retained and made available to influence later decisions.
Example: A coding agent recalls the repository's deployment requirements.
Common mistake: Memory is not the same as model weights; external memory can change without training.
Context engineering
Selecting and organizing information supplied to the model for a task.
Example: Load the relevant API contract instead of the entire repository.
Common mistake: More context can increase cost and distract the model.
Persistence
Keeping information beyond the current execution or conversation.
Example: Save a verified deployment lesson in a durable store.
Common mistake: A context window alone does not guarantee persistence.
02 — The four types of memory
Working memory
Information actively used during the current task.
Example: Current issue, tool results and task state.
Common mistake: The RAM analogy is useful but not literal; runtime state may also be persisted.
Episodic memory
Records of particular experiences and their context.
Example: Yesterday's deployment failed with a missing API_URL.
Common mistake: A single episode is not a universal rule.
Semantic memory
Facts and general knowledge.
Example: Production requires API_URL, according to the deployment specification.
Common mistake: Facts may expire or be wrong.
Procedural memory
Knowledge of how to perform a task.
Example: Validate environment variables before deployment.
Common mistake: A procedure is not proof that it works in every environment.
03 — CoALA architecture
Agent decision processReason and choose actions
↓
Working memoryCurrent task and state
↓
Long-term memoryEpisodic · semantic · procedural
CoALA
Cognitive Architectures for Language Agents is a framework connecting memory, decision-making and actions.
Example: An agent retrieves a previous failure, updates working memory and chooses to run a test.
Common mistake: CoALA is a conceptual framework, not a required software stack.
Internal and external actions
Internal actions operate on memory or reasoning; external actions interact with the environment.
Example: Retrieve a lesson internally, then inspect a deployment externally.
Common mistake: A remembered observation is not a fresh observation.
04 — Practical memory implementations
Working state
Messages, active plan, tool outputs and structured runtime state.
Example: Store the current test status in a task object.
Common mistake: Do not assume all runtime state fits in the model context.
Episode store
Durable records of tasks, actions, outcomes and evidence.
Example: Save a run ID, error code, timestamp and test result.
Common mistake: Avoid storing secrets or unnecessary personal data.
Knowledge store
Documents, structured records or searchable indexes containing facts.
Example: Retrieve a verified API specification using RAG.
Common mistake: Vector similarity is not factual verification.
Skill store
Reusable instructions, scripts and workflows.
Example: A SKILL.md describes deployment checks and references a validation script.
Common mistake: CLAUDE.md and AGENTS.md can contain both facts and procedures; file format does not define memory type.
05 — Memory lifecycle
CaptureRecord outcome
↓
Validate and storeSource · scope · timestamp
↓
RetrieveSelect relevant information
↓
ReviewCorrect or forget
Capture
Record useful events and outcomes after execution.
Example: Log a failed test and its error code.
Common mistake: Do not indiscriminately retain every invocation or raw reasoning.
Retrieval
Select relevant memories for the current task.
Example: Filter deployment episodes by repository and environment.
Common mistake: Relevance alone does not imply correctness.
Provenance and validation
Track source, time, scope and verification status.
Example: Link a requirement to a versioned configuration file.
Common mistake: A model-generated summary is not independent evidence.
Forgetting and correction
Expire, supersede or delete outdated information.
Example: Replace an old deployment command after a migration.
Common mistake: Do not silently retain contradictory instructions; respect deletion requirements.
06 — Distillation and consolidation
ExperienceDeployment failures
↓
Validated knowledgeRequired environment variables
↓
Candidate procedurePreflight validation
↓
EvaluationCompare against baseline
Distillation
Extract a compact useful lesson from one or more experiences.
Example: Summarize three failures as a candidate missing-variable pattern.
Common mistake: A summary can lose exceptions or invent causal explanations.
Consolidation
Integrate validated lessons into existing knowledge.
Example: Confirm the pattern against the deployment specification and merge it into the knowledge base.
Common mistake: Do not promote an unverified hypothesis to a fact.
Procedure promotion
Turn a supported lesson into a candidate reusable procedure.
Example: Add a preflight environment check, then test it.
Common mistake: Keep version history and rollback; do not automatically grant new permissions.
07 — Progressive disclosure
Progressive disclosure
Load additional instructions and resources only when needed.
Example: Discover a deployment skill by its description, load SKILL.md when selected, then read its references if necessary.
Common mistake: Do not confuse discovery metadata with the full skill.
Context budget
Allocate limited model context to the most useful information.
Example: Keep the current task and relevant evidence; summarize older messages.
Common mistake: Summaries can omit critical details; preserve references to originals.
08 — Self-improving agents
Observe outcomeCollect evidence
↓
Propose changeCandidate skill
↓
Evaluate and approveHoldout and review
↓
Version and monitorRollback if needed
Experience-driven improvement
Change external knowledge or procedures based on validated outcomes.
Example: A repository agent proposes a preflight check after recurring failures.
Common mistake: External memory updates are not model retraining.
Controlled learning loop
Propose, evaluate, approve, version and monitor changes.
Example: Compare the new skill with the previous skill on held-out deployment cases.
Common mistake: Do not let an agent treat its own confidence as proof of improvement.
09 — Memory security and reliability
Memory poisoning
Incorrect or malicious content persists and influences future actions.
Example: A retrieved document tells an agent to bypass approval; quarantine it as untrusted content.
Common mistake: Stored text does not acquire instruction authority merely by being remembered.
Access and retention
Restrict memory by user, project, purpose and retention policy.
Example: Prevent one customer's records from appearing in another customer's context.
Common mistake: Do not store credentials in general-purpose memory.
Conflict and freshness
Resolve inconsistent or outdated memories using authoritative evidence.
Example: Check the current config when an old note conflicts with it.
Common mistake: Recency alone is not authority.
10 — Memory evaluation
Retrieval quality
Measure whether relevant evidence is retrieved.
Example: Recall@5: relevant items retrieved in the top five divided by all relevant items for a query.
Common mistake: Retrieval quality does not guarantee correct answers.
Task performance
Measure whether memory improves actual outcomes.
Example: Compare identical tasks with memory disabled and enabled, using the same model and budget.
Common mistake: Avoid leaking evaluation answers into memory.
Cost and reliability
Track tokens, latency, storage, incorrect recalls and harmful actions.
Example: Compare success rate and cost per successful task across repeated trials.
Common mistake: A larger memory is not automatically a better memory.
Regression and promotion gate
Require evidence before adopting memory or skill changes.
Example: On a frozen holdout, require no critical security failures and a predefined improvement threshold.
Common mistake: Set thresholds before testing; report uncertainty and failures.
Key insights to retain
❞Experience is what happened. Knowledge is what we learned. A skill is how we apply what we learned.
Synthesized engineering principle.❞A larger memory does not necessarily make an agent smarter. Better memory selection might.
Synthesized engineering principle.❞An agent can improve its behaviour without changing its model.
Synthesized engineering principle. Further reading
Cognitive Architectures for Language Agents (CoALA) — original research framework. The diagrams above are simplified teaching adaptations.
Back to contents ↑