Docs · Guide

Building and changing agents

Duct's agent rulebook on LangChain 1.x, LangGraph and deepagents: 37 rules, each naming its primitive and its enforcing test, plus 12 ranked open gaps. Read it before adding an agent or changing a prompt, tool, model default, middleware or pin.

The framework-free half of these rules (architecture, prompting, memory, evals, guardrails, observability) is the agent-engineering skill in the maintainer's agent-skill hub (~/.agents/skills/agent-engineering/, not in this repository), which every project's agent reads. This page stays Duct's: the LangChain and deepagents primitives, the enforcing tests and the open gaps. A lesson any agent product could use goes in the skill's references/lessons.md the day it lands.

At a glance

Rules here are tests, because notes get skipped

A study of 481 public CLAUDE.md files found 4–16% of their prose security rules backed by a real control (arXiv 2608.23550). So where a rule can be a test, it is one, and the Reference names it under "Enforced by"; what cannot be tested yet is ranked under Open gaps.

The rules are Duct's reading of the harness-engineering literature, indexed in agent-harness-references.md; the records behind them are under Sources.

The harness is five files

TermPlain meaning
RungHow much framework an agent uses, from one call up to deepagents
RunnerThe one file that owns an agent: tools, prompts, limits, hooks
BinderWraps a Python function as a tool the model can call
MiddlewareA guard around every model or tool call
Sub-agentA child agent on a bounded side job; keeps the parent's context small
File, in backend/agents/core/Owns
deep_session.pyAssembly (build_deep_session_agent, build_session_agent, one session_middleware list) and the loop (DeepSession: turns, pauses, steers, compaction, failure posture)
lc.pyLangChain adapter: resolve_chat_model, stream_agent, interrupt_pause, prompt_caching_middleware, and Duct's middleware (ReportedRetryMiddleware, SteerMiddleware, SeenImagePruneMiddleware)
turn.pyHow every user turn is built: ContextSpec, BLOCK_ORDER (stable first)
errors.pyOne classifier: a failure is a code before it is a message
*_tools.pyBinders: framework-free domain functions behind thin LangChain wrappers

A runner (agents/<type>/v1/runner.py) owns tools, prompts, limits and hooks; tests/test_harness_boundaries.py keeps frameworks out.

Add an agent in nine steps

Each step ends with its Reference rule group.

  1. Run it through the prioritize skill. Building is free; maintenance is forever.
  2. Pick the rung. The runner docstring says which deepagents features it spends. Shape.
  3. Build it through the shared assembly; anywhere else fails its test. Shape.
  4. Declare run limits and a context spec. The loop; Context and caching.
  5. Name every sub-agent's tools, the general-purpose one included, read-only. Shape.
  6. Wire activity_hooks and record the CONTEXT row for session review (tests/test_tool_activity.py). Evals.
  7. Classify failures through the one error classifier. Tools.
  8. Render and judge it. make dump-prompts, a rubric in backend/tests/eval/rubrics/, a case in backend/tests/eval/cases/. Evals.
  9. Run make check.

Change one thing, then prove it

You changeRule groups, then the eval gate
A promptContext and caching; Evals
A toolTools
A model or tier defaultMaintenance
MiddlewareShape; The loop
A dependency pinMaintenance

Exact names and two pricing gotchas: Reference, "Changing an agent, in full".

Replacing an engine or harness is the change that loses behaviour without a test failing: the new runner is tested against itself, the old one is deleted, and whatever only the old one did is gone. Before the delete, write what the old engine did, per entry path, as tests the new one must pass (what reaches the model, the events the app reads, what a reload shows). The move off the Claude Agent SDK skipped this and lost follow-up pictures, the audit's resumed report and its progress, and the provider search's card.

Open gaps

Ranked by failure prevented or money saved, over effort. Each becomes an issue (prioritize skill) before code, then is struck through here. Numbers are stable: models.py cites gap 3.

