Agent Loop
AndonMitev/agent-loop
Loops autônomos que se auto-evoluem a cada tick para atingir objetivos
Ver no GitHubFramework para criar loops autônomos e auto-evoluíveis para agentes IA (Claude Code). Define um objetivo em uma linha e o loop executa iterações contínuas — observa, age, valida, registra e replaneja — sem intervenção humana na iteração interna. Usa JSON + Python puro, token-light, sem infraestrutura externa.
Instalação
npx convez-ai AndonMitev/agent-loop1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Manter repositórios saudáveis (testes, tipos, cobertura)
- Experimentos validados contra sinais lentos/ruidosos
- Pesquisa autônoma com triangulação de fontes
- Build iterativo com verificação separada do construtor
Veredito

Conceito sólido e inovador para automação contínua sem overhead de infraestrutura. Implementação focada e bem documentada, mas requer disciplina do usuário para definir gates (critérios de sucesso) claros — sem isso, o loop vira retrabalho infinito.
README
A tradução para o português deste README ainda está na fila.
agent-loop
Give an AI agent a one-line goal. It runs an autonomous loop that works toward it, verifies its own output, journals, and fires its own next tick — AI-first, token-light, self-evolving.
Self-evolving autonomous loops for AI coding agents (Claude Code & Codex). You set direction; the loop runs itself — observe → act → verify → journal → re-evolve its next directive, with no user in the inner loop. The engine is plain Python + JSON + markdown instructions: no API key, no build step, no infra — it rides whichever agent you already use. (~1.4k always-on tokens for all 11 skills; the heavy thinking is pay-per-use.)
The one idea
A tick is a pure function:
(state.json + new data) → (action + new state + one log record)
Each tick is a stateless agent. The substrate (state.json + log.jsonl) is the loop's entire memory between
ticks, so token cost per tick is bounded no matter how long history grows. The loop "evolves" because every tick
rewrites state.next — the directive the next tick reads first.
Only one thing changes by type of work — a profile. The loop primitive and substrate are identical for all:
| Profile | For | Gate ("what good means") |
|---|---|---|
| research | investigate an open question | every claim triangulated across ≥2 independent sources, refuted, cited, confidence-scored |
| experiment | validate an idea vs a slow/noisy signal | pre-registered bar, frozen before peeking; honest null = success |
| build | construct from a milestone DAG | acceptance met and a verifier separate from the builder confirms |
| maintenance | keep an existing app healthy | full suite green before and after; no regression; surgical edits |
Install (Claude Code plugin)
/plugin marketplace add AndonMitev/agent-loop
/plugin install agent-loop@agent-loop
Then in any project: /spawn-loop "<your goal>". On first run the helper is copied into that project's .loop/.
Quickstart (install → first output)
/plugin marketplace add AndonMitev/agent-loop
/plugin install agent-loop@agent-loop
/spawn-loop "keep this repo green and tidy"
/spawn-loop classifies the goal, seeds .loop/<id>/, runs the first tick, and schedules the next — you don't
click through iterations. You'll see a loop appear:
$ python3 .loop/loop.py list
repo-health [maintenance] event cyc= 1 preg=0 todo=0 next: sleep until a health signal fires …
Inspect it with python3 .loop/loop.py status repo-health; remove it with python3 .loop/loop.py rm repo-health.
Use — a full walkthrough (real commands, real output)
# 1. Spawn. One command: classifies the goal, seeds .loop/, runs the first tick, schedules the next.
/spawn-loop "keep my repo green: tests pass and types check"
# → creates loop 'repo-green' [maintenance], runs tick 1, self-schedules
# 2. See all your loops.
python3 .loop/loop.py list
# repo-green [maintenance] event cyc=1 preg=0 todo=0 next: sleep until a health signal fires …
# 3. Inspect one loop — goal, gate, last reading, what it'll do next.
python3 .loop/loop.py status repo-green
# 4. Nudge it manually (it ticks itself; use this only to debug or push it along).
/loop-tick repo-green
# 5. Delete it when you're done.
python3 .loop/loop.py rm repo-green
More worked examples — one per profile (research / experiment / build / maintenance) — in EXAMPLES.md.
Autonomy (AI-first)
The loop does not rely on you to drive each step — you give a goal and approve hard gates; it does the rest. It is
built to behave like an autonomous engineer, not a script. Every tick lives by a Prime directive (the first
thing loop-tick reads, overriding everything else):
- Decide + act, never passive. A tick never ends on a wait or a status report — it changes state/code/config, records a verdict, or makes an explicit, justified no-op. It always moves toward the goal.
- Invoke skills, don't describe them. When the work calls for a capability (
/deep-research,/grill-ai,/plan-decompose,/test-driven-development, …) the loop calls the skill — judgment-gated (only when it earns its tokens), never paraphrased or simulated. - Grill itself at every real distinction. Any kill/keep, promote, tombstone, anomaly, or surprising result
fires
/grill-aiadversarial self-critique before the call is committed. The loop argues with itself so you don't have to.
How it carries that out:
- Self-firing. Each tick chooses its
dispatchand fires the next tick itself —loopcontinues now,scheduleself-wakes viaScheduleWakeup/cron,eventwaits onMonitor/a signal. One/spawn-loop→ a self-running loop. - Hands-off in-session loop (Stop hook) — on by default.
/spawn-looparmspython3 .loop/loop.py auto <id>, so aStophook re-fires/loop-tickautomatically — no user clicks at all — until the tick setsdispatchaway fromloop, the goal completes, the burst cap (max, default 12) is hit, or you runloop.py stop. (Technique adapted from Anthropic's Ralph Wiggum plugin, MIT.) - AI second brain, not a human. Critique is
/grill-ai(the agent asks and answers from evidence) +/doubt-driven-development; errors are handled by/debugging-and-error-recovery. No human in the critique or recovery path. - ACT, don't ask. The loop decides and proceeds. It stops to ask only at genuine human gates — real money, prod deploy, external publish, spending, or destructive/irreversible ops.
- Durable autonomy. For unattended survival across closed sessions, point a cron/CI at
/loop-tick <id>(or graduate to Managed Agents). Self-paced (ScheduleWakeup) loops run while the session is alive.
Triggers
Loops are condition-routed, not dumbly periodic. A trigger is a predicate over (state, signal) → action, at two
levels: when a tick fires (time / push) and what it does once awake (the matched action). Push exists for
harness-tracked events (background-task completion, the Monitor tool tailing a log); external state is polled on
the heartbeat. See each loop's state.triggers.
Schedule vs loop (per-tick dispatch)
It's not one or the other per loop — each loop oscillates, decided at the end of every tick:
Is there useful work to do right now whose result the next step needs? YES → loop (run the next tick immediately; bounded by your compute, not the world). NO → schedule (wait): fast external state you must poll → short interval (≲270s); idle / slow signal → long interval (20–30m+) or event (wake on push: task completion,
Monitor, a cron heartbeat).
state.dispatch holds the profile default (build → loop, experiment → schedule, maintenance → event); each
tick overrides it by what's actually true (maintenance flips to loop while draining fixes; experiment
loop-bursts when new data lands).
Token cost (it's cheap by design)
The framework is built to be low-token, and autonomy doesn't change that if you follow the rails:
- Tiny per-tick read. A tick reads
state.json(~1KB) +tail 3— never the whole history. Cost per tick is bounded no matter how long the log grows (rotatefolds old records to an archive). - No re-doing past work. A tick sees only the tail, so the durable
decidedledger instate.json(always read in full, survivesrotate) carries what's settled: one line per item ({key, verdict, why}, deduped by key). Every tick checks it before acting and records new verdicts into it, so a tick many cycles later doesn't repeat killed or explored work. The ledger is the optimized journal — recall without re-reading logs. - Cost-gated thinking. The expensive part (critique via
/grill-ai+ a subagent) runs only on new data / anomaly, not every tick. Idle ticks are nearly free. - Bounded in-session loop. A
while truein one session would accumulate context every iteration, so the Stop-hook loop is capped (maxiterations) and each tick delegates heavy work to a throwaway subagent — the reused session grows only by small results. For long unattended runs, a cron firing fresh/loop-tickprocesses carries nothing over (each tick starts from the tinystate.json) — the cheapest mode.
Rule of thumb: tight bursts → in-session Stop-hook (convenient); long-haul → cron (cheapest).
Staying lean & sharp (anti-bloat, anti-sloppy)
Two failure modes kill unattended loops — they're guarded explicitly:
- Anti-bloat. Ticks are stateless (read
state.json+tail, never history);rotatebounds the log; heavy work is delegated to throwaway subagents;plan-decomposecuts speculative scope;author-skillonly fires on a proven recurring need and never duplicates. Andself-evolvegarbage-collects every pass — removes unused/duplicate skills, merges overlaps, keeps the smallest capability set. Net capability, not count. - Anti-sloppy. Verification is mechanically forced, not a guideline: the
appendhelper rejects any record that marks work done (backlog_done/ a done-ish verdict) unless it carries averifyblock with a real check that passed — and rejectsresult:"fail". Done is a verified fact, not a claim. On top of that, the tick's output quality gate: frozen acceptance verified by a real check (not vibes); every claim backed by evidence (file:line/data/passing command); no overclaiming (honestPARTIAL/UNKNOWNover a confident guess); confidence-filtered (low-confidence findings are verified up or dropped, not asserted — kills false positives); judgment calls verified by a separate agent (the builder never rubber-stamps itself); terse output.
Compatibility (Claude Code + Codex)
The engine is tool-agnostic: a Python helper (loop.py) + a JSON substrate + markdown instructions, none of which
depend on a specific agent.
- Claude Code — native: install as a plugin,
/spawn-loop&/loop-tickskills, aStophook for in-session autonomy. - Codex — native via
.codex-plugin/plugin.json(points at the same skills), plusAGENTS.mdfor driving the engine directly (python3 .loop/loop.py+ theSKILL.mdprocedures). For autonomy use headless re-invocation (codex exec/ a cron) instead of the Stop hook. - Shared state —
state.json/log.jsonlare plain JSON written only through the helper, so different agents can drive the same loop. (Targeted at Claude + Codex; others work viaAGENTS.mdbut aren't a focus.)
Why the .claude-plugin/ directory, if it's agnostic? That name is required by Claude Code to discover and
install a plugin (marketplace.json + plugin.json live there) — it's the Claude adapter, two manifest files,
nothing more. The agnostic engine is loop/loop.py + loop/profiles.json + the skills/*/SKILL.md
instructions + the .loop/ substrate (plain Python/JSON/Markdown, no Claude dependency). Codex's adapter is
AGENTS.md. One engine, one small adapter per agent — the .claude- prefix marks the adapter, not the framework.
Controls
Plain facts, no ceremony — the whole engine is ~600 lines of dependency-free Python you can read in one sitting:
- It runs on top of your existing agent (Claude Code / Codex) and inherits its permissions — it adds structure and verification, it doesn't grant itself new powers.
- Completion is decided by running the checks you define (your tests/builds/metrics), like a test runner or CI job.
- Everything is journaled to
log.jsonl;loop.py done <id> --dry-runpreviews what a check will run;loop.py stophalts a running loop anytime.
Honest limitations
- Self-paced loops are session-bound. In-session self-wake (
ScheduleWakeup) runs only while the session is alive. For unattended survival across closed sessions, drive/loop-tick <id>from a cron/CI job (or Managed Agents) — same loop, durable clock. - Verification is yours to ground. The framework gives you the places to verify (the build profile's separate-verifier step, the maintenance regression gate) — the checks themselves must run real tests/builds.
How it's laid out
.claude-plugin/marketplace.json # makes this repo a Claude Code marketplace
plugins/agent-loop/
.claude-plugin/plugin.json
skills/spawn-loop/SKILL.md # classify goal → seed a loop
skills/loop-tick/SKILL.md # run one iteration
loop/loop.py # the substrate helper (deterministic, schema-enforcing)
loop/profiles.json # the three work-type profiles
Companion skills (bundled)
The loop tick calls these, vendored into the plugin so it works out of the box:
- Original, AI-first —
grill-ai(AI-to-AI critique second brain),plan-decompose(autonomous goal → verifiable milestone DAG),deep-research(orchestrator-worker investigation: parallel sweep → triangulate → refute → cited synthesis → loop-until-saturation),self-evolve(the loop improves its own gate/triggers/ profile and graduates lessons to memory),author-skill(the loop writes new skills itself when a step recurs, and wires them into the flow — no human review). - From addyosmani/agent-skills (MIT) —
doubt-driven-development,test-driven-development,debugging-and-error-recovery.
Good code, not just working code. Build/maintenance ticks follow code-standards (think-before-coding,
simplicity-first, surgical changes, goal-driven+verified, LSP/types, repo's own commit conventions). It composes
with the host project's own CLAUDE.md / AGENTS.md — on Claude Code your existing CLAUDE.md is already loaded
and takes precedence; code-standards is the baseline that travels with the framework (and covers Codex, which
doesn't read CLAUDE.md).
The loop is self-extending: via self-evolve + author-skill it grows its own capabilities as it runs.
See THIRD_PARTY_NOTICES.md for attribution.
License
MIT © Andon Mitev. Bundled third-party skills under their own MIT licenses — see THIRD_PARTY_NOTICES.md.