Building an Autonomous LLM Coding Harness
Artificial intelligence coding agents have emerged as one of the most transformative applications of large language models. Rather than operating as static question-answering systems, modern coding agents act autonomously: they inspect a codebase, search for relevant definitions, inspect existing tests, propose structured file modifications, run verification checks, and iterate until a task is solved.
Yet building a reliable autonomous coding assistant reveals several critical engineering challenges:
- Unconstrained Writes and Code Regression: A model left to overwrite files without human oversight can silently delete existing logic or introduce subtle regressions.
- The Delimiter Counting Blind Spot: Neural language models process text as discrete tokens rather than nested syntax trees. When a model introduces an unclosed parenthesis or bracket, the compiler often emits an unhelpful diagnostic with zero location information (for example,
Incomplete form, EOF reached). If you feed this error back to the model, it typically rewrites the entire file from scratch, shifting the parenthesis imbalance somewhere else. - Execution Safety and Sandboxing: A model generating code must be able to run tests and evaluate expressions, but it must not execute arbitrary shell commands that could compromise the host environment.
In this chapter, we construct a complete, multi-language coding agent in Gerbil Scheme called Coding Harness. The harness implements an interactive tool-calling loop, generates colored unified diffs for every proposed edit, intercepts compiler errors with an automated delimiter scanner, and prompts the developer to fix bracket mistakes directly in their editor.
The Architecture of an Agentic Harness
An effective coding agent is organized as a stateful loop coordinating four specialized layers:
1 ┌─────────────────────────────────────────────────────────────┐
2 │ User Objective │
3 └──────────────────────────────┬──────────────────────────────┘
4 │
5 ▼
6 ┌─────────────────────────────────────────────────────────────┐
7 │ LLM Tool-Calling Loop (llm.ss) │
8 │ │
9 │ • Multi-turn conversation context │
10 │ • OpenAI-compatible Chat Completions API │
11 │ • Function calling & tool dispatch │
12 └──────────────┬──────────────────────────────▲───────────────┘
13 │ │
14 Tool Invocations Tool Results
15 │ │
16 ▼ │
17 ┌─────────────────────────────────────────────────────────────┐
18 │ Tool Registry (tools.ss) │
19 │ │
20 │ • read_file, list_dir, grep, outline_file, find_definition│
21 │ • eval_code (sandboxed REPL execution) │
22 │ • run_shell (whitelisted commands) │
23 │ • propose_edit (staged file modification) │
24 └──────────────┬──────────────────────────────▲───────────────┘
25 │ │
26 Staged Edit Check Status
27 │ │
28 ▼ │
29 ┌─────────────────────────────────────────────────────────────┐
30 │ Approval & Verification Gate │
31 │ │
32 │ 1. approval.ss: Display colored diff & request approval │
33 │ 2. checker.ss: Run build/test verification │
34 │ 3. parens.ss: Scan delimiters on syntax errors │
35 └─────────────────────────────────────────────────────────────┘
Why Syntax Errors Go to the User
When a compiler cannot parse a file due to an unclosed delimiter, it usually cannot identify which opening bracket lacked a matching closer. In Gerbil, the compiler simply says:
1 --- Syntax Error at read-module: error reading module
2 ... detail: "Incomplete form, EOF reached\n"
Because language models lack a mechanical stack, handing this message back to the model rarely works. The model guesses where the missing parenthesis goes, rewrites dozens of lines, and frequently creates a new imbalance.
The Coding Harness inverts this dynamic. When make check fails, the harness runs a lexical delimiter scanner (parens.ss). The scanner tracks every opening and closing delimiter while respecting string literals, block comments, and escape codes. It pinpoints the exact line and column of the unclosed delimiter, prints an excerpt of the code with a visual pointer, and pauses to let the user fix the file in their editor. Once the developer saves the file and presses Enter, the harness re-runs the check and resumes the agent.
The Delimiter Scanner (parens.ss)
The module parens.ss implements lexical token scanners for four distinct language families:
lisp: Handles Scheme and Gerbil strings, vertical-bar symbols, line comments (;), nested block comments (#| ... |#), and here-strings (#<<).python: Handles hash comments (#), single quotes, double quotes, and triple-quoted multiline strings.haskell: Handles line comments (--), nested block comments ({- ... -}), and character literals.c-like: Handles line comments (//), block comments (/* ... */), single quotes, double quotes, template literals (`...`), and regular expression literals (/.../).
Here are the key scanning and diagnostic reporting procedures from parens.ss:
1 ;; File: parens.ss (excerpts)
2 ;; Lexical delimiter scanner that reports unbalanced (), [], and {}
3
4 (import :std/sugar
5 :std/format
6 :std/srfi/13)
7
8 (export scan-parens
9 scan-delimiters
10 parens-ok?
11 format-paren-report
12 source-excerpt)
13
14 (defstruct paren-problem
15 (kind line col message closer opener-line opener-col))
16
17 (defstruct paren-report
18 (ok? problems hints forms))
19
20 ;; Scan TEXT using LEXICON rules ('lisp, 'python, 'haskell, or 'c-like)
21 (def (scan-delimiters text (lexicon 'lisp))
22 (let ((stack '()) ;; stack of (char line col)
23 (problems '())
24 (hints '())
25 (line 1)
26 (col 1)
27 (len (string-length text)))
28 (let loop ((i 0))
29 (if (>= i len)
30 ;; Reached EOF: check if any opening delimiters remain on stack
31 (begin
32 (for-each
33 (lambda (entry)
34 (let ((ch (car entry))
35 (l (cadr entry))
36 (c (caddr entry)))
37 (set! problems
38 (cons (make-paren-problem
39 'unclosed l c
40 (format "'~a' opened at line ~a, col ~a is never closed (EOF reached)"
41 ch l c)
42 #f l c)
43 problems))))
44 stack)
45 (make-paren-report (null? problems) (reverse problems) hints '()))
46 (let ((ch (string-ref text i)))
47 (cond
48 ;; Opening delimiters: push onto stack
49 ((memv ch '(#\( #\[ #\{))
50 (set! stack (cons (list ch line col) stack))
51 (advance-and-loop (+ i 1) ch line col))
52 ;; Closing delimiters: verify matching opener
53 ((memv ch '(#\) #\] #\}))
54 (if (null? stack)
55 (begin
56 (set! problems
57 (cons (make-paren-problem
58 'unexpected-close line col
59 (format "Unexpected closing '~a' with no matching opener" ch)
60 ch line col)
61 problems))
62 (advance-and-loop (+ i 1) ch line col))
63 (let* ((top (car stack))
64 (open-ch (car top))
65 (open-l (cadr top))
66 (open-c (caddr top)))
67 (set! stack (cdr stack))
68 (unless (matching-pair? open-ch ch)
69 (set! problems
70 (cons (make-paren-problem
71 'mismatch line col
72 (format "Mismatched closing '~a' for '~a' opened at line ~a, col ~a"
73 ch open-ch open-l open-c)
74 ch open-l open-c)
75 problems)))
76 (advance-and-loop (+ i 1) ch line col))))
77 ;; Newlines: increment line counter, reset column
78 ((char=? ch #\newline)
79 (set! line (+ line 1))
80 (set! col 1)
81 (loop (+ i 1)))
82 (else
83 (set! col (+ col 1))
84 (loop (+ i 1)))))))))
When a syntax error occurs, format-paren-report extracts the source text around the problem line and prints a pointer directly below the offending column.
Generating Unified Diffs and Human Approval (approval.ss)
The module approval.ss ensures that no proposed modification is applied to disk without explicit review. It calculates unified diffs, renders additions in green and deletions in red, and prompts the user for action:
1 ;; File: approval.ss (excerpts)
2 ;; Colored unified diff generation and interactive user approval
3
4 (import :std/sugar
5 :std/format
6 "util")
7
8 (export ask-approval
9 render-diff)
10
11 ;; Prompt the developer to approve, reject, or inspect a proposed edit
12 (def (ask-approval path old-content new-content)
13 (let ((diff (render-diff path old-content new-content)))
14 (displayln diff)
15 (let loop ()
16 (display "Approve this edit? [y]es, [n]o, [d]iff, [a]bort: ")
17 (flush-output-port)
18 (let ((reply (read-line)))
19 (cond
20 ((eof-object? reply) 'abort)
21 ((member reply '("y" "yes" "Y")) 'approve)
22 ((member reply '("n" "no" "N")) 'reject)
23 ((member reply '("a" "abort" "A")) 'abort)
24 ((member reply '("d" "diff" "D"))
25 (displayln diff)
26 (loop))
27 (else
28 (displayln "Please enter 'y', 'n', 'd', or 'a'.")
29 (loop)))))))
This gate gives the developer total control over file mutations. If an edit introduces unwanted changes or alters unrelated files, the user enters n to reject it. The harness returns an explanation to the model so it can formulate an alternative approach.
The Verification Gate (checker.ss)
After an approved edit is written to disk, checker.ss executes the project’s build and test command (make check by default). If the check succeeds, control returns to the model. If the check fails, the harness analyzes the compiler output:
1 ;; File: checker.ss (excerpts)
2 ;; The make check gate and user-repair loop
3
4 (import :std/sugar
5 :std/format
6 "util"
7 "parens"
8 "approval")
9
10 (export run-check
11 check-with-user-fix)
12
13 (def (check-with-user-fix edited-files)
14 (let-values (((output exit-code label) (run-check edited-files)))
15 (if (zero? exit-code)
16 (values #t output)
17 ;; Check failed: inspect edited files for delimiter problems
18 (let ((delims-failed #f))
19 (for-each
20 (lambda (file)
21 (when (file-exists? file)
22 (let ((rep (scan-delimiters (read-file-string file))))
23 (unless (paren-report-ok? rep)
24 (set! delims-failed #t)
25 (displayln "\n━━ SYNTAX ERROR: Unbalanced Delimiters Detected ━━")
26 (displayln (format-paren-report file rep))))))
27 edited-files)
28 (if delims-failed
29 (prompt-user-to-repair edited-files)
30 (values #f output))))))
31
32 (def (prompt-user-to-repair edited-files)
33 (displayln "\nPlease fix this syntax error in your editor.")
34 (displayln " [Enter] I fixed it: re-run the check")
35 (displayln " r Revert this edit")
36 (displayln " m Let the model try to fix it")
37 (displayln " a Abort this task")
38 (let loop ()
39 (display "fix> ")
40 (flush-output-port)
41 (let ((line (read-line)))
42 (cond
43 ((or (eof-object? line) (string=? line "a"))
44 (values #f "User aborted task."))
45 ((string=? line "r")
46 'revert)
47 ((string=? line "m")
48 (values #f "Compiler syntax error: please repair."))
49 (else
50 ;; Re-run check after manual user fix
51 (check-with-user-fix edited-files))))))
This interaction eliminates the loops where models repeatedly fail on bracket closures. The developer fixes the delimiter with their editor’s parenthesis matching in seconds, presses Enter, and the harness continues without losing context.
Running the Coding Harness
The harness is executed directly from the terminal inside any project directory:
1 $ gerbil-harness "Add a helper function to format negative currency amounts"
2 Detected project language: gerbil (via gerbil.pkg)
3 Loaded 9 tools into agent registry.
4
5 === Plan ===
6 1. Read source_code/currency.ss to understand existing formatting helpers.
7 2. Propose edit adding format-negative-currency with tests.
8 3. Run make check to verify.
9
10 [Tool: read_file path: "currency.ss"]
11 Read 42 lines.
12
13 [Tool: propose_edit path: "currency.ss"]
14 --- currency.ss
15 +++ currency.ss
16 @@ -14,6 +14,11 @@
17 (def (format-currency amount)
18 (format "$~a" (fixed amount 2)))
19 +
20 +(def (format-negative-currency amount)
21 + (if (< amount 0)
22 + (format "($~a)" (fixed (abs amount) 2))
23 + (format-currency amount)))
24
25 Approve this edit? [y]es, [n]o, [d]iff, [a]bort: y
26 [Applied edit to currency.ss]
27
28 ==> Running make check...
29 ✓ Check PASSED (all tests OK).
30
31 Task complete. The new helper format-negative-currency is implemented and passing tests.
Now let us observe what happens when a model proposes an edit containing an unbalanced delimiter:
1 [Tool: propose_edit path: "util.ss"]
2 --- util.ss
3 +++ util.ss
4 @@ -3,4 +3,5 @@
5 (def (add1* x) (+ x 1))
6 +(def (add2 x)
7 + (let ((y (add1* x)))
8 + (+ y 1))
9
10 Approve this edit? [y]es, [n]o, [d]iff, [a]bort: y
11 [Applied edit to util.ss]
12
13 ==> Running make check...
14
15 ━━ SYNTAX ERROR: Unbalanced Delimiters Detected ━━
16 util.ss: UNBALANCED DELIMITERS
17
18 * '(' opened at line 4, col 1 is never closed (EOF reached)
19 3| (def (add1* x) (+ x 1))
20 4| (def (add2 x)
21 ^
22 5| (let ((y (add1* x)))
23 6| (+ y 1))
24
25 hint: missing 1 closing delimiter ')' at end of form.
26
27 Please fix this syntax error in your editor.
28 [Enter] I fixed it: re-run the check
29 r Revert this edit
30 m Let the model try to fix it
31 a Abort this task
32 fix>
After appending the missing ) in your editor and pressing Enter, the harness detects the clean check and proceeds smoothly:
1 ==> Running make check...
2 ✓ Check PASSED.
3 Resuming agent workflow.
Interpreting the Results
The interaction highlights three critical architectural advantages:
- Human Oversight of Mutations: By surfacing proposed modifications as unified diffs before disk writes, developers prevent unauthorized deletions, hallucinated library dependencies, or out-of-scope edits.
- Deterministic Bracket Correction: Language models struggle with character-level delimiter balancing. By transferring reader errors to the user alongside visual line and column excerpts, the harness eliminates the primary failure mode of automated coding assistants.
- Multi-Language Adaptability: Because the delimiter lexicons and syntax error rules are separated into language profiles (
lang.ss), the exact same harness operates across Gerbil, Python, Haskell, TypeScript, and JavaScript projects.
Wrap Up
In this chapter we built Coding Harness, an autonomous agentic pair-programming assistant in Gerbil Scheme. By combining multi-turn tool calling, colored unified diff approval, automated build verification, and a dedicated delimiter scanner, the system bridges the gap between language model generation and software engineering rigor.
Optional Practice Problems
- Automated Rollback on Abort: Extend
approval.ssto maintain an in-memory backup of every file touched during a session, automatically reverting all disk mutations if the user selectsabort. - Context Compaction: Implement a
/compactcommand inllm.ssthat summarizes earlier turns in the conversation history when token consumption exceeds 80% of the model’s context window. - AST Definition Finder: Extend
outline_fileintools.ssto use Gerbil’s macro expander (gxc -S) to report fully qualified export lists and macro definitions in addition to top-leveldefforms.