#GapChangeEffort
1~~Insights' auto-added general-purpose sub-agent carries every tool, ProposeChanges, RollbackChangeSet and RememberFact included~~done 2026-10-25: agents/insights/subagents/general_purpose.py supplies a read-only one on the verifier's model; test_agent_assembly.py holds every deep runner's sub-agent lists writer-free. Retry and limits for sub-agents remain gap 5S
2~~SDK retries stack under ReportedRetryMiddleware, invisible to the UI and the quota cooldown~~done 2026-10-25: max_retries=0 (Gemini 1) in resolve_chat_model, a test per provider. A per-request timeout is still open: the SDK defaults are ten minutes and a thinking call can legitimately run long, so it needs a measurement firstS
3~~Deep-rung summarisation fires at ~850k on the current Claude models~~done 2026-10-25: resolve_chat_model writes context_window_for(model) into the model profile's max_input_tokens, so every fraction deepagents derives is a fraction of Duct's budget; tests/test_summarisation_trigger.py holds it across the catalogue. Still open: a 128k-window model's trigger (109k) sits under the insights prune trigger (120k), as it did before — pruning per window is its own changeS–M
4~~Fallback fires on auth, bad-request and overflow errors~~done 2026-10-25: ClassifiedFallbackMiddleware falls back only on a failure is_retryable classes as transientS
5~~Sub-agents run without retry or limits; a sub-agent exception ends the parent turn~~done 2026-10-25: subagent_middleware(limits) on every spec of both runners (run limits, the reporting retry, the tool-error middleware), ToolErrorMiddleware in session_middleware; test_agent_assembly.py and test_deep_session.py hold bothS–M
6deepagents can append to Duct's system prompt per modelhalf done 2026-10-25: tests/test_system_prompt_ownership.py fails a bump that suffixes a catalogue model unannounced (no catalogue model is suffixed since Haiku 5.5 replaced Haiku 4.5, the one that was). Still open: render the suffix in make dump-promptsS
7Tool definitions are unreviewed promptRender tools in make dump-prompts; widen prompts.yml pathsS–M
8Execution policy hardening: auto-apply allowlist, agent-initiated rollback, drift check on rollbackG1 and G2 of the execution approvals recordS
9Execution policy hardening, part twoTracked with the maintainer, not hereM
10~~The memory digest says "present" for any open state, however old~~Done 2026-09-28: seen · Nd · verify, re-read before asserting, refresh on re-rememberS
11~~No gate runs a harness change against real models~~Done 2026-09-28: tier 0 offline, tier 1 in shadow (agent-eval.yml)M
12No dollar ceiling per runA cost guard on RunLimitsM

Runners-up:

Remember: a rule with no test is a note. A gap closes with its test.

Reference

The full rule tables, grouped as the harness-engineering list groups them. "Primitive" is the LangChain, LangGraph or deepagents piece that implements the rule. "Enforced by" is the test, check or review that holds it; test paths are relative to backend/.

Shape

RulePrimitiveEnforced by
Lowest rung that works: one structured call, then a fixed workflow, then create_agent, then deepagents only for what it adds (sub-agents, scratch filesystem, planning). Say in the runner docstring which of those the agent spends, and re-justify when one is switched off.init_chat_model, create_agent (1.x, semver-stable), create_deep_agent (0.x, pinned exactly)review; each runner's docstring; backend/AGENTS.md, "Agent ports"
Build every session graph in one place. The rung is chosen; the middleware is not.build_session_agent / build_deep_session_agenttests/test_agent_assembly.py (a graph built elsewhere fails; the audit ran a bare create_agent from 2026-08-16 to 09-27 with its RunLimits unenforced and no prompt caching, all tests green)
A sub-agent exists to isolate context for a bounded side job. Name its tools; never let deepagents default them. The auto-added general-purpose sub-agent gets every parent tool unless one by that name is supplied.SubAgent dicts with explicit toolstest_agent_assembly.py::test_no_sub_agent_of_either_runner_carries_a_writer; content: test_sub_agents_never_get_the_writer_tools

Tools

RulePrimitiveEnforced by
Few, workflow-level tools with meaningful ids. Insights reaches every connector entity through one FetchData(entity_id), and every tool on a connected MCP server through ListConnectedTools / CallConnectedTool, never one definition per server tool.StructuredTool + Pydantic args_schemareview; tests/test_mcp_tools.py (mounted only when a server is connected)
Bound every result, and never cut mid-structure: fold losslessly first.agents/core/compaction.py (called by the insights data binder and the MCP binder); FilesystemMiddleware eviction on the deep rungtests/test_insights_data.py (compaction keeps every number a brief could quote); tests/test_mcp_tools.py (an oversized result is capped at MAX_RESULT_CHARS)
An error is a result that says what to do next, with a code. Never str(exc) to a client.classify_error; ToolErrorMiddleware with tool_error_message (a raise becomes an error result the model reads on)tests/test_agent_errors.py; test_deep_session.py
Tool definitions are prompt: they head the cached prefix, so review them like prompt and keep their order deterministic.nonegap 7 (make dump-prompts renders no tools yet)
Anything a tool returns from outside Duct (a search query, a page, an ad) is data, never instructions. Label it in the prompt.noneeach agent's system prompt (insights: BOUNDARIES)
Arithmetic over rows is Duct's, not the model's. A row report carries totals, rates (ratios of totals, or weighted means, never a mean of rates) and per-dimension subtotals, computed from the catalog's agg, ratio and weight, and says what they cover.agents/insights/totals.py, called by fetch_entitytests/test_insights_totals.py; tests/test_insights_catalog_contract.py; the eval gate's must_quote check

