24 de agosto de 2026 · [[El Abismo de Máquina/Ecos|¿qué es un eco?]] # Eco: Los cuatro tipos de bucle, según el equipo de Claude Code > [!entradilla] > El equipo de Claude Code define qué es un bucle y lo parte en cuatro tipos, según qué pieza del trabajo dejas de hacer tú. Con los frenos de gasto. > [!tip]+ Por qué me interesa > > Esto lo publicaron el 30 de junio, tres semanas después de que el tuit de Steinberger sobre *loop engineering* llenara X de gente discutiendo qué es un bucle sin ponerse de acuerdo. Yo escribí sobre aquello [[Newsletter/2026/86-Loop-engineering-vs-prompt-engineering|el 11 de junio]], y me quedé con las ganas de la parte práctica. Aquí está. > > Lo bueno es que es el fabricante quien escribe, y escribe sin épica ninguna. Su definición es de una línea: un bucle es un agente repitiendo ciclos de trabajo hasta que se cumple una condición de parada. A partir de ahí clasifican cuatro tipos por cómo arrancan y cómo se detienen, y lo que hace útil la clasificación es la columna final de la tabla: cada tipo se corresponde con una pieza distinta del trabajo que dejas de hacer tú. La comprobación, la condición de parada, el disparador o el prompt entero. Puesto así, montar un bucle deja de ser un proyecto y pasa a ser una decisión pequeña que se puede tomar hoy. > > Los dos apartados finales son los que menos se citan y para mí valen tanto como el resto. Uno es de calidad: escribe tu comprobación manual en un fichero para que el agente la ejecute entera, y pon a un segundo agente a revisar con el contexto limpio, porque el que ha hecho el trabajo llega convencido de su propio razonamiento. El otro es de gasto: pilota antes de una tirada grande, usa un script para lo que sea determinista porque sale más barato que razonarlo cada vez, y no lances una rutina más a menudo de lo que cambia aquello que estás comprobando. > > La pega, que es pequeña: está escrito para quien programa, con sus comandos y su vocabulario de repositorio. Casi todo se traduce a otros trabajos sin mucho esfuerzo, pero traducirlo te toca a ti. A lo mejor por eso se cita tan poco fuera del mundo del código. La otra pega, más de fondo, es que un texto del fabricante no va a hablarte de cuándo un bucle no compensa. Eso lo comento aparte en [[Posts/2026.08/25-loop-engineering-dos-meses-despues|el post]]. > > El original: [Loop engineering: Getting started with loops](https://claude.com/blog/getting-started-with-loops) > [!abstract]- Resumen esquemático > > #### Definición y criterios de clasificación > > - Bucle: un agente repitiendo ciclos de trabajo hasta que se cumple una condición de parada. > - Los cuatro tipos se clasifican por: cómo se disparan, cómo se detienen, qué primitiva de Claude Code usan y para qué tipo de tarea sirven. > - Advertencia de partida: no todas las tareas necesitan bucles complicados; empezar por lo más simple y usar los patrones de forma selectiva. > > #### Tipo 1 - Por turnos > > - Disparo: un prompt del usuario. Parada: Claude juzga que ha terminado o que necesita más contexto. > - Para tareas cortas que no forman parte de un proceso ni de un horario. > - Es el bucle agéntico que ya corre en cada prompt: reúne contexto, actúa, comprueba su trabajo, repite si hace falta y responde. > - Control de gasto: prompts específicos y mejor verificación vía skills, para reducir el número de turnos. > - Mejora recomendada: escribir los pasos de comprobación manual en un `SKILL.md` para que el agente se verifique solo de punta a punta. Cuanto más cuantitativa es la comprobación, más fácil le resulta autoverificarse. > - Ejemplo dado (`verify-frontend-change`): arrancar el servidor, abrir la página, interactuar con el control, capturar antes y después, consola sin errores nuevos, traza de rendimiento con Chrome Devtools MCP; si falla un paso, volver al primero. > > #### Tipo 2 - Por objetivo (`/goal`) > > - Disparo: un prompt manual en tiempo real. Parada: objetivo cumplido O número máximo de turnos. > - Para tareas con criterio de salida verificable. > - Mecanismo: cada vez que Claude intenta parar, un modelo evaluador comprueba la condición y le devuelve el trabajo hasta que se cumpla o se agoten los turnos. > - Por eso funcionan tan bien los criterios deterministas: número de tests que pasan, umbral de puntuación superado. > - Ejemplo: `/goal get the homepage Lighthouse score to 90 or above, stop after 5 tries.` > - Control de gasto: criterio de terminación específico y tope explícito de intentos. > > #### Tipo 3 - Por tiempo (`/loop` y `/schedule`) > > - Disparo: un intervalo de tiempo. Parada: lo cancelas tú, o el trabajo se completa (se fusiona el PR, se vacía la cola). > - Para trabajo recurrente donde la tarea es la misma y solo cambian las entradas, o para asomarse a sistemas externos y reaccionar a lo que cambió. > - `/loop` corre en tu ordenador: si lo apagas, se detiene. `/schedule` crea una rutina en la nube que aguanta sin sesión abierta. > - Ejemplo: `/loop 5m check my PR, address review comments, and fix failing CI` > - Control de gasto: intervalos más largos, o reaccionar a eventos en vez de a tiempo. > > #### Tipo 4 - Proactivo > > - Disparo: un evento o un horario, sin nadie delante en tiempo real. Parada: cada tarea sale cuando cumple su objetivo; la rutina corre hasta que la apagas. > - Para flujos recurrentes de trabajo bien definido: informes de error, triaje de incidencias, migraciones, actualización de dependencias. > - Se compone con las primitivas anteriores más el modo automático y los *dynamic workflows* (en vista previa de investigación). > - Receta de ejemplo: `/schedule` para revisar el canal de informes cada hora, `/goal` para definir qué es terminado, skills para documentar cómo verificarlo, workflows para orquestar agentes que triagen, arreglen y revisen, y modo automático para no parar a pedir permiso. > - Control de gasto: rutinas a modelos más pequeños y rápidos, y el modelo más capaz reservado para los juicios. > > #### Mantener la calidad > > - La calidad de la salida de un bucle depende del sistema que lo rodea. > - Mantener limpio el propio código base: Claude sigue los patrones y convenciones que ya existen. > - Dar a Claude la forma de verificar su propio trabajo, dejando escrito con skills qué es un buen resultado para ti y para tu equipo. > - Documentación de frameworks y librerías al alcance, que es donde están las buenas prácticas actualizadas. > - Segundo agente para revisar: un revisor con contexto limpio está menos sesgado y no arrastra el razonamiento del agente principal. > - Regla de fondo: cuando un resultado no da la talla, no quedarse en arreglar ese resultado; intentar dejarlo escrito en el sistema para todas las iteraciones futuras. > > #### Controlar el gasto de tokens > > - Elegir la primitiva y el modelo adecuados: las tareas pequeñas no necesitan varios agentes ni bucles, y algunas admiten modelos más baratos y rápidos. > - Criterios de éxito y de parada claros, para que llegue antes a la solución (pero no demasiado pronto). > - Pilotar antes de una tirada grande: los *dynamic workflows* pueden lanzar cientos de agentes. > - Usar scripts para lo determinista: ejecutar un script sale más barato que razonar los pasos cada vez. > - No lanzar rutinas más a menudo de lo necesario: ajustar el intervalo a la frecuencia con la que cambia lo que se está comprobando. > - Revisar el consumo: `/usage` desglosa por skills, subagentes y MCPs; `/goal` sin argumentos da turnos y tokens gastados; `/workflows` da el consumo por agente. > - La elección de modelo y de nivel de esfuerzo está entre las palancas que más mueven lo que cuesta un bucle. > > #### Tabla resumen y punto de partida > > | Bucle | Sueltas | Úsalo cuando | Con qué | > | --- | --- | --- | --- | > | Por turnos | La comprobación | Estás explorando o decidiendo | Skills de verificación propias | > | Por objetivo | La condición de parada | Sabes qué aspecto tiene terminado | `/goal` | > | Por tiempo | El disparador | El trabajo pasa fuera de tu proyecto, con horario | `/loop`, `/schedule` | > | Proactivo | El prompt | El trabajo es recurrente y está bien definido | Todo lo anterior más dynamic workflows | > > - Forma de empezar que recomiendan: mirar el trabajo que ya haces, elegir una tarea donde el cuello de botella seas tú y preguntarte qué pieza puedes soltar. ¿Sabes escribir la comprobación? ¿Está claro el objetivo? ¿El trabajo llega con horario? > - Después: lanzar el bucle, observar dónde se atasca o dónde se pasa de la raya, e iterar sobre él sin miedo. --- # Contenido original: Loop engineering: Getting started with loops Fuente: [Loop engineering: Getting started with loops](https://claude.com/blog/getting-started-with-loops) · Delba de Oliveira y Michael Segner · 30 de junio de 2026 There's a lot of talk right now about loop engineering or "designing loops" instead of prompting your coding agent. If you spend some time on X trying to pin down what a loop actually is, you'll come across multiple different answers. On the Claude Code team, we define **loops as agents repeating cycles of work until a stop condition is met**. We categorize a few different types of loops based on: - How they are triggered - How they are stopped - What Claude Code primitive is used - What type of task is most appropriate for each. We'll cover the main loop types, when to use each, and how to maintain code quality while managing token usage. Not all tasks require complex loops; start with the simplest solution and use these patterns selectively. ## Turn-based loops - **Triggered by**: A user prompt. - **Stop criteria**: Claude judges it has completed the task or needs additional context. - **Best used for:** Shorter tasks that are not part of a regular process or schedule. - **Managed usage by:** Write specific prompts and improve verification using skills to reduce the number of turns. Every prompt you send starts a manual loop with you directing each turn. Claude gathers context, takes action, checks its work, repeats if needed, and responds. We call this the agentic loop. For example, ask Claude to create a like button. It reads your code, makes the edit, runs the tests, and hands back something it *believes* works. You then manually check the work, and write the next prompt. You can improve the verification step by encoding your manual steps as a SKILL.md so Claude can check more of its own work, end-to-end. This should include tools or connectors to allow Claude to *see*, *measure* or *interact* with the result. The more quantitative the checks are, the easier it is for Claude to self-verify. For example, in your SKILL.md file you may specify: ```plaintext --- name: verify-frontend-change description: Verify any UI change end-to-end before declaring it done. --- # Verifying frontend changes Never report a UI change as complete based on a successful edit alone. Verify it the way a human reviewer would: 1. Start the dev server and open the edited page in the browser. 2. Interact with the change directly. For a new control (button, input, toggle): click it, confirm the expected state change, and screenshot before/after. 3. Check the browser console: zero new errors or warnings. 4. Use the Chrome Devtools MCP, run a performance trace and audit Core Web Vitals. If any step fails, fix the issue and rerun from step 1 - do not hand back partially verified work. ``` ## Goal-based loop (/goal) - **Triggered by**: A manual prompt in real-time. - **Stop criteria**: Goal achieved OR maximum number of turns reached. - **Best used for:** Tasks that have verifiable exit criteria. - **Managed usage by:** Setting a specific completion criteria and explicit turn caps, "stop after 5 tries." Sometimes, a single turn is not enough, especially for more complex tasks. Agents do better when they can iterate. You can extend how long Claude keeps iterating by defining what done looks like with /goal. When you define the success criteria, Claude doesn't have to make a determination on what is "good enough" and end the loop early. Each time Claude tries to stop, an evaluator model checks your condition and sends it back to work until the goal is met or a number of turns you define is reached. This is why deterministic criteria, such as number of tests passed or clearing a certain score threshold, are so effective. For example: ```plaintext /goal get the homepage Lighthouse score to 90 or above, stop after 5 tries. ``` ## Time-based loop (/loop and /schedule) - **Triggered by**: A specified time interval. - **Stop criteria**: You cancel it, or the work completes (the PR merges, the queue is empty). - **Best used for:** For recurring work, or interfacing with external environments / systems. - **Managed usage by:** Set longer intervals or react based on events rather than time. Some agentic work is recurring: the task stays the same and only the inputs change. For example, summarizing Slack messages every morning. Other work depends on external systems, and a simple way to interface with one is to check it on an interval and react to what changed. For example, a PR which may receive code reviews or fail CI. For these, you can trigger when Claude runs with `/loop` which re-runs a prompt on an interval. For example: ```plaintext /loop 5m check my PR, address review comments, and fix failing CI ``` `/loop` runs on your computer, so if you turn it off, it stops. You can move the loop to the cloud by creating a routine with `/schedule`. ## Proactive loops - **Triggered by**: An event or schedule, with no human in real time. - **Stop criteria**: Each task exits when its goal is met. The routine itself runs until you turn it off. - **Best used for:** Recurring streams of well-defined work: bug reports, issue triage, migrations, dependency upgrades, etc. - **Managed usage by:** Routing routines to smaller, faster models and using the most capable model for judgment calls. The primitives above, along with other Claude Code features like **auto mode** and **dynamic workflows** (research preview) can be composed into a loop for long-running work. For example, to handle incoming feedback, you can use: 1. **`/schedule`** (research preview) to run a routine that checks for new reports 2. **`/goal`** to define what done looks and **skills** to document how to verify it 3. **Dynamic workflows** to orchestrate agents that triage each report, fix it, and review the fix 4. **Auto mode** so the routine runs without stopping to ask for permission Putting it together, a prompt could look like this: ```plaintext /schedule every hour: check #project-feedback for bug reports. /goal: don't stop until every report found this run is triaged, actioned, and responded to. When fixing a bug, use a workflow to explore three solutions in parallel worktrees and have a judge adversarially review them. ``` ## Maintaining code quality The quality of a loop's output depends on the system around it. When designing the system: - **Keep the codebase itself clean**: Claude follows patterns and conventions that already exist in your codebase. - **Give Claude a way to verify its own work**: Encode what good looks like for you and your team with skills. - **Make docs easy to reach:** Frameworks and libraries docs have up-to-date best practices. - **Use a second agent for code reviews**: A reviewer with fresh context is less biased and not influenced by the main agent's reasoning. You can use the built-in `/code-review` skill or Code Review for Github. Loops that write code need loops that check it. When an individual result doesn't meet the standard, don't stop at fixing the individual issue, try to encode it to improve the system for all future iterations. ## Managing token usage To manage token usage, loops should have clear boundaries: - **Choose the right primitive and model for the job:** Smaller tasks don't need multiple agents or loops. Some tasks can use cheaper and faster models. - **Define clear success and stop criteria:** Be specific about what done looks like so Claude can arrive at the solution sooner (but not too soon). - **Pilot before a large run:** Dynamic workflows can spawn hundreds of agents. Gauge usage on a smaller slice of the work first. - **Use scripts for deterministic work**: Running a script is cheaper than reasoning through the steps. For example, a PDF skill can ship a form-filling script that Claude runs each time, instead of re-deriving the code. - **Don't run routines more often that you need to:** Match the interval to how often the thing you're watching changes - **Review usage:** The `/usage` command breaks down recent usage by skills, subagents, and MCPs, `/goal` with no arguments shows number of turns and token usage so far, `/workflows` shows each agent's token usage and you can stop an agent at any time. Your model and effort level choices are among the biggest levers on what a loop costs. ## Getting started To summarize: | Loop | You hand off | Use it when | Reach for | | --- | --- | --- | --- | | Turn-based | The check | You're exploring or deciding | Custom verification skills | | Goal-based | The stop condition | You know what done looks like | `/goal` | | Time-based | The trigger | The work happens outside your project on a schedule | `/loop`, `/schedule` | | Proactive | The prompt | The work is recurring and well-defined | All of the above, and dynamic workflows | To get started with loops, look at the work you already do. Pick one task where you're the bottleneck and ask which piece you could hand off: can you write the verification check? Is the goal clear enough? Does the work arrive on a schedule? Once you have an idea, run the loop, observe the results like where it stalls or over-reaches, and don't be afraid to iterate on it. For more information, read the Claude Code docs on running agents in parallel, as well as the loop, schedule, goal, and dynamic workflows pages. *This article was written by Delba de Oliveira and Michael Segner*