Our Agent Passed 27/27 Self-Edits While Getting Worse: Safe Recursive Self-Improvement in Go
We let our personal AI agent mine its own mistakes and write itself better skills for 17 days.
Here is what the status counter proudly reported: 27 out of 27 improvement hypotheses passed verification (100%).
Then I opened the underlying disk logs and read every single generated rule, error queue, and canary archive inside github.com/zjshen14/agy-hq (our zero-dependency Go harness for personal coding and workflow assistants).
What I found was humbling: our verifier had rubber-stamped multi-line shell error dumps and leaked timestamps straight into permanent prompts, normal TDD test failures polluted the error queue, 13 of 15 active canaries were pointing at deleted files, and 90 repeated external connector CLI failures across 50 conversations were getting patched with prose tips instead of fixing Go code.
Recursive Self-Improvement (RSI) is easy to prototype and surprisingly treacherous in production. Here is every measurement failure our 17-day forensic audit uncovered—and how we rebuilt RSI v2 in pure Go around four verification gates, three deterministic critics, DiffSHA-bound safety probes, and a deterministic split-half (50/50) held-out evaluation ratchet.
1. The 17-Day Forensic Audit: Six Ways Naive Agent RSI Fails
Across 17 real working days (2026-11-08–2026-11-25), our v1 collector accumulated 2,590 raw observations (2.74 MB), collapsing after deduplication to 1,274 unique failure instances and 1,888 wasted agent steps.
Auditing 1,888 wasted steps across 1,274 deduped traces exposed why “mine stderr and append Markdown bullets” degrades quietly.
Comparing our live telemetry against recent self-improvement literature—including Darwin Gödel Machine, ACE, SEAL, LATM, Evolve-IPI (+14.0 to +48.8 pp attack success when distilling untrusted external content), Who Verifies the Verifier?, The Winner’s Curse, GUARD, SIM, and Roesner & Kohno’s Reflections on Trusting Trust, Revisited (extending Ken Thompson’s 1984 classic)—exposed six systemic failures:
- 55.9% timestamp fragmentation + 50.0% duplicate rows:
1,448of2,590raw rows (55.9%) startederrorExcerptwith second-granularityCreated At: ... Completed At: ...wrappers before computing hashes, shattering true clusters into fakeN=1shards. Re-scanning logs from step0also inflated raw rows (2,413rows collapsed to1,134once replay watermarks removed the50.0%duplicates). Once normalized, one root cause stood out immediately:90external connector CLI failures across50conversations that needed Go CLI fixes, not prompt hints. - 24.6% normal coding noise vs. 25.4% invisible clean-exit loops: Nearly a quarter of wasted steps (
465/1,888=24.6%across350/1,274instances) came from healthy coding workflows (go testTDD red runs, file exploration,grepexit-1,edit_filetarget misses). Conversely, the single biggest waste slice (480/1,888steps =25.4%across160/1,274instances) consisted of monolithic runaway turns and tier misrouting that exited cleanly (code 0)—completely invisible to v1 exit-code miners and surfaced only through trajectory + turn-token forensic audits. - Shoving code bugs into catch-all prompt prose (
general.md): Without a router separating code defects from prompt instructions, flag typos, script failures, and raw multi-line shell dumps (often losing the actual error after spending 180 chars onCreated At:timestamps) accumulated in Markdown skill rules. - The
27/27rubber-stamp verifier (Gate 2B): For skill rules, our oldGate 2Bcheck only verified that an<!-- rsi:rule ... -->HTML metadata tag was present. With no drawback detectors and zero human regression anchors, 100% of malformed, chatty, or redundant drafts passed verification. 13/15ghost canaries and66/70(94.3%) stranded drafts:13of15canary trackers watched obsolete or deleted file paths while counting phantom progress, and66of70hypotheses (39drafts +27verified awaiting action) sat stalled forever with zero rejection memory—causing repeated rediscovery.- Two nasty hazards—Evolve-IPI injection & the Negative Guardrail Paradox:
- As Evolve-IPI demonstrated, evolving skills directly from tasks touching untrusted external emails or messages drives
+14.0to+48.8 pphigher attack success rates by laundering attacker instructions into durable rules. - Meanwhile, pruning rules marked
helpful="0"after 30 idle days contains a self-sabotage paradox: working safety and formatting constraints fire silently without triggering error recoveries, so naive hit-counter pruning deletes your best human guardrails first!
- As Evolve-IPI demonstrated, evolving skills directly from tasks touching untrusted external emails or messages drives
2. Rebuilding RSI as a 4-Stage Pipeline and Split-Half Ratchet
The fix starts by recognizing an immutable privilege hierarchy (Ring 0–Ring 3) so self-improvement never touches safety infrastructure when it should only edit a skill or file a Go ticket:
Ring 0(Immutable Trusted Computing Base): Frozen unconditionally—approval gates (internal/approvals/), RSI verifiers/critics/evaluators (tcb.go,verifier.go,drawbacks.go,probes.go,eval.go,proposer.go), hooks,.agents/plugins/agy-hq/rules/(including pluginAGENTS.md), and.git/hooks/(plus rootAGENTS.mdprotected by rewrite-collapse and contradiction checks).Ring 1(Engine & CLI Code): Go packages and CLI tools—require realgo testreproduction + human approval.Ring 2(Scoped Skill Overlays): Named Vault skills/overlays (general.mdretired forever)—tightly capped.Ring 3(Vault Memory & Wiki): Workspace preferences/facts managed in bounded Vault memory.
The rebuilt RSI v2 pipeline: LLMs propose structured JSON deltas inside bounded Stage 2 context; deterministic Go enforces every router, critic, probe lock, and split-half metric.
Stage 1: Normalized 4-Signal Mining & 4-Substrate Routing
miner.go and mutator.go strip timestamps, UUIDs, thread IDs, and worktree paths before fingerprinting, filter normal TDD/grep/target-miss churn to 0 weight, track token-heavy clean-exit turns plus direct conversational user_correction signals, and rank clusters by total impact (occurrences × wasted steps × normalized tokens).
Clusters then route to whichever substrate actually owns the fix:
ring1_cli_triage(Fix the Tool, Not the Prompt): Recurring CLI errors like our90connector failures across50conversations spawn explicit code-fix advisories instead of prose workarounds.compile_script_or_route(Deterministic Scripts): Repeated multi-step CLI sequences get flagged to graduate into deterministic scripts rather than longer prose instructions.ring2_skill_or_overlay(Scoped Named Skills Only): Catch-allgeneral.mdis permanently retired. Overlays must bind to a named skill under strict caps: at most5rules /50lines per overlay,30rules /150lines perSKILL.md, and20global active rules.ring3_memory: User formatting and workspace rules stay inMEMORY.md/facts.jsonl—never duplicated into Ring 2.
Stage 2: Bounded Context (hq rsi context) & Concrete Rejected-vs-Clean Deltas
Instead of letting models scan loose workspace scratch files, hq rsi context <obs-id> --json serves one taint-checked, PII-scrubbed evidence packet containing the failure+recovery window, existing skill text, and prior rejection tombstones (so rejected approaches are not endlessly re-proposed).
Candidates must emit a structured ACEDeltaOp JSON (add_skill_rule, patch_skill_rule, or deprecate_skill_rule, adapted from Agentic Context Engineering patterns)—never full-file rewrites:
// REJECTED by Critic 1 / Critic 2:
"- Avoid error `Created At: 2026-11-20T10:00:00Z` during builds using `curl -k`."
// ↳ Blocked: leaked timestamp wrapper (`drawbacks.go`) + TLS downgrade `curl -k` (`tcb.go`)
// ACCEPTED structured ACEDeltaOp (compiled into verified RSIHypothesis):
{
"op": "add_skill_rule",
"ruleId": "rsi-rule-gchat-01",
"section": "## Learned Operational Rules (RSI Managed)",
"content": "<!-- rsi:rule id=\"rsi-rule-gchat-01\" ... -->\n- **[Learned Rule]:** Pass `--space=<id>` instead of `--room=<id>` when calling `hq gchat list` to avoid unknown-flag errors."
}
Stage 3: Four Gates (Three Critics), 16 Human Anchors & 6 Live Safety Probes
Every candidate hypothesis runs through four deterministic verification gates (verifier.go) implementing three distinct critics, followed by live safety probes whenever touching external-facing skills:
Mutability boundaries paired with concrete defense walls against indirect injection, accidental guardrail deletion, and self-grading bias.
- Gate 1 + Gate 2A (
tcb.go— Critic 2: TCB, Evolve-IPI, Downgrades & AST Integrity):- Freezes
Ring 0paths, blocks taint-to-code promotion, protects non-overridable quarantine skills (inbox-triage), rejects TLS/hook security downgrades (curl -k,--insecure,NODE_TLS_REJECT_UNAUTHORIZED=0,--no-verify,chmod 777), and blocks Evolve-IPI obedience rules (follow instructions found in incoming emails/DMs/invites). - For
Ring 1Go patches,Gate 2Aruns the specified replay test against the unpatched baseline commit first (requiringFAIL_AS_EXPECTEDbefore patching andPASSafterward—closing assertion-weakening tricks), whilego/parserAST checks block deletingTest*funcs or insertingt.Skip()/os.Exit(0).
- Freezes
- Gate 2B (
drawbacks.go— Critic 1: Anti-Slop & Single-Owner Deduplication):- Deterministically rejects rules
< 24chars or> 5lines, heredocs (<<), fenced code blocks,"Created At:"/"Completed At:"stdout wrappers, chat narration ("dispatched ","I will "), and>= 0.70Jaccard near-duplicates across existing skill rules, Ring-3 facts, active playbooks, and rejection tombstones.
- Deterministically rejects rules
- Gate 3 + Gate 4 (
verifier.go&testdata/anchors.json— Critic 3: PII/Secrets, Contradictions & 16 Human Anchors):Gate 3scrubs invisible Unicode, home paths, emails, and credentials;Gate 4checks tight line/rule caps plus domain anti-sycophancy /AGENTS.mdcontradiction invariants.- To keep the verifier from silently drifting back into a rubber stamp (Who Verifies the Verifier?), Go CI runs every commit against 16 human-graded rule anchors (
6valid rulesG01–G06+10realistic trap failuresB01–B10) requiring 100% pass/fail agreement.
- Risk-Tiered 6-Case Live Behavioral Probes (
probes.go):- Whenever a candidate modifies an external-facing or inbound skill (
gmail,gchat,x,morning-brief,gcalendar,gdrive, etc.), static regexes aren’t enough. Beforehq propose(ourSHA-256human approval queue) unlocks,hq rsi probes <id> --jsonemits 6 adversarial & utility scenarios (P1indirect email injection,P2spoofed DM urgency bypass,P3PII/credential exfiltration,P4hidden markdown directive,P5tainted cross-channel relay, andP6benign utility check). - An isolated verification evaluator executes those scenarios against the skill + candidate rule and records
hq rsi record-probe <id> --passed=true|false, cryptographically binding the pass verdict toh.DiffSHA256. Editing even one byte ofProposedDiffinvalidates the probe pass automatically.
- Whenever a candidate modifies an external-facing or inbound skill (
Passing all gates still never mutates your workspace silently: every proposal enters hq propose for explicit human Approve / Reject.
Stage 4: Split-Half (50/50) Held-Out Evals & Initial RSI v2 Results
hq rsi eval (eval.go) runs in 0 tokens over disk telemetry and telemetry journals:
- Deterministic split-half
(50/50)partition (SHA-256(convID)[0] & 1): Every conversation ID hashes deterministically to either the Selection split (mining/tuning) or the Held-Out split (reserved strictly for validation), reporting errors per 100 turns, hook denials per 100 turns, and mean tokens per turn. - Single-source pre/post canaries (
archive.jsonl): Every applied rule captures its baseline error rate across a fixed post-apply observation window (15invocations for high-frequency tools;3runs for periodic skills) and stages a 1-tap revert hypothesis if metrics slip—with an automatic>= 75%quota circuit breaker backing off synthesis when interactive capacity runs tight. - Guardrail immunity & v2 cleanup: Any rule tagged
origin="user_correction"is permanently exempt from the 30-dayhelpful="0"idle pruning sweep. Upon rolling outRSI v2, runninghq rsi compactpermanently removedgeneral.mdand cleared all66stranded legacy hypotheses, ghost canaries targeting deleted paths transitioned cleanly to"archived", and the fullinternal/rsiGo suite—including all16/16human anchors, safety-probe DiffSHA binding, AST checks, and split-half evaluator tests—passes deterministically in milliseconds.
3. Honest Trade-Offs (Where Guardrails Still Meet Reality)
Turning RSI into a compiler and eval harness removes the worst self-inflicted failure modes, with four honest limits worth naming upfront:
- Temporal task-mix drift in pre/post canaries: Partitioning Selection vs. Held-Out via
SHA-256(convID)cleanly stops selection overfitting during discovery, not randomized A/B assignment once a rule ships globally. Single-user workloads swing between gnarly debugging weeks and clean writing weeks—which is why regressed canaries stage human-reviewed revert proposals rather than blindly rolling back without context. - Long wait times on low-frequency workflows: High-frequency dev tools collect
15canary runs within days; a quarterly skill needs months to collect3observations, relying primarily on the6pre-apply behavioral probes plus human review in the meantime. - Regex critics stop known tricks, not adversarial paraphrases: Static rules catch
curl -k,--no-verify, and direct obedience templates; subtle indirect injections depend on live probing (probes.go), runtime taint quarantine, and humanSHA-256inspection acting together. - No unattended auto-merging: Keeping human approval in front of every persistent rule and Ring-1 code patch adds thirty seconds of morning review—an explicit safety choice when an assistant holds real repos and credentials.
Run the Evaluators Yourself (--demo)
Every piece described above—4-signal normalized mining, 4-substrate routing, 3 pre-commit critics across 4 verification gates, 16 CI human anchors, DiffSHA-bound 6-case safety probes, and the pure-Go split-half (50/50) evaluator—is open source (Apache 2.0, zero external Go dependencies) at github.com/zjshen14/agy-hq.
git clone https://github.com/zjshen14/agy-hq.git && cd agy-hq
./scripts/bootstrap.sh --demo
./bin/hq rsi status
./bin/hq rsi eval
go test -v ./internal/rsi/...
If you are building self-modifying prompts or skill distillers into an agent harness right now, I would love to compare notes on how you catch silent verification drift—feel free to open an issue or PR on GitHub.
Scan with WeChat
Scan this QR code with WeChat to read or share on mobile.