Context and caching

RulePrimitiveEnforced by
Per-user and per-project text goes in the USER turn, never the system prompt. Stable blocks first.ContextSpec, BLOCK_ORDERtests/test_turn.py
Every graph asks for caching. Anthropic caches only a request that says so; Gemini caches implicitly; OpenAI routes by prompt_cache_key.AnthropicPromptCachingMiddleware (appended by create_deep_agent, by build_session_agent, and by prompt_caching_middleware() for a one-shot pass); resolve_chat_model(cache_key=thread)tests/test_agent_assembly.py; cache share on TOKEN_USAGE
Duct owns the final system prompt byte for byte. deepagents harness profiles append text per model: 0.7.15 shipped coding-agent guidance ("Never speculate about code you have not opened…") for Haiku 4.5, Sonnet 4.6 and Opus 4.7, plus profiles for OpenAI Codex models; the 0.7.23 pin still does and adds an NVIDIA Nemotron profile. Packages can register more.register_harness_profilegap 6
Prune before you summarise, and batch the pruning so each cache break buys something.ContextEditingMiddleware + ClearToolUsesEdit(clear_at_least=…)RunLimits.__post_init__ (prune trigger below the summarisation floor); tests/test_deep_session.py; tests/test_insights_middleware.py
Set the summarisation trigger from CONTEXT_WINDOW, not the library's model profile (0.85 × the profile's max_input_tokens is ~850k on Opus 5.5 and Sonnet 5.5, where Duct budgets 200k)._within_ducts_window in resolve_chat_model writes the budget into the profile deepagents readstests/test_summarisation_trigger.py
One emergency compaction and one retry on a real overflow; a second overflow is the ordinary failure.compact_thread (agents/core/lc.py), called from DeepSessiontests/test_insights_session.py (compacted once and retried; a second overflow is the ordinary failure)

The loop

