ADR 0002: agda-mcp¶
File: agda-native-air/docs/adr/0002-agda-mcp.md
- Status: Accepted. Every decision below is landed on
main; follow-ups each one requires are named in its section and tracked in Milestone 5. - Date: 2026-09-07 (the day the #68 hardening wave was closed as complete; the field record runs 2026-08-21 through 2026-09-04).
- Tracking: #148 (this record); #68 (the wave, closed) and its children #69–#79; the fixes that followed from it, #100, #101, #103, #106, #108, #114, #115; Milestone 5 (#134–#139, #145–#147) for what is open; #205, the
autotool (decision 25); #242, the launcher's anchor (decision 26); #249, the launcher's fast path (decision 27); #248, the display mode ofget_goalandtype_of(decision 28); #347, a lane restarted when its Agda changes (decision 29); #136,fill_hole's apply and patch (decision 30). - Ancestry: #10 (M1-2, the four-tool server, PR #38); #11 (M1-3, the corpus tools, PR #44); #66 (in-place checking, PR #67); and [
feedback/flrp-agda-mcp-improvements.md] (imported by PR #80), the field report whose § 7 verification addendum is where most of the decisions below were earned.
Executive summary¶
agda-mcp is a small Haskell server that speaks the Model Context Protocol over stdio and gives a coding agent thirteen tools over the pinned agda, a fourteenth on request, and a fifteenth, auto, when started with --auto.
- Proof-state tools:
check_file,get_diagnostics,get_goal,fill_hole. - Whole-project gate:
check_project. - Live queries:
type_of,normalize,resolve_name,definition_of,exports_of; and, registered only with--auto(#205),auto, Agda's own proof search at a hole, which answers a candidate term. - Corpus tools:
search_by_name,search_by_type,get_dependencies, when started with--corpus;search_by_name'sinScopeAtkeeps the names a file can write (#203), and the scope-awaresearch_in_scopeof #17 phase 1 behind it is presented when--exposenames it.
This document is the design record: what was decided, the evidence that earned each decision, and what each one still owes. The deep notes it distills stay where they are, under docs/agda-mcp/, and every decision links to its own note.
The design in five minutes.
The server runs Agda in two lanes and lets only one of them judge.
- The batch lane spawns a real batch process once per call,
agdaon the file for the per-file tools and the project's own gate forcheck_project, and derives every verdict from that process's exit code, never from its prose (§ 3 records the one departure, which can turn a green gate red and never the reverse).
The verdict travels with the following:
- the command to which it is equivalent,
- the resolved binary and working directory, and
- the project to which the file resolved,
so a client can check the claim instead of trusting it.
-
The interaction lane keeps one persistent
agda --interaction-jsonchild per project root and answers questions about a loaded file in milliseconds, such as the following: -
what is this expression's type,
- what does this name resolve to and why,
- what does this module export,
- what does this hole want.
Those answers inform and never decide, because interaction-mode Agda is tolerant by design: it loads a file with open holes where batch Agda exits 42.
Underneath both lanes sits one rule: when Agda can answer a question, ask Agda; anything the server derives from source text is a pre-flight approximation and a fallback, never the authority.
Why it is shaped this way comes down to one field datum and one measurement.
The datum. In July 2026 a Claude Code session formalized about 1200 lines of literate Agda in ualib/agda-algebras with the server configured and its four tools listed, and never called it once, because nothing said whether green meant the build passed, and the two tools with no shell equivalent were unreliable on the literate files that repository is made of.
The measurement. A batch judgment costs about 2.6 s of interface loading on a standard-library fixture, while a question about a file the lane has loaded costs 1–3 ms. So verdicts are made expensive and unimpeachable, knowledge is made cheap and explicitly non-authoritative, and the proof-state and live-query tools say, in every response and in their descriptions, which of the two they are. The three corpus lookups ride neither lane and run no Agda at all; search_in_scope reads the same index and validates every result through the interaction lane (§ 10).
Where it stands¶
The #68 wave closed as complete on 2026-09-07: its eleven children (#69–#79) and the fixes that followed from them (#100, #101, #103, #106, #108, #114, #115) are all merged.
Nine field sessions between 2026-08-21 and 2026-09-04, in agda-algebras and in formal-ledger-specifications, record the server as the primary development instrument, with warm check_file rounds of 2–35 s against 20 s to 10 min for the shell equivalents, and with the project echo cited in nearly every report as the affordance that made a cross-worktree verdict trustworthy (§ 12 below).
Where it goes¶
Milestone 5 collects the ergonomics the field record asked for (§ 13), as follows:
- a profiling tool,
- many-files-one-call forms,
- registry hygiene across worktrees,
- a reason beside
checkedFromSource, - queries inside a parameterized module's scope,
- two payload fixes.
The opt-in apply for fill_hole that this list held has landed, as an apply and a patch (#136; § 7, decision 30).
Corpus-backed retrieval as server tools is issue #17 (M2-3), whose design map is a forward pointer from this record, not part of it.
1. Context: the field test that shaped the server¶
The server's first shape (M1-2, PR #38) was four tools, each spawning a batch agda over a transient copy of the file, with get_goal reading a goal through the AgdaDojang.Debug reporting macro. Issue #66 (PR #67) moved checking in place, at the file's real path with the bytes restored afterwards, because a scratch copy of a hierarchically-named module fails with ModuleDefinedInOtherFile. M1-3 (PR #44) added the three corpus tools. That was the server the field session met.
The session (ualib/agda-algebras Issue #459, PR #507) wrote its own post-mortem, which is [feedback/flrp-agda-mcp-improvements.md]. Its § 2 reconstructs the decision an agent makes at each check: a verdict it cannot trust costs more than no verdict; its edit unit is a whole module; every module is .lagda.md; its questions were about scope, not goals; and it could not tell what the server was doing. Its § 0 asked that every claim be re-verified before an issue was filed, and the § 7 addendum (2026-07-29; scripted MCP sessions against 911ae18, cross-checked with direct agda runs) did so, with the following result:
-
Confirmed (and even worse than reported).
-
fill_holeansweredokfor a candidate that left an unsolved implicit, whereagdaon identical content exits 42 (#69); get_goalreported the reporting macro's own unsolved type,(x₁ : _3 x) → _5 x x₁, where the fixture documentsA(#70, a long-standing defect that an April transcript had rationalized as "mutual dependency between holes");-
hole detection matched only the literal token
{!!}, missing{! !},{! e !}, and?in every flavour while counting, and filling, tokens in comments and prose (#71, #73). -
Refuted.
check_filewas never green on unsolved metas: the server was batch-strict from the start, because it runsagda <file>per call. What was missing was saying so, which became #72. -
Found while re-testing. No diagnostic carried a position, because the parser expected Agda's old
file:10,5-15format and 2.8.0 emitsfile:9.12-13(#74);--timeoutwas parsed and never enforced (#77).
The wave's plan kept the document's own priorities, as follows:
- P0 is trust (#69, #70, #71, #73, #72),
- P1 is reach beyond the shell (#74, #75, #76, #77),
- P2 is economics and ergonomics (#78, #79).
Its acceptance metric was blunt, that the next real literate-repository session reaches for the server instead of the shell.
Three later issues came from the wave's own measurements rather than from the report, as follows:
- #101 from the #83 field test (the one agent that reached for the server on its own sent a relative path, got a bare
-32603, wrote "the MCP agda server crashed", and never called it again), - #100 from a literate fixture whose prose named the module,
- #106 from reviewing #100's fix, which spawned #114 and #115 by probe.
Issue #103 made a second consumer project (fls) a client with its own toolchain, and #108 moved get_goal onto the lane once #75 had built it.
2. The two-lane architecture¶
(See also #75, #108, #248, #347, and [agda-mcp/agda-mcp-interaction-lane.md].)
Decision. Verdicts come from a batch process spawned per call, agda for the per-file tools and the project's own gate for check_project; knowledge comes from a persistent agda --interaction-json child per resolved project root; and the boundary is policy, held by the tool descriptions, the server's instructions, and reviews, not a convention.
-
Batch lane (verdicts): the per-file tools
check_file,get_diagnostics, andfill_hole, plusget_goal's fallback path, each spawn the realagdaat the file's real path, patch in place when they must (fill_hole's candidate, the reporting macro), and restore the bytes on every path, timeout included, unless the call asked for an accepted candidate to stay or another writer changed the file meanwhile (§ 7, #136).check_projectruns the project's own gate instead (amaketarget, an operator-configured command, oragdaon theEverythingmodule; § 3), as a bounded subprocess under the same kill ladder, and never patches a file. The cost is a cold process per call, deliberately: a verdict is always a real batch run's own exit code, Agda's for the per-file tools and the gate's forcheck_project. -
Interaction lane (knowledge):
type_of,normalize,resolve_name,definition_of,exports_of, and since #108get_goal's primary path (Cmd_goal_type_contextreturns Agda's own goal display as data, with no file mutation; the response sayssource: "interaction-lane", and the injected-macro path remains assource: "injected-macro"for a lane that cannot serve the file, and as the one path that reports binder visibility). Interaction mode loads a file with open holes and succeeds, which is exactly why it may never decide a verdict; the server says this out loud, since #191 once for every lane tool in its instructions. -
The lane prints types as an editor does (#248). Agda's goal and inference commands name a display mode (Agda's
Rewrite), which decides how the types in an answer are printed:AsIsas stored,Simplifiedafter simplification, which keeps a defined name such asGroup α ρ, andNormalisedin full normal form, which unfolds every definition (InstantiatedandHeadNormallie between). The lane sentNormalisedfrom its first probe, onNatfixtures where every mode prints the same thing.get_goalandtype_ofnow takerewrite, the mode by Agda's own name (any other word is refused before Agda is asked), defaulting toSimplified, which is what an editor'sC-c C-,andC-c C-dsend; every answer says which mode printed it, andget_goal's fallback saysNormalised, since its macro normalizes whatever was asked.search_in_scope(withsearch_by_name'sinScopeAt) andresolve_name's recovery still sendNormalised, and the proof-search loop asks for it by name: the first derives its query from the goal's display and compares printed types, the second reads only an error, and the loop's binder counts, peek, and scorer were built and measured on that printer. -
Agda's own proof search is a lane tool whose answer is a candidate (#205).
autosendsCmd_autoOne, which under Agda 2.8 runs Mimer (Agsy's replacement since 2.7), and answers the term found, joined onto one line, or the search's own message or Agda's refusal, in band. It is the one lane tool that changes the lane's state: a found term is given into it with force, skipping the termination check, so the server re-loads the file before answering, the reset a give owes (#163), and the term is a candidate forfill_holeand never a verdict. It is registered only with--auto(decision 25), and like every hole tool it follows the one-hole rule and names the hole it searched inaddressed(decision 21). -
A lane answers only from the Agda the server would start (#347). A lane keeps its child for up to fifteen idle minutes,
reload: trueor not, while the batch lane starts a new Agda per call; so when the Agda that--agda-binnames changes under a session, the two lanes would answer from two environments. Each lane therefore keeps a stamp of the Agda a spawn would start, taken before its child is spawned, and a request takes a fresh stamp under the slot's lock before it reuses the lane; on a difference it stops the lane as the reaper does and spawns another, and the answer'slane.loadisrestarted(a verbose answer addslane.agdaStamp). The stamp has three parts, one for each way a registration's Agda changes, as follows: -
the real path
--agda-binresolves to, every symlink followed, which moves when a pin (a gc-root symlink to one build) is rebuilt; - a fingerprint of the file's bytes when it is 64 KiB or less (a wrapper script), else its size and modification time (a binary), which moves when a dev shell rewrites its per-checkout wrapper to name another store path, and not when it rewrites the same bytes;
- the output of an optional
--agda-identity-command, for a launcher whose own path and bytes never change:scripts/agda-for-flake.sh --print-keyprints the key under which the launcher would build, which moves with the checkout's lock.
The identity command's output stands for --agda-identity-ttl seconds (default 2) after it runs, and a spawn always runs it afresh, so a lane's stamp is never older than its request. A failing command is part of the stamp, named by how it failed. The batch tools take no stamp; their peek takes one only once the stored load would otherwise vouch for the file, and declines a lane whose stamp differs.
-
A peek is not a call. The batch tools may read a warm lane's stored load to enrich a response, filling hole listings'
goalfields (#108) and unsolved metas' names and types (#115), and only when the lane's recorded load matches the file's current bytes; a cold or stale lane leaves the response byte-identical, and no batch tool ever spawns, loads, or waits on a lane. -
The lexical layer is demoted, not deleted.
AgdaMCP.Holesstays the splicing engine (a pre-Agda source edit needs a source view) and the fallback for files Agda refuses to load; it is never again the authority for anything Agda can answer, and parity tests hold it to the lane'sInteractionPointsacross the fixture matrix. -
scope_atwas omitted rather than approximated: no interaction command enumerates the names in scope, and the bar (§ 2.2 of the field report) is to ship a tool only if it helps the server beat the shell. The finding is recorded on #75. -
The corpus lookups ride neither lane; they are pure lookups on an in-memory index (§ 10).
search_in_scope(#17, phase 1) is the one corpus tool that also takes the interaction lane, and only as knowledge: it types each candidate rendering in the queried file's scope and returns nothing the lane refused.
Evidence. The lane note was written from live probes of the protocol under the pinned Agda 2.8.0 before the Haskell existed, and the implementation cites it. The economics, measured disk-warm: a batch call costs 2.78 s and 2.60 s on the repeat, paid per call; the lane's process start plus Cmd_load costs 2.59 s once, and five knowledge queries after it added less than measurement noise (2.580 s for the load plus five, against 2.589 s for the load alone). Switching between two files under one root pays the switched-to file's load, tens of milliseconds warm. The #83 shell baseline was a 10.0 s median per check. Three protocol facts are load-bearing and were each probed: commands execute strictly in order, so a Cmd_show_version sentinel after every command frames responses without heuristics or timeouts; a per-load argv must carry the resolved project flags, because Cmd_load with an empty list inherits no useful context; and a hole-free file's completed top-level scope loses file-local opens, so resolve_name prefers a goal-scoped query whenever the file has an interaction point.
Evidence for the display mode. The #243 session through Copilot CLI (GPT-6.1 Sol) called get_goal once, on the hole of its first draft of a one-step subgroup test in agda-algebras, and its report said the context "expanded the carrier and operations into lengthy interpretation terms"; the playground session of 2026-10-04 had asked for a rewrite argument defaulting to Simplified, because it needed what agda-mode shows and the server printed something else ([mcp-field-reports.md]). Measured on that hole through the agda-algebras registration's arguments (its Agda 2.8.0 wrapper), a context's size being the sum of its printed types, the results are as follows:
get_goal. By default the context is 168 characters, with𝑮 : Group α ρ,ε∈B : ε ∈ B, anddiff-closed106 characters; withrewrite: "Normalised"it is 1,326, with𝑮528,ε∈B145, anddiff-closed416, which is what the server before this change answered to every call. The goal,IsSubgroup 𝑮 B, is a record type and prints the same in both.type_ofat that hole.𝑮prints in 9 characters against 528,ε∈Bin 5 against 145, andmkIsSubgroupin 432 against 1,585.search_in_scope, built once in each mode. At that hole: the same derived query (IsSubgroup), the same six rows in the same order, and printed types of 1,664 characters against 6,458. On the suite's own fixture, whose goaltwice n ≡ n + nunfolds,Simplifiedchanged the derived query (tokenstwice ≡ +for+ ≡) and the lane-form statement exclusion stopped firing: two tier-3b failures. The archive holds onesearch_in_scopecall and noinScopeAtcall, so there is nothing to replay, and the tool stays in the mode it was measured in.- What the default costs. A lemma stated through an alias prints as the alias:
Data.Nat.Properties.+-commasAlgebra.Definitions.Commutative _≡_ _+_, against(x y : ℕ) → x + y ≡ y + xinNormalised, so a reader who needs the arity asks forNormalised. That is what an editor shows, and it is why the proof-search loop, whose binder counts read the expanded form, asks forNormalisedby name: its budget-1 regression run over the 41 agda-algebras rows, configured as the publishedctx-probe-1, is identical field for field on the server before and after this change, and its live specs pass against the new one. - The tests. A fixture with a module parameter of a defined type (
p : Pair Nat, beside a record parameter as the control) keeps the name by default and unfolds underrewrite: "Normalised"; the suite fails on the old default (five tests) and on a server that ignores the argument in either tool (one test each). The descriptions read 1,813 (get_goal) and 439 (type_of) of the 2,048 characters a client reads, andtools/listgrows from 24,597 to 25,289 characters.
Evidence for the restart (#347). The gap was found by Copilot's review of PR #344 (#342, the launcher keyed by the lock), whose guide could only tell the reader to restart the server after moving a lock. The measurements behind the stamp's shape (2026-11-08), as follows:
- Bytes, not metadata. Three
nix developentries in a row in an agda-algebras checkout rewrote its.agda/bin/agdawith one sha256 and three modification times (the shell writes it withcat >), so a stamp of size and mtime would restart every lane at every shell entry. - What a stamp costs. The path and contents parts cost 18 to 45 µs per call (2,000 stamps each of three wrappers, the largest the 12 KiB launcher); the launcher's
--print-keycosts 15.3 ms (median of 30 on formal-ledger-specifications, 14.1 to 36.1), which is why its output is cached. An agent's calls arrive a model turn apart, so for an agent nearly every lane call runs it, and a lock moved between two calls is always seen; a scripted client that calls many times a second pays once per two seconds. - The tests. Seventeen new tests: tier 1m, without Agda, on the stamp and the identity cache, and tier 3d through stand-in
--agda-bins that exec the real Agda (a symlink re-pointed restarts the lane; the same bytes with a new mtime reuse it and new bytes restart it; an identity command whose output changes restarts it; a respawned lane carries the current key, not the cached one; a stale lane is not peeked). Each of seven mutations of the server (no comparison, no fingerprint, a peek that ignores the stamp, no symlink resolution, no cache, norestartedecho, a spawn that trusts the cache) fails one to four of them, and the launcher with--print-keyfalling through to a build fails four of its five new tests. Copilot's review of PR #349 added three, each failing before its fix: a FIFO held open by a writer is stamped without being read (the stamp now reads regular files only; the read had blocked under the slot's lock), and a thread killed mid-run unwinds out ofrunCommand, through the identity cache too, instead of coming back as a failed run (runCommand, which the batch tools share, now rethrows asynchronous exceptions; a cancelled identity run had been cached as a failure stamp). - End to end. One server session through
scripts/run-server.shand the launcher, registered as [agda-mcp/registering-a-project.md] says, in a scratch worktree of formal-ledger-specifications atmaster, askedtype_of Set(verbose) ofsrc/Ledger/Prelude.lagda.mdfour times. The first call spawned the lane and loaded the module cold in 35.6 s, under keyfd3559bd…; the second, nothing moved, reused it in 21 ms, a--print-keyrun included. The worktree'sflake.lockwas then replaced by an older one whose environment the store held, and after three seconds the third call answeredrestartedunder keyfeed37b8…in 10.6 s (a 9.2 s load); its child's command line named that environment's libraries file, and the answer wasNotInScopeinsideAxiom/Set/Map/Extra.agda, the failure an old environment gives this tree. With the lock restored, the fourth call answeredrestartedunderfd3559bd…again and typedSetin 10.1 s. Without the restart, the third and fourth calls would have reused the first child.
Lifecycle, in brief. One lane per root of the same per-call project resolution the batch tools use, so "which tree" and "which process" cannot diverge; requests serialized per lane; a re-load only on evidence of change (mtime, size, and a content fingerprint, or the client's reload: true for a changed dependency, which no stamp on the queried file can see); one deadline shared by every phase of a request; the #77 kill ladder on expiry, then a respawn; a crash surfaced as a structured failure naming the lane, the event, and the child's stderr tail, never a bare -32603; idle lanes closed by EOF, which Agda answers by exiting cleanly; a lane whose Agda changed restarted before reuse (#347).
Status. Adopted (PRs #107 and #110; the display mode since PR #257 (#248); the restart by PR #349 (#347)). Open: queries inside a parameterized module's scope (#139, [M5-6]); an honest payload when hole goals degrade to ? because the lane holds no matching load (#146, [M5-8]); many-files-one-call forms of check_file and exports_of (#135, [M5-2]); and in-band cancellation via Cmd_abort instead of the kill ladder, noted as follow-on work in the lane note.
3. The verdict discipline¶
(See also #69, #72, #78, and [agda-mcp/README.md].)
Decision. For the per-file tools, success is a function of the exit code alone; check_project adds two conjuncts, in the safe direction only (below); and every verdict says what ran and what green means.
- Every batch proof-state response carries
verdict(equivalentTo, the exactagdacommand the call is equivalent to;meaning, one sentence;exitCode, Agda's own),command(binaryresolved againstPATH,args,cwd), andproject(§ 5); the one response shape without averdictis a lane-sourcedget_goal, which carriescommand,project, and the lane echo instead (below). A change in Agda's message format can empty the diagnostics list; it cannot turn a failing build green. The suite pins this with a stand-in binary that exits non-zero while printing nothing a parser could latch onto. fill_holetolerates exactly one class of error on an otherwise green file: the[UnsolvedInteractionMetas]of the file's other open holes and of sub-holes inside the candidate. A candidate that leaves[UnsolvedMetaVariables]or[UnsolvedConstraints]is a type error (#69, PR #81); that is the FLRP "implicits under a defined function" pattern that cost the field session a build cycle.- There is no
strictoption, because there was never a lenient mode; the work of #72 was contractual, not semantic, and the tool descriptions now carry the client-visible contract, so what a client receives when it connects (tools/list, and since #191 theinitializeinstructions) answers whether green means the build passes (the report's § 6 meta-suggestion). get_goal's batch path reports a non-zeroexitCodeeven when the goal is right, because the injected macro leaves an interaction point behind, and its description says so; a lane-sourced answer carries no verdict at all.check_project(#78, PR #98) is the one deliberate departure, and only in the safe direction:successis a conjunction of exit 0, finishing inside the bound, and no failure evidence in the output, so a wrapper that ends inechoand reports exit 0 for a failedmakecomes back assuccess: falsewithmaskedFailure: true. The recognizers (an Agda error diagnostic, GNU make's own*** ... Error Nline) are a list, not a theory, sooutputTailis returned whatever the verdict; evidence can turn a green gate red, never a red gate green. The gate is discovered in a fixed order (a namedmaketarget;--check-command, run directly with no shell; the nearest Makefile'scheck;agdaon theEverythingmodule; else a failure naming what was searched), and a check that did not happen is never reported as a pass.
Evidence. The § 7 verification of the field report is the record of what an untrustworthy verdict costs, and the consumer-side document written after the RP-3 session ([feedback/agent-case-for-corpus-proof-search.md] § 1) names the discipline's effect: it "removes an agent's ability to talk itself into 'probably green'". The 2026-08-21 field report used the verdict echo to quote a check in a PR body "as a checkable claim rather than an assertion".
Status. Adopted (PRs #81, #95, #98). Since #184 (PR #190) the default answer carries verdict.exitCode alone, and a call that passes verbose: true gets equivalentTo, meaning, and command back field for field; the meaning sentence is stated in each tool's description instead, and an error response keeps the whole echo. No open follow-up.
Where the contract is stated (#191, PR #193). A client puts every tool's description and schema, and the server's initialize instructions, in its model's context on every turn, and Claude Code 2.1.282 cuts each description, and the instructions, at 2,048 characters. Measured before #191: eleven of the fourteen descriptions ran to 3,193 to 7,648 characters, so 27,808 characters of contract never reached a model, fill_hole's status rule, check_file's hole listing, and the wrong-tree refusal on two tools among them; and about 37,500 of the 77,603 characters of tools/list repeated text stated elsewhere in the same list. So the contract is now split by who shares it and stated once.
- The instructions (1,981 characters) carry what every tool shares: the two lanes and each one's cost (the exit-code rule stated of
successalone, sincefill_hole's status tolerates open holes,check_project's output can turn its gate red, andget_goal's fallback exit judges nothing),reload, the path refusal, the tree every answer names and the wrong-tree refusal with its registry limit,verbose, how failures arrive,checkedFromSource, and the hole model's coordinates; they name only the tools the server exposes. - Each description carries its own tool's contract and nothing else, every one under the cap (the longest,
check_project's, is 1,960 characters), and names another tool only when that tool is exposed (a subset hidingcheck_filegetsget_diagnostics' whole contract); the suite asserts both, for every single-tool subset. - The README carries the mechanism a model does not need in order to use a tool correctly (
search_in_scope's rendering ladder and rank formula, the lane's re-load vocabulary). --expose NAME,...presents a subset:tools/listand the instructions name those tools alone, and a call to any other registered tool is refused by name before it runs.
tools/list fell from 77,603 characters to 24,094 (plus 1,981 of instructions; the arms below ran the same tools/list and a 1,989-character version of the instructions, before review fixes scoped their exit-code rule to success), and the surface as delivered to Sonnet 5, the first-turn difference against a one-tool probe server, from 16,230 tokens a turn to 9,217, or 3,583 with the four verdict tools alone exposed. On Sonnet 5 arms at the #162 caps (runs arm-surface-mcp-1 and -2, arm-surface-both-1, arm-verdict-mcp-1 and -2, 2026-09-26, zero anomalies; [reports/agent-bench/README.md]) the trim cut a server arm's cached tokens a turn by about a third and its cost by 17 to 19 %, and left the tool mix and the restatements as they were. With the four verdict tools alone the per-turn context fell below the shell arm's (about 9,600 cached tokens a turn against 10,060), yet the arm cost USD 3.78 and 3.84 against 2.88, because it wrote more and took 150 more turns, most of them reading the library by trial (111 and 97 failed reads). That arm solved 52 and 53 and restated 1 and 2, against the full surface's 48 and 45 and 7 and 8, and the transcripts show the difference is the route and not better proving: with the search tools the subject found the library's lemma by name and cited it; without them it read the original's module and wrote the proof out, which the judge counts as solved, and on the 34 rows with no original every arm solves 31 to 34.
4. Ask Agda, don't re-derive¶
(See also #100, #106, #185, and [agda-mcp/agda-mcp-ask-agda-audit.md].)
Decision. answer = whatAgdaSaid <|> whatWeDerived. When Agda can answer a question, in output a call already captures or through a lane query, Agda's answer is the authority; a local derivation from source text is a pre-flight approximation and a fallback, and a change in Agda's output degrades a field to the derived value, never to a wrong value. The rule is written where a new tool's author will read it, in the README's architecture notes, and #106 audited it across every derived answer in the server.
- The worked example (#100, PR #105).
get_goalscanned the file for itsmodulefield, so a literate file whose prose opened a line withmodulewas reported under the prose's name, while Agda had already printed the true answer in theChecking M (path).line of the same run. Agda's answer is also better than a correct scan's: it is the name Agda resolved (AnonModulefor amodule _ whereheader,Proofs.Usefor a hierarchical module), where a scan can only repeat what the header claims, and the difference is a diagnosis. Both paths now read Agda's name first (the lane's storedliModule, the batch run'sagdaModuleNameOf), with the declared-name scan off the code-only view as the fallback. - The inventory's verdicts. Delegated: goal type and context (#108), the module name (#100, #108), goal-scoped hole answers (#75). Subordinated rather than substituted: the batch listings' hole positions and spans, which the scan still computes on every call because the splicing engine structurally needs a source view; their warrant is the parity suite (tier 2d against batch Agda, tier 3 against the lane's interaction points), not a per-call answer, and the audit records that residue accurately. Stays local by measurement: project resolution, because no Agda query answers "what libraries and include paths apply to this file" and the lane is a consumer of that answer, not a source. Out of scope: the gate discovery in
AgdaMCP.Gate, which is not Agda's question. - Measurement 1 refuted the strong conjecture. Driving
agda --interaction-jsonover the § 5 error corpus showed the protocol carries the same prose batch prints, in a JSON envelope: the envelope retires the parser's segmentation layer in principle (block splitting, banner dedup, severity classification) and none of its content extraction (codes, ranges,involvedpayloads). So #74's parser stays, transport-independent, and a lane-sourced diagnostics tool would run the same parser on the same prose. The one class where the protocol carries more than the prose, unsolved metas with names and types as data, became #115. - Measurement 2 found a hole in the rule's own application, and became #114 (§ 8).
- One answer is derived by design: what a definition says (#185).
definition_ofanswered where a definition is (the file and the range of the name at its binding site, which is what Agda's WhyInScope answer carries), and since #185 it also quotes the declaration that site opens:source {startLine, endLine, text, truncated, declarationEndLine?}, the defining file's own lines (the signature and its clauses, awhereblock included), at mostmaxLinesof them (40 by default). No interaction command answers a declaration's range, so the extent is cut by Agda's layout rule over the source (AgdaMCP.Declaration): deeper lines, further clauses of the same name, and the interior of a hole continue a declaration, and the first other line at its indentation ends it. The derivation is kept honest by being checkable rather than by being authoritative: the text is verbatim and names its line range. It is not elaborated; the elaborated body, which Agda could answer as a library, is #164.
Evidence. Four module-name shapes measured on #106 (Agda's answer against the scan's); the per-class table in the audit's § 3, one fixture per § 5 error class driven three ways; and the acceptance item that asked #75 to say it "retires" the scanner and the injection, recorded as overtaken because the scanner splices and the injection reports visibility on purpose.
Evidence for the source quote. The arms of #162 measured the gap it closes: given the server and a shell, the subject called definition_of 0 times (19 in the server-only arm) and read library sources through the shell instead; and on the hard tier of #189, the server arm's 14 definition_of answers were followed by 16 Read calls of a file an answer had named. Over the 92 distinct sites the archived arms asked about, the declarations ran to a median of 2 lines (135 characters), 15 lines at the 90th percentile, 29 at the 95th, and one module to 686; 40 lines quotes 87 of the 92 whole. Re-run on the protocol of the header-free arms with the server the only change (2026-10-03; [reports/agent-bench/README.md]), Sonnet 5 called definition_of 47 times in 25 of 55 sessions against 11 in 8, taking the calls from exports_of, type_of, and search_by_name (knowledge calls 81 against 85); Opus 5 on the hard tier followed 11 answers with a Read of the named file against 19, read the library 23 times against 31, and cost 18 % less, with every quote whole and the remaining reads of the module around the definition.
Status. Adopted (PRs #105, #110, #116; the source quote in PR #229). No open follow-up; the rule is the review question for every new field.
5. Project resolution and transparency¶
(See also #76, #101, #103, and [agda-mcp/agda-mcp-environment.md].)
Decision. The library context is resolved per call from the requested file, echoed in full, and a wrong tree is an error, not a wrong answer.
- Resolution. Walk up from the file to the nearest
*.agda-lib, stopping at a repository boundary; read the registryagdawill actually use (the server's--library-file, else$AGDA_DIR/libraries, else~/.agda/libraries) fresh on every call, because a snapshot at startup is not necessarily what the next call will read; then act on the comparison. A registry that roots the file's library elsewhere is refused beforeagdais spawned, with arootMismatchobject naming both roots and the registry that disagrees. A registry that agrees proceeds unchanged. A library the registry has never heard of proceeds with its owninclude:directories added as-i. No*.agda-libabove the file proceeds on the server-start configuration and says so,rootSource: "server-config". Two stated limits: a configured--library-filethat does not exist leaves nothing to compare against, which the response reports aslibrariesFileMissingrather than leaving the caller to infer it; and the name comparison is exact, so the check catches stale worktrees, not stale versions. - The echo.
projectcarriesrootSource,root, the file's ownlibrary, thelibrariesFileconsulted, what it declares (registeredLibraries), and the effectiveselectedLibrariesandincludePaths, soprojectandcommand.argsnever disagree. - Paths are resolved honestly and never guessed (#101, PR #102). A relative
filePathresolves against the server's working directory, the only directory a separate process knows; a path that resolves to nothing readable is refused with apathErrornaming what was sent, what it resolved to, the directory, and the fix, and only regular files are ever opened. Trying the path under each registered root and taking a unique hit would have made the #83 call succeed, at the price of occasionally answering green about a tree nobody named, which § 3.6 of the field report calls worse than an error. MCP'sroots/listis the protocol-correct way to learn where a client stands and is left as follow-up work pending a bidirectional transport. - A foreign toolchain is a first-class client (#103, PR #104).
--agda-binnames the client's ownagda(for a Nix-pinned project, a gc-rooted wrapper realised once), and--cwdnames its checkout root, because Agda anchors project discovery to the directory it runs in, not to the checked file; the checkingagdathen runs there and writes its interfaces where the project's ownnix develop --command agdawould. - The stray directory (#76). The untracked
agda/directory the field report saw in a client worktree was reproduced and explained, and the fix is recorded in § 11.
Evidence. The 2026-08-21 report: rootSource: "nearest-agda-lib" picked up the worktree's own .agda-lib while the server's cwd was another repository, "precisely the failure mode agda-algebras' CLAUDE.md warns about for the nix develop agda wrapper", and "the echo makes it verifiable rather than hoped-for". The 2026-09-01 fls report: both subprojects (formal-ledger and the Hydra-only formal-ledger-test) resolved with zero configuration, where the CLI equivalent is hand-assembled -i flags. The 2026-09-01 agda-algebras report: a LibraryError on first contact was a ten-second read from command, project.registeredLibraries, and rootSource. Eight of the nine reports name the per-call resolution or its echo as the reason a cross-worktree verdict could be trusted.
Status. Adopted (PRs #95, #102, #104). Since #184 (PR #190) the echo is in full only on request: the default answer carries project.root and project.rootSource (and librariesFileMissing when it is true), so every answer still names its tree, and verbose: true restores the rest of the block field for field; the wrong-tree refusal is unchanged. Open: the registry's one-absolute-path-per-library shape goes stale under worktree churn (three sessions in two weeks hit it), and #137 ([M5-4]) chooses between a parent-directory registration and lazy resolution.
6. Structured diagnostics¶
(See also #74 and [agda-mcp/README.md].)
Decision. Diagnostics are data beside the prose, in a shape a client can branch on.
- Each carries
code(Agda's own bracketed name, or a warning's-W[no]Code);fileand a 1-basedrangein the file as written (both of Agda's position formats parse, andlineandcolstay as aliases of the start); the full message body, bounded at 24 lines and 2000 characters with the elision stated; and aninvolvedpayload per code:expectedandactual,candidates(did-you-mean lists, ambiguity candidates, missing exports, a clashing definition's origin),metaTypesper unsolved meta or constraint, and since #115metaswith each meta's name, type, and range when a warm lane holds them. - Ordering is most-likely-root-cause first and stable: unresolvable-file errors, the scope warnings that precede a hard error (
ModuleDoesntExportbefore theNotInScopeit causes), scope errors, type errors, unsolved metas and constraints, remaining warnings. The list is capped bymaxDiagnostics(default 10) withdiagnosticsTotalreporting the pre-cap count, and the duplicates Agda prints under its "All done; warnings encountered" banner collapse to one. - The regression suite has one fixture per class of the field report's § 5 corpus, asserting the code, the range, and the payload § 5 asks for.
Evidence. The 2026-08-29 report: five errors across the session, "each diagnosed from one call", including two UnsolvedMetaVariables batches whose involved.metaTypes identified the implicit-endpoint disease and "one stray underscore whose 1-char range pinpointed an argument that vanishes under reduction". The 2026-09-02 report: six errors in a 737-line module, each "localized instantly", the fixity bug "a ten-second read" from involved.actual/expected. The consumer-side document's § 1 names structured diagnostics as the attack on an agent's dominant failure mode, "misdiagnosis followed by thrashing".
Status. Adopted (PRs #94 and #118). Open: UnsolvedConstraints restates the whole meta dump beside the UnsolvedMetaVariables list that was the useful part, "a hundred lines for six metas" (#145, [M5-7]).
7. The hole model¶
(See also #70, #71, #73, #79, #136, #201, and [agda-mcp/README.md].)
Decision. A hole is what Agda would treat as an interaction point, addressed by position, and every answer re-anchors the client.
AgdaMCP.Holesports Agda 2.8.0's literate preprocessor and a model of its lexer (PR #88): every hole syntax ({!!},{! ... !}with nesting, a lexically separate?); no hole inside comments, pragmas, string or character literals, or literate prose; every literate flavour Agda supports masked to its code regions; and all positions in the coordinates of the file as written. The same scan yields the code-only view that the reporting-macro injection and the module-name fallback read, so there is one answer to "is this line code?" rather than one per caller (#100).get_goalreports the hole's goal, not the reporting macro's own unsolved type; the defect was in the agda-dojang reflection layer as driven by batch Agda 2.8.0, and CI could not see it because no test asserted an end-to-end goal value (#70, PR #82).- Holes are addressed by
(line, column), withholeIndexkept for compatibility and documented as source-order and shift-prone (#79, PR #99). A position inside no hole is an error listing the file's nearest holes, never a guess; a request carrying both spellings, or half a position, is rejected.check_fileandfill_holereturn the full hole list, andfill_hole's list describes the file as that candidate leaves it, so a multi-hole edit needs no index bookkeeping between calls. - A file with one hole has nothing to guess between (#201). There, a position on a line the hole occupies reaches it whatever its column, and so does a call that names no hole; a file with two or more holes keeps the strict rule. Every
get_goalandfill_holeanswer says which hole it used and how,addressed {line, col, resolvedBy}, whereresolvedByisspan,index,only hole, same line, oronly hole, so a caller that meant something else sees it. The input schema'soneOfgained the no-address shape, and its branches now exclude one another, so it admits exactly the requests the parser accepts over every combination of the four address keys (before, it admitted an index beside half a position, which the parser refuses). -
A checked candidate reaches the file by an apply, or reaches its client as a patch (#136).
fill_holetakes two optional arguments, and a call that passes neither restores the file and answers as it did, byte for byte. -
apply: trueleaves the candidate in the file when, and only when, its status isok;appliedin the answer says whether it did, and every other status (type_error,timeout,crash) restores the file. It is for an agent working alone, whose next step was to write the same text with its own edit tool. patch: trueaddspatch, the edit that was checked, in the form a client applies to a text of its own: an editor changes its buffer, not the file, and can show the candidate before it does. It is answered on every status, because it says what was tried andstatussays what Agda made of it; a candidate Agda refused is still something a person may want to edit.-
--no-applyis the operator's refusal of the first. A server started with it declares noapplyin its schema, promises none in its description, and refuses by name a call that passes one, so a registration beside an editor leaves no lasting change under an open buffer. -
A patch names its text, its place in two units, and both results (#136). It is
patch {file, digest, range, bytes, oldText, newText, resultDigest}, as follows: -
digestandresultDigestname the file's bytes before the edit and with it, each assha256:and 64 hexadecimal digits; that is agda-native-ide's basis, the digest of the UTF-8 text Agda read (its ADR 0003, § 4).resultDigestis of the bytes Agda judged, which are the bytes an apply leaves. range {startLine, startCol, endLine, endCol}is for a client that holds a text. It is 1-based with its end exclusive; a line ends at LF; a column counts Unicode code points, so an astral glyph such as𝑨is one column (and two UTF-16 units, and four UTF-8 bytes); and a leading byte-order mark has no column. These are the coordinates of every hole list, and they are Agda's.bytes {start, end}is for a client that holds the file: 0-based offsets into its bytes, the end exclusive. They need no convention, a byte-order mark and a carriage return being bytes like any other.oldTextis what the range holds, for a client to find there before it writes;newTextis what replaces it.-
The shape is not
fill_hole's alone. A refinement's replacement holds new holes (#209), and a case split replaces a whole clause, on several lines (#207); each is a range, the text it holds, and the text that replaces it. -
The splice adds nothing (#136). The candidate replaces the hole's whole token (
{!!},{! e !}with its contents, or?) exactly as it was sent. Agda's own give parenthesizes a term where the hole's place needs it, andfill_holedoes not:f xfor the hole ofg {!!}is checked, written, and patched asg f x. So what is checked, what an apply writes, and what a patch says are one text, and a caller who wants the parentheses sends them. -
The server writes only over bytes it knows (#136). The in-place check has other writers beside it: an editor saves when its user does. So the patched text goes over the file only while the file holds the bytes the call read, and the restore, or the decision to keep, is made only while it holds the bytes the server wrote. A file found changed is left as the other writer left it, and the call fails as
fileChanged {file, when, expected, found}with no verdict, since Agda may have read either text.get_goal's fallback patches the same way and has the same guard. Until #136 the restore was unconditional, and a save made during a check was overwritten by it. The guard is a comparison and then a write, so it shortens the time in which a save can be lost, from the whole check to the instant between the two, and does not end it; and the two steps that touch the file (the comparison with the patch write, and the settlement) cannot be interrupted, so a call cancelled inside one still leaves the file settled. A cancelled call keeps no candidate: one held through a settlement that kept a candidate is taken at a last check whose handler restores, so only a cancellation in the instant between that check and the answer reaching the client leaves an accepted candidate unanswered. -
The lane needs nothing new for an apply (#136). A lane re-loads a file whose stamp (modification time, size, and a fingerprint of its bytes) has changed, and the batch tools' peek declines a load whose stamp is stale (§ 2). An applied candidate changes the stamp, so the issue's first design point was already met, and a test now holds it; no batch tool calls a lane to say so (decision 3).
Evidence. Verification's fixture with four Agda-visible holes reported two, one of them in a header comment, so "the first hole" addressed a comment (#71); fill_hole on a prose token in a .lagda.md returned ok (#73). Parity tests pin the scan to batch Agda and to the lane's interaction points across the fixture matrix. ADR 0001's state model adopts fill_hole's re-anchored list wholesale, so client-side hole arithmetic can never drift from Agda's.
Evidence for the one-hole rule. Across the archived agent-bench arms of #154, #162, #184, #191, and #189 (and their cost runs), the strict rule refused 39 of 234 fill_hole calls and 47 get_goal calls, and four more fill_hole calls named no hole. All 86 refusals were in a file with exactly one hole, on the line it sits on, with the column off by one (21 of the 39 fill_hole refusals: a 0-based column) to thirteen; each cost a turn retrying at the position the refusal listed. Replayed through the new server against the work files as they stood at each call (rebuilt from the subjects' own reads and edits), all 90 resolve: the 86 as only hole, same line, each at the hole its refusal listed, and the four as only hole; Agda then judged 38 of the 43 fill_hole candidates ok and 5 type errors, and answered all 47 goals. In the re-run mcp arms (hard-answers-opus5-mcp-1, suite-answers-sonnet5-mcp-1, 2026-10-03; [reports/agent-bench/README.md]) no address was refused, and 10 reached their hole by the one-hole rule, against 3 refusals in each header-free baseline.
Evidence for the apply and the patch. Measured 2026-11-23 and 2026-11-24, at the pinned Agda 2.9.0.
- The friction. The first session with the server as its main instrument (agda-algebras, 2026-09-01) wrote that "every accepted candidate has to be re-applied by hand in a second edit step"; a review session in formal-ledger-specifications (2026-10-06) made three
fill_holecalls, allok, "then written back by hand" ([mcp-field-reports.md]); and a session of 2026-10-13 made six, eachok, and wrote every candidate back afterward in one batch ([field-reports/2026-10-13-private-abelian-socle-lemma.md]). - Who applies. An agent alone writes through its harness. In Claude Code 2.1.331, after a file was rewritten on disk with the same bytes (what a restore does) the edit tool edited it without remark, and after its bytes changed on disk (what an apply does) the edit was still made, with a note that the file had changed since it was read; so an apply costs that agent no read. An editor is the other client: it changes its buffer, as agda-native-ide's Emacs tools put a give in the buffer (ide#71), and a server that wrote the file under it would leave the two apart.
- The unit, against Agda. Batch Agda lists the five holes of the suite's fixture at
29.9-13,33.9-10,37.7-17,44.17-18, and44.19-20in each of four encodings of it: LF, CR LF, a leading byte-order mark, and both. Its reader (Agda.Utils.IO.UTF8.readTextFile) says why: it strips the mark and makes each CR LF one LF before anything is counted. The server's scan agreed with one exception, a marked file, where it was wrong twice: a hole on line 1 sat one column right of Agda's (65 against 64), and a--comment that opened the file was read as code, so a hole token in it was listed (two holes where Agda has one). The scan now drops the mark before it counts. A wide character counts one column in Agda, and a tab in code is a lexical error there. - The mark, and the scans that read lines. Review of PR #371 found the same defect one layer up: the views the line scans read kept the mark as line 1's first character, so the first token there was the mark and the keyword run together. On a marked file whose line 1 is
module M where,get_goal's fallback found no header to put its import under and the module-name fallback found no name; anopen importon line 1 was no import tosearch_in_scope; anddefinition_of's quote read a line-1 site one character to the left, cut a definition there after its signature, and carried the mark into its text. All four are older than #136. The views are now of the text after the mark, and the declaration quote takes it off first; five tests hold it, one of them against Agda (the fallback answers the goalNand the moduleBomHeaderon such a file, and restores it, mark and all). - The CR of a CR LF. The scan ends a line at LF, so the CR is its line's last character, and it sits at the column where Agda, which has folded the pair, puts the line's end: the two agree on every position Agda prints, and a hole that closes its line ends there in both. The scan alone has the column after the CR, the offset of the LF itself. Every offset of a CR LF text maps to a position that maps back to it (a test tabulates one; review of PR #371 had read the CR as mapping back to the LF), no hole of the fixture starts or ends inside a pair in any encoding, and the function that builds a patch states that a span must not.
- Where the scan still differs. Agda also ends a line at a lone CR, a form feed, NEL, LS, and PS; the scan does not, and neither does an Emacs buffer (a form feed alone on a line: Agda places the hole after it on line 6, the scan and Emacs on line 5). That is #369.
- How common each case is. Of 4,318 Agda sources (the standard library 2.3, agda-algebras at the flake's pin and at its
master, formal-ledger-specifications at itsmaster, and this repository) none holds a byte-order mark, a CR LF, or one of those five characters, while 310 of agda-algebras' 407 hold an astral glyph. The code point is the unit that matters daily; the rest is for a file an editor on Windows saved. - The unit, in an editor. In Emacs 29.3 (
emacs --batch),forward-lineand thenforward-charreach the hole at Agda's line and column in all four encodings (the buffer holds no mark and no CR) and after a wide character;move-to-columnstops one character short after漢, because it counts display columns. - A wrong unit is not caught by the old text. On the fixture's line
q = f 𝑨 (f 𝑨 (f ? ?))the second hole's column, read as a count of UTF-16 units, is the first hole's place, where the same?sits. A test applies the patch both ways: in code points it gives(f ? zero), the text Agda was handed; in UTF-16 units it gives(f zero ?), and nothing warns that client butresultDigest. This is the splice defect of ADR 0001's decision 16, reproduced on purpose. - The tests. 51 new tests (653 to 704; 39 with the change, ten from the first review of PR #371, and two from the second). Tier 1o, without Agda, uses stand-in
--agda-bins that record the bytes they are handed: for each of the five holes in each encoding, the patch applied to the original, by bytes and by line and column, gives exactly those bytes; an apply leaves exactly them onokand restores the file byte for byte ontype_error,timeout, andcrash; a stand-in that saves over the file during its run, or moves it away, finds its file as it left it, on the restore path, the apply path, andget_goal's fallback; a call cancelled during the check restores; and a hole written across two lines has a range that ends on its second. Tier 2k holds every patch's range to the lane's own interaction points, start and end, in each encoding and on line 1 after a mark, applies five candidates in turn by the positions each answer re-anchors untilcheck_filepasses the file, and shows the lane after an apply (the peek fills no goal from the old load, the next lane call answerschanged, and the peek then fills goals again). Tier 2l drives--no-applythrough the executable. Twenty-five deliberate breaks of the server, made one at a time, each failed between 1 and 11 tests, and none passed the suite: the restore and the keep made without looking at the file, and the first write likewise; a cancelled call that leaves its patch; an apply that keeps a refused candidate, or is ignored;appliedorpatchanswered unasked; a column counted in UTF-16 units; a byte-order mark counted; a byte range counted in characters; either digest naming the other text; a range's end misplaced; one rotation of SHA-256 changed; a splice that adds parentheses;--no-applydeclaring, promising, or allowing an apply; and a lane, or a peek, that ignores the file's stamp. The review's ten tests are the three on a file in memory (the masking each step runs in, and the two cancellations), the five on line 1 of a marked file, and two on a CR LF pair; nine more breaks, made the same way, each failed between 1 and 5 tests: either file step left interruptible; the mark put back in each of the three views; the declaration's extent, or its quote, read on the marked text; a position that skips the CR; and the old wording under--no-apply. One of the nine first passed the suite, because the fixture's signature named the definition whatever name was read at the site; the test now asks for the extent of clauses with no signature. The second review's two tests come with three more breaks, each caught: no last check after a keep, a last check whose handler does not restore, and one that restores whether or not anything was cancelled. - What an answer costs. A call that passes neither argument answers as the server before this change did, field for field once
elapsedMs,pid, andloadElapsedMsare dropped: seven tools on a standard-library and an agda-algebras obligation (14 answers, and 14 withverbose: true), andfill_holeon all 22 standard-library obligations with a refused candidate and with a refinement (44 answers, 25okand 19type_error, and 44 verbose). Two runs of the old server differ from each other incheckedFromSourceon three of the 44, where a candidate closes a file's only hole and leaves an interface for the next run, and the new server's answers equal the second old run's.appliedadds 15 or 16 characters to an answer, and a patch adds 318 plus the file's path and the candidate (482 and 483 on the two obligations). What a client is shown on every turn grows by 707 characters, all of itfill_hole's entry intools/list(3,021 to 3,728; its description 1,630 to 1,784 of the 2,048 a client reads; the whole list 26,099 to 26,806 with the suite's corpus fixture), and the instructions grow by 14, for the unit (2,005 to 2,019, and 2,042 with every tool exposed). - End to end. A scratch library outside every repository (an
.agda-liband one module with three holes, the first after𝑨), registered with this checkout'sscripts/run-server.shas [agda-mcp/connecting-an-agent.md] says, each call made through the registration as a client makes it.fill_holewithpatch: trueon the hole after the glyph answeredokand a patch at15.12-16, bytes 205 to 209, whosedigestwas the file's ownsha256sum, and left the file as it was; a short script that knows only the patch applied it by bytes, and the file's digest becameresultDigest.apply: trueon the{! zero !}hole with the candidate𝑨answeredapplied: trueand leftb = 𝑨. A refused candidate for the last hole, with both arguments, answeredtype_error,applied: false, and its patch, and the file's digest did not move; an accepted one answeredokwith exit code 0 andapplied: true, and the file's digest was itsresultDigest.check_filethen passed the file withcheckedFromSource: false: the interface Agda wrote while it judged the last candidate was the interface of the file as applied. The same registration with--no-applyrefused an apply by name. And twofill_holecalls withapply, written to one server at once as a harness that sends tool calls in parallel does, were answered in order, bothokand applied: the server reads one request at a time. - The digest. The backend shell's package set has no SHA-256, so it is written after FIPS 180-4 in
AgdaMCP.Digestand held to the standard's vectors, to every length across the two padding boundaries, and to coreutils'sha256sumon five fixtures. It costs 1.3 ms per 100 KiB; the largest source in the pinned libraries is 379 KB, and a patch computes two. - The instant the guard leaves. A comparison and the write after it are separate system calls: a read, then a truncation and a write. Traced on the server over 30
fill_holecalls (strace, ext4, 2026-11-24), the end of the read and the truncation were 0.12 to 0.51 ms apart before the check (median 0.21) and 0.12 to 2.5 ms apart at the restore (median 0.23), against 0.10 to 0.14 s between the two writes on that small module, the tracing included. A save that lands there is overwritten, as every save during a check was before. Nothing in a file's interface closes it against a writer that takes no lock: an advisory lock binds only the writers that ask for it, and an editor does not; and replacing the file by a rename compares nothing either, changes the file's identity, and loses a save written through a descriptor an editor already holds. - A cancellation inside a file step. The settlement first ran under
mask, and undermaska file open is an interruptible operation: GHC'sopenFilemakes an interruptibleopen(2)and delivers a pending exception when the call fails or is interrupted (c_interruptible_open, GHC 9.10.3), and an exception taken there would end the settlement before its write. On a local file it did not happen: of 165,173 exceptions thrown at 200,000 masked read-then-write rounds on ext4, and 129,194 on tmpfs, none arrived inside a round. It can whereopen(2)sleeps (a network or FUSE file system), so both steps now run underuninterruptibleMask_, and the suite holds that on a file in memory whose read and write block: a call cancelled during the settlement restores, and one cancelled while the patch is half written puts the original back and runs no Agda. The cost is that a read or a write that never returns cannot be cancelled. The second review of PR #371 found the path this left open: withapply, the settlement keeps an accepted candidate and writes nothing, so a cancellation held through it was taken as the call leftmask, after the keep, and the call failed with the candidate in the file and no answer saying so. A kept candidate now ends in a last check (allowInterrupt) whose handler restores; a test cancels the settlement of an apply and finds the file restored (it fails without the check), and its control finds an apply nobody cancels kept, with nothing written after the check. What remains is an exception that arrives after that check, or after the call returns and before its answer is written. In the server the call runs in the thread that reads requests, one at a time, so its cancellation is SIGINT, and the server then exits. - What the guard does not reach. A write that fails is not retried: its error reaches the caller, and since the trace shows a write to be a truncation and then a write, the file can be left short. A server stopped by SIGTERM during a check exits at once, leaves the candidate in the file, and leaves its Agda running (SIGINT restores; a closed standard input lets the check finish and restore). Two servers checking one two-hole file at once, the second starting during the first's check and ending after it, leave the first's candidate in the file; before #136 both answered
ok, and now the first answersfileChanged. All three were so before this change, and the last two are #370.
Status. Adopted (PRs #82, #88, #99); the one-hole rule since PR #228 (#201); the apply, the patch, and the guarded write since PR #371 (#136, [M5-3]). Open: the scan's line ends (#369); a server stopped during a check, and two servers on one file (#370); refine and case_split, whose answers are patches of this shape (#209, #207); and the tool annotations of #253, under which fill_hole is read-only only on a server started with --no-apply.
8. Evidence-channel honesty¶
Decision. Before inferring anything from what Agda did not say, check that the channel it would have said it on was open; an absent field means unknown, never a guess.
checkedFromSource(#77) reads Agda'sChecking M (path).progress lines, and its warm branch is an inference from silence, since a warmagdaexits 0 printing nothing.--trace-imports=0manufactures that silence, so under it a cold check wore the warm signature in both lanes (#114, PR #117). Detection is complete because the flag's arrival path is single (anOPTIONSpragma and an.agda-libflags:field are both rejected with[OptionError], so only the argv the server assembles can carry it) and its grammar is closed (=Nis the only level-carrying spelling, bare means 2, a space-separated level is not one, the last occurrence wins; every spelling measured). Both lanes read the effective level out of the argv they built and withhold every answer that would rest on a silence the server caused: the boolean in each lane, andcheck_project'smodulesChecked, which counts the same lines. A progress line that did arrive still outranks the muting.- Degrade was chosen over restore. Appending
--trace-imports=1when the effective level is 0 would keep the field truthful, but--agda-binmay name a foreign toolchain (#103), and a flag an olderagdarejects would break every call; restoring needs a version gate that degrading does not. - Unsolved metas as data (#115, PR #118). Agda prints its unsolved metas' locations and never their types, so the § 5 corpus's last ask was unanswerable from a batch run; the lane's
AllGoalsWarningslists every meta with a name, a type, and a range.check_fileandget_diagnosticsattach them asinvolved.metasfrom the same warm-lane peek that fills hole goals, never a lane call and never a verdict input;metaTypesis untouched because it is what Agda's prose said.
Evidence. The misreading reproduced through the real server on a clean module with caches scrubbed before each run (true with default flags, false with the flag appended, for the same source re-check); the lane's cold Cmd_load under the flag emitting no RunningInfo at all; the level-semantics table in the audit's § 4. Field: the 2026-08-22 report read checkedFromSource: true at 17.8 s and then false at 2.3 s as the interface reuse it was; the 2026-09-02 report caught a consumer module served from cache after its dependency changed and re-checked the spine.
Status. Adopted (PRs #117 and #118). Open: checkedFromSource: false right after an edit reads as "stale" until one remembers interfaces are content-hashed, and #138 ([M5-5]) adds a reason beside the boolean.
9. Enforced timeouts, timing, and cache visibility¶
(See also #77.)
Decision. Every call that runs Agda or a gate, on either lane, is bounded, and the bound is enforced by killing the process; every such response says how long it took, and the per-file and lane responses say whether Agda re-checked from source. The corpus lookups run no subprocess and have no bound.
agdais spawned into its own process group, its stdout and stderr drained on dedicated threads so neither can fill a pipe and deadlock the other, and raced against a timer; on expiry the group gets SIGINT, then SIGTERM, then SIGKILL, and is reaped. WrappingreadProcessWithExitCodeinSystem.Timeout.timeoutcould not do this: it kills the waiting Haskell thread and leaks a runningagdaevery time it fires. A timeout is returned as a value, never thrown, which is what lets the in-place tools' restore run on the timeout path exactly as after a clean check.- The default bound was raised from 30 s to 300 s so cold interface builds are not aborted, and the shipped registrations pass 600 s; sizing the bound too small is not a graceful degradation, since it aborts exactly the call that would have built the interfaces.
check_projecthas its own--check-timeout(default 1800 s), because a whole-project gate legitimately runs for tens of minutes. The lane shares one deadline across a request's phases, pipe writes included, and kills its child by the same ladder. - Every proof-state and live-query response carries
elapsedMs; the per-file batch tools and the lane carry the tri-statecheckedFromSourceof § 8,check_projectcarriesmodulesCheckedin its place (a count of the same progress lines, over the gate's output), and the corpus lookups carry neither. So a client can tell a slow cold call from a slow warm one, which § 3.7 of the field report says is the only way an advantage influences a decision.
One correction to the record. The 2026-09-01 fls report praises a 173 s check that "moved itself to the background and notified on completion". That is the client harness backgrounding a long tool call; the server's contribution is the bound that makes a long call safe to wait on. The behavior is real and worth having, but it is not a server decision, and this record does not claim it as one.
Evidence. #77's finding that FillTimeout was unreachable code; the suite's pinning of the restore on the timeout path; the per-call timings across the field record (§ 12).
Status. Adopted (PR #89; the lane's deadline in PR #107). Open: there is no profiling lane, so the 2026-08-30 and 2026-09-04 sessions measured with /usr/bin/time and agda --profile=internal from the shell, and #134 ([M5-1]) proposes profile_file.
10. Corpus tools¶
(See also #11 (M1-3), #202, and [agda-mcp/README.md].)
Decision. Three pure lookups over an in-memory index of an agda-strux JSONL corpus, registered only when the server starts with --corpus, and never invoking Agda: search_by_name (case-insensitive substring over names), search_by_type (fragments of the type as a statement writes it, since #202; below), and get_dependencies (a definition's dependency list, optionally expanded one hop). Since phase 1 of #17 (the status below) a fourth corpus tool, search_in_scope, reads the same index and validates every result through the interaction lane, so it is a corpus tool and a lane tool at once; the three lookups remain pure.
Evidence. At library scale (the published agda-algebras v0 corpus, docs/corpora/), 11,666 rows and 185 MB of JSONL load in about 1.4 s to a 308 MB resident footprint, because the index keeps only the fields the tools serve and drops typeAst and proof bodies; hasBody tells an agent a term exists to go and read. Two consequences are documented for query writers: dependency tokens are fully qualified, and 655 prettyQname keys are shared by more than one row. make corpus-mcp-smoke drives the three lookups over the transport.
Status. Adopted (PR #44), unchanged by the #68 wave. The forward pointer is #17 ([M2-3]): corpus-backed retrieval as server tools, scope-aware and returning checked terms, whose design map is in that issue's comments and is argued from the consumer-side document's four requirements (checked terms only; scope-awareness through the checker; honest negatives with stated bounds; latency that beats grep-plus-read). That design is not part of this record. Its phase 1 landed on 2026-09-15 (PR #161): search_in_scope, the fourteenth tool, reads the file's import surface off the code-only view, ranks the in-scope rows of the index with the driver's token-overlap scorer, and returns only renderings the interaction lane has typed in the file's scope, with an honesty ledger on every response; the contract is the issue's comment of that date, and phase 2 (search_term) stays open on #17.
Matching a type as written (#202). search_by_type matched one case-insensitive substring against each row's printed type, which is printed from outside every module: fully qualified, and with each definition's module parameter, or a record field's bundle, as its first explicit argument, which Agda's printer puts in an operator's first hole (the statement x ⁻¹ ∙ y ⁻¹ ≈ (x ∙ y) ⁻¹, inside open AbelianGroup G, is printed (G ≈ (G ∙ (G ⁻¹) x) ((G ⁻¹) y)) ((G ⁻¹) ((G ∙ x) y))). A query written as a statement reads therefore matched almost nothing, and dropping qualifiers alone, the issue's first plan, would not have changed that.
- Decision. By default each fragment, and each type, is compared as written: qualifiers dropped, after giving Agda's builtins the names the standard library re-exports them under (
Agda.Builtin.Nat.-is∸,Natisℕ); each name's module parameters dropped where it is applied, and an operator's remaining arguments put back in its holes; brackets, spacing, and case ignored. How many parameters a name takes is read off the corpus (the leading binders every function row of its module shares, half of them for a record module, counted up to the first operation parameter such asAlgebra.Definitions's_≈_, which statements pass explicitly), so it is a derived answer in the sense of § 4, used only to match and order rows and never to name or judge anything.patternsrequires several fragments in one type; hits come shortest first and carrywritten, the type as matched;qualified: trueis the old match, which the proof-search loop's retrieval proposer now asks for, so its pool is the one its published runs measured. - Evidence. The 23
search_by_typecalls in the archived agent-bench arms, replayed against their rows' corpora: 11 answered nothing on the archived server and 4 on this one (hom 𝑨 𝑩 → hom 𝑩 𝑪finds∘-hom,m + n ≤ ofindsm+n≤o⇒m≤o, andIsEpi 𝑨 (𝑨 ╱, a fragment cut off inside a bracket, findspepi), and the answers fell from 175,124 characters to 132,097. The novelty tables of #189 are met:x ⁻¹ ∙ y ⁻¹ ≈ (x ∙ y) ⁻¹findsAlgebra.Properties.AbelianGroup.⁻¹-∙-commfirst,[ x ⸴ y ]the six lemmas stated withCommutator.[_⸴_], andconjwithx ∙ yexactlyConjugation.conj-∙-hom, each pinned by a test on fixtures cut from the pinned corpora, and each finding nothing underqualified: true. The cost is at load: 0.9 s on the agda-algebras corpus and 2.5 s on the standard library's, andtools/listgrew by 1,522 characters (23,662 to 25,184 onmainafter PRs #228, #229, and #232; 24,094 to 25,616 before them) for the contract and its examples. - Status. Adopted (#202, PR #231). Not normalized, and stated in the description: variable names,
syntaxdeclarations (the corpus does not carry them), and grouping (brackets are ignored). Whether a model now reaches for the tool is the re-run arm's question, on #202.
Search in scope, folded into search by name (#203). search_in_scope answers a question no other tool can, which names this file can write and how, and over the 51 archived agent-bench runs it was presented in 681 sessions and called once, while its tools/list entry was 4,056 of the 24,094 characters every server session carries on every turn (17 %). Its description opened with the answer's field list and never named that question.
- Decision. The question moves to the search tool subjects already call:
search_by_nametakesinScopeAt: {filePath, line?, column?, reload?}, and with it the call issearch_in_scope's, the pattern its name query, answered by the same handler on the interaction lane (only the names the file can write, each rendering typed there, and the ledger).search_in_scopestays registered and leaves the default surface: a server presents it only when--exposenames it, with the type-token and goal-derived queries, exclusions, and probe budget thatinScopeAtdoes not offer and that phase 2 of #17 builds on. A rewrite of its description would have kept the per-turn cost and bet on wording; a removal would have dropped the answer while subjects kept failingNotInScopeprobes. - Evidence. Of the 681 sessions, 286 asked the question some other way:
search_by_namein 103,exports_ofin 103,grepin 137, and 29 calls failed withNotInScope. 17 of those questions, replayed throughsearch_in_scopeat their obligations' holes with the subjects' flags and corpora, got a spelling Agda typed in the file's scope (11, three of them only qualified, which is what theNotInScopeprobes had missed), the honest "exists, not imported" (3), a corpus row the library refused (1), or noise from a three- to six-letter pattern (2); the answers were no larger thansearch_by_name's (median 2,675 characters against 3,535), and the first call paid the lane's load, 0.8 to 11.4 s. Throughsearch_by_namewithinScopeAtthe same calls answer field for field assearch_in_scopedid, but forcheckedFromSource, which a second call on a loaded file reads as false. The default surface fell from fourteen tools to thirteen and from 24,094 characters oftools/listto 22,109 (21,946 before its review added the nestedrequiredand the blank-pattern rule) (the instructions from 1,981 to 2,005, namingsearch_by_name'sinScopeAtamong the lane's answers and scoping "every answer names the tree" to answers about a file). Evidence comment on #203. - Status. Adopted (#203). Whether
inScopeAtis used is the re-run arm's question, on #203.
11. Environment and registration¶
(See also #76, #103, #133, #242, and [agda-mcp/agda-mcp-environment.md].)
Decision. The server is a separate process with its own toolchain and working directory, and the client registration says so explicitly rather than relying on anything the operator's shell provides.
- The shell wrapper is not the server's
agda. Insidenix develop, theagdaonPATHis a wrapper that supplies a--library-fileinto the Nix store, and the shell function the hook defines (which adds--no-default-librariesand the--libraryflags) is invisible to any subprocess. So a client registration passes--library-fileand-lexplicitly, andcommand.binaryin every response says whichagdaran. agda/librariesis shared, mutable, process-global state. The hook exportsAGDA_DIRunconditionally and rewrites$AGDA_DIR/librarieson every shell entry from whatever*_ROOTvariables are then in effect, which is why the server reads the registry fresh per call (§ 5) rather than at startup. The server writes nothing of its own; the only durable writes are Agda's.agdaiinterfaces beside each checked source and, since #136, a candidate that a call asked it to apply (§ 7), which a server started with--no-applyrefuses.- The stray directory, explained (#76). The flake's shellHook derived its root from the client's checkout when an MCP client spawned the server there, wrote a broken registry into
<client>/agda/, and sbt's version probe wrotetarget/beside it.scripts/run-server.shnow anchors the shell withAGDA_NATIVE_AIR_ROOTand enters this repository first, and the hook validates its root against a marker only this repository carries, warning loudly instead of writing elsewhere. - One registration shape, anchored per worktree. A client project is checked with its own pinned toolchain: the registration names that project's wrapped Agda with
--agda-binand its checkout with--cwd(#103). When this repository's registry already knows the client's library, as it knows agda-algebras (at the flake pin), the registration also passes the wrapper's own registry as--library-file, because the server reads the registry from its own flags, else$AGDA_DIR, and cannot see inside the wrapper (#222). agda-algebras first registered throughenv.AGDA_ALGEBRAS_ROOT, which the hook turned into a line in this repository's registry; every launch rewrote that shared file, so a second session in another worktree re-pointed the first session's registry, and its server then refused its own files. In the claude-tooling registrations both clients anchor to${PWD}, which Claude Code expands inargsat spawn, so each session binds to the checkout it was launched from through one shared registration file (#133, verified end to end on 2026-09-01). The fls template underagda-mcp/examples/carries an absolute placeholder for clients that do not expand variables; the agda-algebras template carries${PWD}, since one file serving every worktree is its point, and since #242 the launcher substitutes the worktree's path for a client that does not expand it. - The launcher anchors the server where the client started it (#242). The launcher's
cdto this repository serves the shell's hook alone. It records the directory it was started in first (rule 10 of claude-tooling's discovery rules: for Claude Code, the directoryclaudewas launched from), passes that directory as--cwdwhen the arguments carry none, and substitutes it for${PWD}and${PWD:-default}, the two forms Claude Code expands, wherever they occur in an argument. It expands no other variable, and names on stderr any argument still holding${. So a client that expands nothing, or a registration that leaves the flag out, anchors exactly as Claude Code's expanded--cwd ${PWD}does, and every registration that names its checkout explicitly is unchanged. The server, for its part, documents the flag as optional (it stays where it was started) and refuses a--cwdstill holding${by name, with the two fixes (omit the flag, or pass an absolute path), even where a directory of that literal name exists. - The launcher's fast path (#249). Entering
nix developcosts seconds before the server can answerinitialize, and a client that does not wait loses the server: Codex CLI'sexecsends its first request without waiting, and in #243's trial its model looked for the tools 8 ms before they arrived and ran every check from the shell. A registration that names a prebuilt server (AGDA_MCP_BIN, in itsenvblock) and its own Agda (--agda-bin) needs nothing from the shell, so the launcher makes the same substitution and--cwddefault, enters this repository and clearsLD_LIBRARY_PATHas before (so a relative--cwdmeans the same on both paths), and then runs the server directly. The fast path is never the default, and never taken without--agda-bin, because the server's defaultagdais the shell's. What it gives up is the shell's environment: the server and every process it starts inherit the client's, somakefor a gate, the program a--check-commandnames, a bare--agda-bin, and$AGDA_DIR(the registry the server reads when--agda-flagsnames no--library-file, and Agda'sdefaults) come from the client. The shell path has the opposite gap, stated beside it: acheck_projectcall naming atargetruns baremake <target>, whose recipe gets this repository's Agda. AnAGDA_MCP_BINthat is not an executable file is refused by name before either path starts, with the wording the shell path always used.
Evidence. The reproduction in the environment note (a foreign git init directory acquiring agda/libraries, agda/defaults, and target/ on shell entry, with a registry line pointing at a path that does not exist) and its after-fix table; #133's diagnosis, in which every fls checkout's .mcp.json was a dangling symlink and the tooling copy was a byte-for-byte agda-algebras registration; and #222's reproduction on 2026-09-29, in which a server in one agda-algebras worktree checked a file green and then refused it once a second session started in another worktree, while under the new registration two sessions each check their own worktree side by side and this repository's registry stays byte-identical. For #242, make agda-mcp-launcher-smoke (2026-10-09) starts the real launcher five times from a scratch checkout whose path holds a space and an ampersand: --cwd ${PWD} (with ${PWD} inside --agda-flags too, as claude-tooling's agda-flrp registration writes it), --cwd ${PWD:-/nonexistent}, no --cwd, and an explicit --cwd from another directory each run that checkout's own gate, and --cwd ${CLAUDE_PROJECT_DIR} is named by the launcher and refused by the server. Against the previous launcher four of the five fail, the explicit flag alone passing; against the previous server, the tier-2g refusal test fails, because that server entered a directory literally named ${PWD} and started. For #249, launch to ready is defined as the wall time from spawning the registration's exact argv to the first stdout line that is the response to initialize (scripts/python/launch_to_ready.py), and make agda-mcp-launch-time (2026-10-11, five runs each way, from an agda-algebras checkout, load average 3.5 to 11 from other sessions) measured it with claude-tooling's agda-algebras registration. Without --corpus the fast path answered in 13 to 18 ms (median 17 ms), the bare binary in 18 to 22 ms, and the shell path in 4.2 to 5.2 s (median 4.6 s). With the registration's 224 MB corpus the fast path took a median 4.1 s, the bare binary 3.8 s, and the shell path 7.8 s: the server loads its corpus before it answers, so the issue's acceptance criterion (under a second with that registration) holds for the launcher and not for the registration as written, a ceiling the server sets. A modified tracked file in the launcher's checkout made no measurable difference (7.7 s against 7.8 s). A gate recipe that prints what it sees found the store's GNU Make, Agda 2.9.0, and this checkout's agda/ as $AGDA_DIR through the shell, and /usr/bin/make, no agda, and the client's $AGDA_DIR on the fast path. make agda-mcp-launcher-smoke gains three cases (the fast path from the scratch checkout, with a nix first on PATH that fails if called, and an AGDA_MCP_BIN naming a directory with and without --agda-bin), all three of which fail against the previous launcher while the five earlier cases pass.
Status. Adopted (PRs #95, #104, and #222; the registrations live in claude-tooling); the launcher's anchor by #242, whose acceptance check from a Codex session is #243's field report; the fast path by #249, which a registration takes only once its env block names the server (claude-tooling's four do not yet). Open: #137 ([M5-4]), as in § 5; a server that answers initialize before it loads its corpus, which the fast path's measurement shows is the remaining wait.
12. Where it stands: the field record¶
docs/mcp-field-reports.md holds twelve session reports appended by agents working in ualib/agda-algebras and formal-ledger-specifications; three ran without the server connected and say so. The nine with the server, condensed:
| date | project, task | tools | what was measured |
|---|---|---|---|
| 2026-08-21 | agda-algebras, docstring audit | exports_of ×3, check_file ×2 |
exports_of with module: "" validated a corpus linter against Agda's own scope (15 vs 14, 33 vs 33, 4 plus a nested module); first load ~4 s, a heavy module ~18 s |
| 2026-08-22 | agda-algebras, prose-only pass | check_file ×2 |
checkedFromSource true at 17.8 s, false at 2.3 s; a nine-file sweep was better as a shell loop |
| 2026-08-29 | agda-algebras, FLRP RP-3 (~1200 lines) | check_file ~10 |
warm 7–35 s per call against ~10 min make check; five errors, each diagnosed from one call |
| 2026-08-30 | agda-algebras, IsSimple and a certified A₅ | check_file ~12 |
six new modules green on first check; no profiling lane |
| 2026-08-31 | agda-algebras, simple algebras | check_file ×6 |
2–13 s per call against 20–30 s for nix develop --command agda |
| 2026-09-01 | agda-algebras, Entry 4 no-go | check_file, get_diagnostics, fill_hole |
6–8 s warm against 2–3 min cold make check; fill_hole's UnsolvedConstraints payload found the one real bug; the first session with the server as the primary instrument |
| 2026-09-01 | fls, Leios primitive types | check_file ×6, type_of ×2 |
both subprojects resolved with zero configuration; first literate load ~28–30 s, then 90 ms; top-level type_of sits outside a parameterized module |
| 2026-09-02 | agda-algebras, Kurzweil surjectivity | check_file ~15 |
6–12 s per round against ~40 s cold agda; six errors in a 737-line module, each localized instantly |
| 2026-09-04 | agda-algebras, the Parachute record | check_file ×4 |
every edit green on the first pass (7 s, 24 s); profiling ran in the shell; the one save was the root confirmation |
Two honest patterns run through the record. Hole-driven development was mostly unused, and the reports say that was the right call: when an agent can read the sources into context and design the proof whole, write-then-check wins, and holes pay when goal types are genuinely unknown. And the server's value in these sessions was latency, structured diagnostics, and the project echo, not capability the shell lacks; the shell stayed better for per-file sweeps and for the final whole-library gate. Both patterns are inputs to Milestone 5 and to #17.
The controlled measurement of the same claim¶
(See also #162, #154, #17, and [reports/agent-bench/README.md].)
The field record is a set of sessions in which an agent chose what to do; § 12's second pattern was therefore a reading of behavior rather than a measurement. #162 measures it: the 55-obligation benchmark run three times with Sonnet 5 at one protocol version, one arm per instrument, the same prompts, caps, and judge, with the libraries' own sources readable on every arm and the shell arms confined by an audit over the paths their commands name.
Decision. The field record's honest pattern is adopted as a measured finding, and sharpened by what the control shows.
- The value the record named is confirmed and is the verdict. Given the server and a shell together, the subject took all 55 of its verdicts from
check_fileand ranagdaon the shell not once. Latency and a structured answer are what an agent will not give up, which is § 12's "latency, structured diagnostics, and the project echo" measured rather than inferred. - The rest of the surface is worse than a shell here, not merely reproducible by one. The knowledge tools collapse when a shell is beside them (
definition_of19 calls in the server-only arm and 0 in the both arm,search_by_name18 and 1,exports_of11 and 2,type_of34 and 11), and the server-only arm restates six library lemmas that the shell-only arm proves. - The missing capability is searching sources, not reading them. Both arms could read the libraries; the shell arm consulted them 82 times and the server arm 13, because
grepover a tree needs no prior knowledge of where a thing is whiledefinition_ofanswers where a definition is and not what it says.
Evidence. Runs arm162-shell-1, arm162-mcp-1, arm162-both-1, 2026-09-21, claude-sonnet-5, zero anomalies, USD 12.41: 50 solved and 0 restated on the shell arm, 47 and 6 on the server arm, 51 and 2 on both; 308, 342 and 327 turns. On the agda-algebras rows those counts measure access to the library's text as well as the instrument: the judge's original column (#188) has the restated lemma's own proof in view before the last edit for 15 of the shell arm's 18 solves there, 4 of the server arm's 14, and 16 of the both arm's 19. The full table, the per-tool shift, the two qualifications the isolation gate imposes, and the reproduction of the archived arm are in ADR 0001 § 9 and in [reports/agent-bench/README.md]. Neither shell-bearing arm used agda --interaction-json once, though both prompts name it, and neither grepped its row's corpus, though both prompts give its path. Every subject of those arms had the fixture headers' hints in view (a Strategy: line on every row, the haystack tier's Needle: line). Re-run without them on 2026-09-29 (#219; suite219-sonnet5-shell-1, suite219-sonnet5-mcp-1, suite219-sonnet5-both-1, zero anomalies, the shell prompts now naming the source directories), the shell arm solves 47 and restates 4, the server arm 44 and 9, and both 48 and 5; the both arm again takes all 55 verdicts from check_file and runs agda on the shell never, and the knowledge tools again collapse beside a shell (definition_of 0 calls against 11, search_by_name 4 against 21). The three readings stand; the second's six restatements against none are nine against four header-free (ADR 0001 § 9, "The header-free arms").
Status. Adopted (#162). § 13's ordering is unchanged but its first item is now earned rather than assumed: #17, retrieval as server tools, whose first rung is what a shell does best and this server cannot do at all, searching the library's own sources. The Milestone 5 items that make the verdict cheaper keep their place, since the verdict is what the measurement says the server is for.
13. Where it goes¶
- Milestone 5, AgdaMCP as a daily research instrument, filed from the field record:
profile_file(#134, [M5-1]); many-files-one-call forms ofcheck_fileandexports_of(#135, [M5-2]);fill_holeopt-in apply or a returned patch (#136, [M5-3]; landed as both, § 7); registry hygiene across worktrees (#137, [M5-4]); a reason besidecheckedFromSource(#138, [M5-5]);type_ofinside a parameterized module's scope (#139, [M5-6]); theUnsolvedConstraintsrestatement (#145, [M5-7]); honest degraded hole goals (#146, [M5-8]); and a worked validation-oracle example forexports_of(#147, [M5-9]). - Retrieval as server tools (#17, [M2-3]), whose design map is the forward pointer from § 10.
- The wave's measurement and publication companions: the remaining #83 arms ([M1-7]), the demo page (#85, [M1-8]), and the tool paper (#14, [M1-6]), for which this record is the design summary.
- Recorded and deliberately not taken:
roots/listfor client-relative paths (needs a bidirectional transport);Cmd_abortin place of the lane's kill ladder; streaming progress andsince-narrowing forcheck_project; and the restore variant of #114, until a version gate exists for foreign--agda-bintoolchains. - Agda as a library remains the long-term plan for the batch lane's latency; the interaction lane already delivers persistent state and millisecond warm latency for queries, and nothing in this record depends on the library plan landing.
14. Decision log¶
| # | Decision | Status | Evidence |
|---|---|---|---|
| 1 | Two lanes: a batch process per call for verdicts (agda on the file, or the project's gate for check_project), a persistent --interaction-json child per root for knowledge; the lane never decides a verdict |
Adopted (#75, PR #107) | Interaction mode loads holed files where batch exits 42; 2.6 s per batch call against 1–3 ms per lane query |
| 2 | get_goal answers from the lane first, with injection as the stated fallback and the only path reporting binder visibility |
Adopted (#108, PR #110) | Byte-identical goals on the fixture matrix; no file mutation on the happy path |
| 3 | A batch tool may peek at a warm lane's stored load, never call it; a cold or stale lane leaves the response byte-identical | Adopted (#108, #115) | Enrichment tests pin both shapes |
| 4 | scope_at omitted rather than approximated with grep |
Adopted (#75) | No protocol command enumerates a scope |
| 5 | For the per-file tools, success is a function of the exit code alone; every batch verdict carries verdict, command, project |
Adopted (#72, #76, PR #95); in full on request since #184 (PR #190) | Stand-in binary test; field report § 2 and § 6 |
| 6 | fill_hole tolerates only other open holes' [UnsolvedInteractionMetas] |
Adopted (#69, PR #81) | Verification fixture: ok on content agda rejects with exit 42 |
| 7 | check_project may turn a green gate red on failure evidence, never a red gate green |
Adopted (#78, PR #98) | The wrapper-ending-in-echo trap of § 3.5 |
| 8 | answer = whatAgdaSaid <|> whatWeDerived; the rule lives in the README's architecture notes |
Adopted (#100, #106; PRs #105, #116) | Four module-name shapes; the audit's inventory |
| 9 | Structured diagnostics stay parsed from prose; the protocol retires segmentation, not extraction | Adopted (#106, Measurement 1) | Six-class table: five prose-only, one surplus (#115) |
| 10 | Project resolution stays local, per call, echoed; a wrong tree is a refusal before spawn | Adopted (#76, PR #95); root and rootSource by default, the rest on request, since #184 (PR #190) | No Agda query exists; the environment note's reproduction |
| 11 | Relative paths resolve against the server's cwd, refused by name when they miss, never guessed | Adopted (#101, PR #102) | The #83 -32603 datum; § 3.6's "worse than an error" |
| 12 | Foreign toolchains via --agda-bin and --cwd, agda-algebras included, with the wrapper's registry as --library-file where this repository's registry knows the library; registrations anchored per worktree |
Adopted (#103, #133, PR #222) | fls modules resolve and write interfaces as the project's own agda does; two agda-algebras sessions check their own worktrees side by side |
| 13 | Diagnostics as data: code, range, bounded full message, involved, root-cause order, capped with the total |
Adopted (#74, PR #94) | One fixture per § 5 class; field reports of 2026-08-29 and 2026-09-02 |
| 14 | Holes are Agda's interaction points, in every syntax and flavour, never in prose or comments | Adopted (#71, #73, PR #88) | Parity tests against batch Agda and the lane |
| 15 | Holes addressed by position; every answer re-anchors; both spellings at once rejected | Adopted (#79, PR #99) | ADR 0001 adopts the re-anchored list wholesale |
| 16 | checkedFromSource withheld when the server muted the channel; degrade, not restore |
Adopted (#114, PR #117) | Reproduced in both lanes; grammar measured; the version-gate argument |
| 17 | Timeouts enforced by killing the process group; timeouts are values; defaults 300 s and 1800 s | Adopted (#77, PR #89) | FillTimeout was unreachable; restore pinned on the timeout path |
| 18 | Corpus tools are pure in-memory lookups, registered only with --corpus |
Adopted (#11, PR #44) | 1.4 s load, 308 MB resident at library scale |
| 19 | A hand-rolled stdio transport (initialize, tools/list, tools/call) rather than the mcp-server package |
Adopted; reason revisited | The GHC-floor reason expired; kept because it is small |
| 20 | What every tool shares is stated once, in the initialize instructions; each description carries its own contract, under the 2,048 characters a client reads; --expose presents a subset |
Adopted (#191, PR #193) | Claude Code 2.1.282 cut 11 of 14 descriptions (27,808 characters unseen); the surface fell from 16,230 to 9,217 tokens a turn on Sonnet 5; arms cost 17 to 19 % less; four tools alone read the library instead of searching it and cited less (§ 3) |
| 21 | In a file with one hole, a position on its line or no address reaches it; every get_goal and fill_hole answer names the hole it used and how (addressed) |
Adopted (#201, PR #228) | 86 archived refusals (39 of 234 fill_hole calls, 47 get_goal), all in one-hole files on the hole's line; all resolve on replay (§ 7) |
| 22 | definition_of quotes what each definition says beside where it is: the declaration's source lines, cut by layout (no Agda query answers a declaration's range), verbatim, bounded by maxLines (default 40), naming the range it quotes |
Adopted (#185, PR #229) | 0 calls beside a shell in #162; 14 answers and 16 reads of the named files on #189's hard tier; 87 of the 92 archived sites fit 40 lines (§ 4) |
| 23 | search_by_type matches fragments of the type as a statement writes it (qualifiers and each name's module parameters dropped, read off the corpus); patterns for several at once; shortest first, with written; qualified: true keeps the old match, which the loop asks for |
Adopted (#202, PR #231) | 11 of 23 archived calls answered nothing before, 4 after; #189's cited lemmas found from their statements; load +0.9 s and +2.5 s |
| 24 | search_in_scope's question asked through search_by_name's inScopeAt (same handler, the pattern as the name query); search_in_scope registered and presented only when --expose names it |
Adopted (#203) | Presented in 681 archived sessions, called once, 17 % of every turn's tools/list; 286 sessions asked the question other ways; 17 replays answered by it |
| 25 | auto, Agda's own proof search at a hole, is a lane tool whose answer is a candidate, registered only with --auto and so off the default surface; a place there waits for an agent arm that shows it called and useful |
Adopted (#205) | The surface is an arm's main cost (#191: 9,217 tokens a turn after the trim), and auto's entry would add 3,880 characters a turn to the 23,103 of the default tools/list after decisions 21, 22, and 24 (16.8 %, measured with the suite's corpus fixture; the instructions stay under the client's cap, 2,011 of 2,048 characters with auto and 2,028 with every tool exposed); a tool offered is not a tool used (search_in_scope, 681 archived sessions, one call, #203, decision 24); its measured consumer is the proof-search loop (#206); the tool reproduces the hand-driven measurement row for row, 17 of 55 solved by fill_hole under --safe (§ 2; [agda-mcp/README.md]) |
| 26 | The launcher anchors the server in the directory the client started it in: --cwd defaults to that directory, ${PWD} and ${PWD:-default} are substituted in any argument, nothing else is expanded, and the server refuses a --cwd still holding ${ |
Adopted (#242) | make agda-mcp-launcher-smoke: five launches, four anchored at the client and one refused; four fail against the previous launcher; the refusal test fails against the previous server |
| 27 | When AGDA_MCP_BIN names an executable file and the arguments carry --agda-bin, the launcher runs the server directly, after the same substitution, --cwd default, cd, and cleared LD_LIBRARY_PATH; the server then inherits the client's environment, which every document describing the launcher says; never the default, and never without --agda-bin |
Adopted (#249) | make agda-mcp-launch-time, medians of five: 17 ms against 4.6 s through the shell without a corpus; 4.1 s against 7.8 s with the agda-algebras corpus, whose load (3.8 s on the bare binary) the server finishes before it answers; three smoke cases that fail against the previous launcher |
| 28 | get_goal and type_of print as an editor does, in Simplified, take rewrite for Agda's other display modes, and name the mode in every answer; search_in_scope, resolve_name's recovery, and the proof-search loop stay on Normalised |
Adopted (#248, PR #257) | The #243 field hole: a context of 168 characters against 1,326 (𝑮 : Group α ρ against 528); search_in_scope there gave the same six rows, but Simplified failed two tier-3b tests; the proof-search loop's budget-1 run identical on both servers (41 rows) |
| 29 | A lane is reused only while the stamp of the Agda a spawn would start (--agda-bin's real path, its bytes up to 64 KiB or else its size and mtime, and an optional identity command's output, cached for two seconds) equals the stamp taken before the lane was spawned; otherwise it is restarted under its lock and the answer says restarted; the peek declines a stale lane |
Adopted (#347, PR #349) | Same bytes and new mtimes on three dev-shell entries; 18 to 45 µs a stamp, 15.3 ms a --print-key; seventeen tests, each of seven mutations caught; the formal-ledger-specifications lock moved under a live session (§ 2) |
| 30 | fill_hole restores by default; apply: true keeps a candidate whose status is ok, and patch: true answers the edit that was checked, on every status: the file, the sha256 of its bytes before and after, a range in lines and code-point columns, the same span in bytes, the text there, and the replacement; the candidate is spliced as sent; every in-place write is made only after the file is found to hold the bytes the server read or wrote, in a step that cannot be interrupted, and a file another writer changed is left alone and fails the call; --no-apply refuses the apply |
Adopted (#136, PR #371) | Candidates written back by hand from the 2026-09-01 field report to six in a batch on 2026-10-13; Agda's hole positions equal in four encodings, and the scan's two byte-order-mark defects fixed; a UTF-16 reading of a patch fills the wrong hole unwarned; 51 tests, and 37 deliberate breaks of the server each caught; a call that asks for neither answers byte for byte as before (§ 7) |
References¶
-
Issues:
-
#68 the wave, with verification results and sequencing,
- its children #69, #70, #71, #72, #73, #74, #75, #76, #77, #78, #79;
- the follow-on fixes #100, #101, #103, #106, #108, #114, #115, #133;
- the companions #83 (M1-7), #85 (M1-8), #14 (M1-6);
- the forward pointer #17 (M2-3), #202 (search by type as written), and #203 (its scope-aware tool folded into
search_by_name); - the
autotool #205 (M5-18) and its use in the loop #206; - the launcher's anchor #242 (M5-22), and the field report that checks it from Codex and Copilot, #243;
- the display mode of
get_goalandtype_of, #248 (M5-24), filed from #243 and part of #235; - the launcher's fast path #249 (M5-25);
- the launcher keyed by the lock, #342 (PR #344), and the lane restarted when its Agda changes, #347 (M5-32);
- Milestone 5, #134, #135, #136, #137, #138, #139, #145, #146, #147, #185, #201;
fill_hole's apply and patch, #136 (M5-3): the two tools whose answers will be patches of its shape, #207 and #209; what it left open, #369 (M5-33) and #370 (M5-34); the tool annotations it bears on, #253; and agda-native-ide's Emacs tools, ide#71;-
PRs: #38 (M1-2), #44 (M1-3), #67 (#66), #80 (the field report), #81 (#69), #82 (#70), #88 (#71, #73), #89 (#77), #94 (#74), #95 (#72, #76), #98 (#78), #99 (#79), #102 (#101), #104 (#103), #105 (#100), #107 (#75), #110 (#108), #116 (#106), #117 (#114), #118 (#115), #228 (#201), #229 (#185), #257 (#248), #371 (#136).
-
Docs:
-
[
agda-mcp/agda-mcp-interaction-lane.md] the two-lane policy, the protocol as observed, lifecycle, economics, - [
agda-mcp/agda-mcp-ask-agda-audit.md] the rule, the inventory, two measurements, - [
agda-mcp/agda-mcp-environment.md] what is written where, which tree is checked, the operator checklist, - [
agda-mcp/agda-mcp-improvements-summary.md] the wave, fix by fix, with PR numbers, - [
agda-mcp/README.md] the tool contracts and response-field tables, - [
feedback/flrp-agda-mcp-improvements.md] the field report and its verification addendum, - [
feedback/agent-case-for-corpus-proof-search.md] the consumer-side case, - [
mcp-field-reports.md] the session record, - [
adr/0001-proof-search-on-agda-mcp.md] the search built on this server, -
ide ADR 0003 agda-native-ide's record of the same questions: the basis of an answer, and how Agda counts.
-
Code map (
agda-mcp/src/AgdaMCP/): -
Agda.hs: the batch subprocess, the kill ladder,checkedFromSourceOf,progressChannelMuted, Interaction.hs: the lane registry and runner,Project.hs: root resolution, the registry, the mismatch refusal,Holes.hs: the hole model and the code-only view,Patch.hs,Digest.hs: a text edit as a client applies it, and the digest that names its texts,Diagnostics.hs: prose to structured diagnostics,Gate.hs: which command is the gate,Corpus.hs: the index,Tools/ProofState.hs,Tools/CheckProject.hs,Tools/LiveQueries.hs,Tools/Search.hs,Server.hs: the transport,agda-mcp/test/Main.hs: tests,agda-mcp/test/resources/: fixtures,scripts/run-server.sh(at the repository root): the launcher, which anchors the shell here and the server where the client started it, and runs a prebuilt server without the shell when the registration names it and its Agda;scripts/run-server-smoke.shis its smoke, andscripts/python/launch_to_ready.py(make agda-mcp-launch-time) times it.