DevLog
← Back to Blog

Our Agent Passed 27/27 Self-Edits While Getting Worse: Safe Recursive Self-Improvement in Go

By • 11 min read
This article is also available in Chinese: 🌐 阅读中文版 →

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.

Breakdown of 1,888 wasted steps across 1,274 deduped observations (24.6% normal TDD/grep/miss noise, 25.4% clean-exit runaway token loops, 20.4% connector CLI bugs including 90 fails across 50 convs), alongside 27/27 naive verifier false passes, 13/15 ghost canaries, 66/70 stranded drafts, and Evolve-IPI (+14-49 pp ASR).

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:

  1. 55.9% timestamp fragmentation + 50.0% duplicate rows: 1,448 of 2,590 raw rows (55.9%) started errorExcerpt with second-granularity Created At: ... Completed At: ... wrappers before computing hashes, shattering true clusters into fake N=1 shards. Re-scanning logs from step 0 also inflated raw rows (2,413 rows collapsed to 1,134 once replay watermarks removed the 50.0% duplicates). Once normalized, one root cause stood out immediately: 90 external connector CLI failures across 50 conversations that needed Go CLI fixes, not prompt hints.
  2. 24.6% normal coding noise vs. 25.4% invisible clean-exit loops: Nearly a quarter of wasted steps (465/1,888 = 24.6% across 350/1,274 instances) came from healthy coding workflows (go test TDD red runs, file exploration, grep exit-1, edit_file target misses). Conversely, the single biggest waste slice (480/1,888 steps = 25.4% across 160/1,274 instances) 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.
  3. 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 on Created At: timestamps) accumulated in Markdown skill rules.
  4. The 27/27 rubber-stamp verifier (Gate 2B): For skill rules, our old Gate 2B check 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.
  5. 13/15 ghost canaries and 66/70 (94.3%) stranded drafts: 13 of 15 canary trackers watched obsolete or deleted file paths while counting phantom progress, and 66 of 70 hypotheses (39 drafts + 27 verified awaiting action) sat stalled forever with zero rejection memory—causing repeated rediscovery.
  6. 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.0 to +48.8 pp higher 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!

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 plugin AGENTS.md), and .git/hooks/ (plus root AGENTS.md protected by rewrite-collapse and contradiction checks).
  • Ring 1 (Engine & CLI Code): Go packages and CLI tools—require real go test reproduction + human approval.
  • Ring 2 (Scoped Skill Overlays): Named Vault skills/overlays (general.md retired forever)—tightly capped.
  • Ring 3 (Vault Memory & Wiki): Workspace preferences/facts managed in bounded Vault memory.

RSI v2 4-stage pipeline: Stage 1 4-signal normalized miner routing across 4 substrates; Stage 2 bounded untainted context + structured ACEDeltaOp; Stage 3 4 verification gates enforcing 3 critics, 16 human CI anchors & 6 DiffSHA safety probes; Stage 4 split-half (50/50) eval, pre/post canaries, and 30-day user_correction guardrail immunity.

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:

  1. ring1_cli_triage (Fix the Tool, Not the Prompt): Recurring CLI errors like our 90 connector failures across 50 conversations spawn explicit code-fix advisories instead of prose workarounds.
  2. compile_script_or_route (Deterministic Scripts): Repeated multi-step CLI sequences get flagged to graduate into deterministic scripts rather than longer prose instructions.
  3. ring2_skill_or_overlay (Scoped Named Skills Only): Catch-all general.md is permanently retired. Overlays must bind to a named skill under strict caps: at most 5 rules / 50 lines per overlay, 30 rules / 150 lines per SKILL.md, and 20 global active rules.
  4. ring3_memory: User formatting and workspace rules stay in MEMORY.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:

Four-ring mutability lattice (Ring 0 through Ring 3) paired with three immunity walls: Trusting Trust / Evolve-IPI blocking, Negative Guardrail Paradox immunity (user_correction exemption + rejection tombstones), and split-half held-out + pre/post canary ratchets.

Mutability boundaries paired with concrete defense walls against indirect injection, accidental guardrail deletion, and self-grading bias.

  1. Gate 1 + Gate 2A (tcb.go — Critic 2: TCB, Evolve-IPI, Downgrades & AST Integrity):
    • Freezes Ring 0 paths, 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 1 Go patches, Gate 2A runs the specified replay test against the unpatched baseline commit first (requiring FAIL_AS_EXPECTED before patching and PASS afterward—closing assertion-weakening tricks), while go/parser AST checks block deleting Test* funcs or inserting t.Skip() / os.Exit(0).
  2. Gate 2B (drawbacks.go — Critic 1: Anti-Slop & Single-Owner Deduplication):
    • Deterministically rejects rules < 24 chars or > 5 lines, heredocs (<<), fenced code blocks, "Created At:" / "Completed At:" stdout wrappers, chat narration ("dispatched ", "I will "), and >= 0.70 Jaccard near-duplicates across existing skill rules, Ring-3 facts, active playbooks, and rejection tombstones.
  3. Gate 3 + Gate 4 (verifier.go & testdata/anchors.json — Critic 3: PII/Secrets, Contradictions & 16 Human Anchors):
    • Gate 3 scrubs invisible Unicode, home paths, emails, and credentials; Gate 4 checks tight line/rule caps plus domain anti-sycophancy / AGENTS.md contradiction 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 (6 valid rules G01–G06 + 10 realistic trap failures B01–B10) requiring 100% pass/fail agreement.
  4. 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. Before hq propose (our SHA-256 human approval queue) unlocks, hq rsi probes <id> --json emits 6 adversarial & utility scenarios (P1 indirect email injection, P2 spoofed DM urgency bypass, P3 PII/credential exfiltration, P4 hidden markdown directive, P5 tainted cross-channel relay, and P6 benign 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 to h.DiffSHA256. Editing even one byte of ProposedDiff invalidates the probe pass automatically.

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 (15 invocations for high-frequency tools; 3 runs 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-day helpful="0" idle pruning sweep. Upon rolling out RSI v2, running hq rsi compact permanently removed general.md and cleared all 66 stranded legacy hypotheses, ghost canaries targeting deleted paths transitioned cleanly to "archived", and the full internal/rsi Go suite—including all 16/16 human 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:

  1. 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.
  2. Long wait times on low-frequency workflows: High-frequency dev tools collect 15 canary runs within days; a quarterly skill needs months to collect 3 observations, relying primarily on the 6 pre-apply behavioral probes plus human review in the meantime.
  3. 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 human SHA-256 inspection acting together.
  4. 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.

Share this post

Scan with WeChat

Scan this QR code with WeChat to read or share on mobile.

Link copied to clipboard!