RulePrimitiveEnforced by
Every agent declares RunLimits: model and tool calls per run and per thread. Recursion is derived, never picked.ModelCallLimitMiddleware, ToolCallLimitMiddlewareRunLimits.__post_init__, tests/test_deep_session.py
Retry in exactly one layer, the one that reports each attempt and honours Retry-After. Provider SDKs retry underneath by default (Gemini up to 6 times), invisibly.ReportedRetryMiddleware; SDK max_retries=0gap 2
A retry says how long, and the provider's Retry-After wins. MODEL_RETRYING carries retry_in, a duration the client anchors to its own clock; a provider asking longer than MODEL_RETRY_HEADER_MAX_DELAY is not retried, because the coded failure now beats a countdown that fails anyway. Summariser calls are billed scope: compaction: they count toward the total and never drive the gauge.retry_delay (lc.py), retry_after_seconds (errors.py)tests/test_insights_session.py; tests/test_stream_translation.py
Fall back only on transient failures. ModelFallbackMiddleware falls back on every exception, auth and overflow included.ClassifiedFallbackMiddleware in deep_session.pytests/test_deep_session.py (rejected key stays rejected; a 429 falls back)
Input typed mid-turn is steered or queued, never refused (no 409 for a busy session). The route decides; the runner reports user_input_consumed when it dequeues, so the client drops the "queued" mark.SteerMiddleware + the session's steer_queue, else chat_queuetests/test_insights_session.py; tests/test_stream_translation.py
What the person sent is what the model receives, on every way in: the idle follow-up, a message steered mid-turn, one that missed the turn's last call, the first message of a resumed thread. A turn takes the content blocks, never a text projection; a new entry path gets a row. From 2026-09-05 to 11-27 an idle follow-up lost its pictures and every suite was green.chat_message_content, _turn_input, steer_messagestests/test_model_input_contract.py (posts through the real route into a real loop and reads what the fake model was sent)
A tool the provider runs inside its own call (Anthropic's web_search) is reported through the same hooks as Duct's, so its card, its transcript row and a session audit look the same on every provider._server_tool_traffic in _dispatch_updatestests/test_stream_translation.py::test_a_provider_side_web_search_is_reported_like_ours
A pause is a checkpointed interrupt() and survives a redeploy. Work before the interrupt is idempotent, because the node reruns on resume.langgraph.types.interrupt, Command(resume=…)tests/test_deepagents_harness.py
A writer survives the replay a cut run makes. A run continued from its checkpoint executes the in-flight tool call again, with the same call id; change sets and artifacts are keyed on it (one row per conversation and call, held by a partial unique index) and memories dedupe by content hash, so the second execution reads what the first wrote.ToolCallBinder (deep_session.py), agents/core/tool_calls.py, change_set_for_tool_call, artifact_for_tool_calltests/test_writer_idempotency.py; tests/test_deep_session.py (the loop names the call to the tool)
A thread is keyed on the conversation, never the session.checkpointer thread_idbackend/AGENTS.md
Run status comes from the stream, in the recorder. A dead process's running rows are cancelled at the next boot.ConversationRecorder, cancel_orphaned_runstests/test_conversation_run_status.py

Memory

RulePrimitiveEnforced by
One write path (remember()), one read path (search()), recalled into the USER turn. No MemoryMiddleware, no LangGraph Store.service/memory.pytests/test_memory*.py
A remembered state of an outside system (a campaign's status, a budget, a redirect) is a claim with a date, not a fact. Show its age and re-read it before asserting it.volatility() / freshness() in service/memory.py; the seen · Nd · verify digest line; MEMORY_DISCIPLINEthe freshness axis of tests/test_memory_retrieval.py (stale-assertion and false-alarm rates held at 0)

Humans and authority

RulePrimitiveEnforced by
Authority lives in code, never the prompt. No agent-facing approve or apply tool, in either harness.service/execution/policy.pytests/test_execution_policy.py
Nothing that moves money, goes live, or cannot be fully undone applies without a click on that set.the auto-apply allowlist (AUTO_APPLY_ALLOWLIST)tests/test_execution_policy.py; the allowlist is under review (gap 8)
The agent acts with the user's delegated credentials, scoped to the project at build time. Non-members get 404.binders take a membership-checked project_idtests/test_route_auth_boundaries.py
Only an explicit Stop cancels a run. A page that leaves mid-turn detaches: the run finishes and is written down, the grace close and the pruner wait for the turn, and a returning tab reattaches from the segment after the rows it hydrated._close_after_grace, _stale_session_ids, after_segment on the stream (routes/agents.py); the recorder's segment stamp; hooks/useAgentSession.jstests/test_runs_survive_navigation.py; lib/__tests__/liveRuns.test.js, agentHistory.test.js

Evals and observability

RulePrimitiveEnforced by
Offline tests drive the real harness with a canned model and assert events, tool names and payloads, never prompt prose.ToolCallingFake, emittedmake test
What is sent to the model is tested too: byte-stable prefix across calls, history and reasoning kept, effort passed. The Claude Code regressions of April 2026 were exactly these.RecordingFake (tests/fakes.py); the "Model defaults" section of make dump-promptstests/test_request_invariants.py (both rungs and the insights runner); prompts.yml fails a default changed without the dump
A prompt, model default, effort or harness change is judged k times against a baseline, on synthetic accounts, before it merges. Binary markers gate; 1–5 scores are logged.tests/eval/gate.py, tests/eval/cases/, make agent-eval (DeepSeek V4 Flash on OpenRouter, GLM 5.3 Flash judging)agent-eval.yml on harness PRs (it runs on every push to a ready PR, so open agent PRs as drafts while iterating), in shadow until an A/A window; tests/test_eval_gate.py holds the gate's own logic. One provider today; the per-provider matrix is tier 2
One span per model call and one per tool call, at one choke point.ReportedRetryMiddleware (model); awrap_tool_call middleware (tool)five binders span their own tools today (gap, runner-up)

Maintenance

RuleEnforced by
Bump the LangChain stack by hand and alone; Dependabot proposes no version of it (.github/dependabot.yml), only security fixes. poetry install --with dev locally the same day, or local tests run other versions than CI.tests/test_deepagents_harness.py, tests/test_agent_assembly.py
A model has a price or it has no cost. PRICING mirrors CONTEXT_WINDOW, cost_usd() takes cached tokens out of the input figure, and an unpriced model reports cost_usd: None, never a guess: on BYO keys the figure is what the user pays.tests/test_stream_translation.py
A model that leaves the catalogue leaves a row behind. RETIRED_MODELS maps a replaced id to its successor, never a step up in price, and keeps the old model's own price and window, so a thread it served still reads what it cost; resolve_engine_model would otherwise send an unknown id to the provider default (a Heavy pick of Opus 5 would have run on Sonnet without a word). An OpenRouter slug whose only successor costs more gets none and keeps running as picked.tests/test_model_transport.py; tests/test_stream_translation.py
A model's request contract is data, not a check at a call site. CLAUDE_BOUND_THINKING: a forced tool_choice is a 400, so a typed answer after a tool loop goes through agents/core/research.research_answer, never a bare ToolStrategy; a thinking block replayed after an earlier turn changed is a 400 for newer accounts, so resolve_chat_model asks the API to drop it. takes_temperature drops the temperature the Claude 5 family and GPT-6 refuse while they reason. Classify a new model in both tables when it joins.tests/test_research_answer.py; review
A new model is a table migration: PRICING, CONTEXT_WINDOW, MODEL_FALLBACK, tiers, thinking, and a check of the LangChain profile and deepagents harness profiles for that id.tests/test_stream_translation.py (PRICING and CONTEXT_WINDOW cover the same ids)
Every harness component names the failure it compensates for, and is re-measured when the model changes. planning=False on insights is the worked example: two of five turns were checklist rewrites.STYLE.md (comments carry reasoning)

Middleware: what we mount and why

MiddlewareMountedVerdict
ContextEditingMiddleware + ClearToolUsesEditsession_middlewarekeep; clear_at_least is RunLimits.tool_results_clear_at_least, a quarter of the trigger, since 2026-10-25 — without it every call past the trigger cleared one more result and broke the cached prefix there
ModelCallLimitMiddleware, ToolCallLimitMiddlewaresession_middlewarekeep; per-tool caps are RunLimits.per_tool_run_limits (content caps generate_video at 3 a turn), still to add for ProposeChanges and task
ModelFallbackMiddlewaresession_middleware, as ClassifiedFallbackMiddlewarekeep; classified since 2026-10-25
ReportedRetryMiddleware (ours)session_middlewarekeep: ModelRetryMiddleware has no per-attempt hook and ignores Retry-After
SteerMiddleware, SeenImagePruneMiddleware (ours)session_middlewarekeep; no prebuilt equivalent
AnthropicPromptCachingMiddlewareevery graphkeep; measure a 1h TTL for idle chats
TodoListMiddlewarecontent onlykeep as measured
FilesystemMiddlewaredeep rung, no executekeep; never the shell
SubAgentMiddlewaredeep rungkeep; always supply general-purpose yourself
SummarizationMiddleware (deepagents)deep rungkeep; its trigger comes from CONTEXT_WINDOW since 2026-10-25 (gap 3)
PatchToolCallsMiddlewaredeep rungkeep
ToolErrorMiddlewaresession_middleware and every sub-agentkeep; mounted 2026-10-25
HumanInTheLoopMiddlewarenot mountedskip: change-set cards and policy.py do this
PIIMiddlewarenot mountedskip; remember() redacts. Revisit for traces
LLMToolSelectorMiddleware, ProviderToolSearchMiddlewarenot mountedskip: changing tools per call breaks the cache; tool tokens are small
ModelRetryMiddleware, ToolRetryMiddleware, LLMToolEmulatornot mountedskip: ours reports; service/rest.py retries; fakes exist
ShellToolMiddleware, FilesystemFileSearchMiddleware, Claude-native tool middlewarenevernever on a server; a capability the model may lack is a Duct tool

Changing an agent, in full

ChangeDo
Promptmake dump-prompts and read the diff as prose (prompts.yml). Nothing volatile above the stable blocks. Replay the bundles that motivated it (make session-replay) on two providers, and run make agent-eval (agent-eval.yml runs it on the PR): FAIL does not merge; INCONCLUSIVE needs a line in the PR saying why it is acceptable
ToolBound its output; errors carry a code and a next step; decide its activity card; keep writers off every sub-agent list; batch tool changes, since each one invalidates the cache
Model or tier defaultUpdate PRICING, CONTEXT_WINDOW, MODEL_FALLBACK and the tier map together, and add a RETIRED_MODELS row for any id the new one replaces. Classify it in CLAUDE_BOUND_THINKING and takes_temperature. Check the LangChain profile exists for that id, not just its window (langchain-anthropic 1.7.4 had none for claude-sonnet-5-5, which meant max_tokens=4096 with thinking inside it), and any deepagents harness profile. Run the live web-search matrix. For an OpenRouter slug, price it at the model vendor's own endpoint (/api/v1/models/<slug>/endpoints), not the one price /api/v1/models shows, and read the vendor's changelog: a slug pins a build the vendor may already have retired
MiddlewareChange session_middleware, nowhere else. Re-measure SUPERSTEPS_PER_MODEL_CALL (tests/test_deep_session.py). Comment the failure it prevents
Dependency bumpAlone; poetry install --with dev; tests/test_deepagents_harness.py and tests/test_agent_assembly.py; diff create_deep_agent's stack order and deepagents/profiles/ against the previous version

Sources

The index of everything read is agent-harness-references.md.