# Óscar Gallego — full blog (markdown) > Every published post on oscargallegoruiz.com, concatenated as markdown for LLM context. Bilingual (ES + EN). --- URL: https://www.oscargallegoruiz.com/en/blog/on-device-ai-extraction-rules/ Lang: en # On-device AI: keep wrong numbers out of your forms > Apple's on-device AI misread my mileage, then my app picked the wrong oil change. Field-level rules, an editable task, and the fallback the fix still misses. **Short answer:** Apple's on-device AI turned `12.300 km` into 12.3 kilometers in my app. I gave explicit numbers and relative dates precedence over the model's output, then made the proposed maintenance task editable. Reading the code for this article also exposed a fallback that still lets an unjustified task through. The most annoying part wasn't the mileage. While testing [Rydger](https://www.rydger.com/), my maintenance app for motorcycles and cars, I entered a generic oil change for a BMW F 850 GS. The app picked `Fork oil`. Then it showed me the task as fixed text, with no way to change it. I could see exactly what was wrong. My own review screen wouldn't let me review it. This happened on November 5, on my English-language iPhone, while I was entering Spanish text and number formats. These are observations from that test, followed by code changes and regression fixtures. I don't have a model accuracy benchmark or a measured failure rate. ## The type was right; the mileage wasn't The one-line entry feature uses Apple's Foundation Models to extract a Swift structure from what the rider types. With [guided generation](https://developer.apple.com/documentation/foundationmodels), Apple guarantees that the generated result fits the defined types. That's useful. It doesn't tell the app what the rider meant by a period. In my input, `12.300 km` meant twelve thousand three hundred kilometers. The model read it as twelve point three. It also failed to recognize plain `oil` as maintenance. This longer entry was misread too: ```text cambio de aceite en Motos Pepe 89,90 € a 15.000 km ayer ``` That's an oil change at Motos Pepe for €89.90, at 15,000 km, yesterday. Nothing exotic. The phone's language and the notation I use when writing simply don't match. A positive-number check won't catch the mileage error: 12.3 is a perfectly good positive `Double`. **A valid field can still contradict the input.** The check has to reach back to the sentence, not stop at the generated type. ## Explicit fields get their own authority The first fix added `OneLineEntryTextHints`, a set of deterministic rules for the parts of the sentence the app can recognize directly. When a rule finds a value, it takes precedence over the model's value. Here's the amount field in `OneLineEntryOnDevice.proposal`: ```swift let amount = OneLineEntryTextHints.amount(in: request.text) ?? positive(reading.amount) ``` The rules look for evidence attached to the number. Distance needs a recognized unit. An amount needs a euro marker. Otherwise the odometer reading could helpfully become the bill as well. The numeric parser handles grouped thousands and decimal commas under the conventions used by this feature. Relative-day rules resolve words such as `ayer` and `yesterday` against the request's reference day. When no rule matches, the model's field remains available. Other information, such as the shop name, can still come from the model. The regression test for the Motos Pepe sentence deliberately feeds the proposal function a bad model response: an expense, 15 km, and an amount of 8,990. It expects a service at 15,000 km for 89.90, yesterday, while keeping the vendor. That bad response is synthetic. It isn't a transcript captured from the phone. The test's job is to hold the model wrong on purpose and check that the surrounding code corrects it. A lucky generation shouldn't be able to make this test pass. ## “Oil” is a match, not enough evidence for “fork oil” The task-linking failure was more mundane. Several maintenance tasks contained `oil`, and the matcher took the first one. For the BMW in my test, that meant fork oil. The fix makes the matcher consider specificity. A candidate naming a component the entry never mentions loses to a candidate without that extra requirement. A Spanish mention of `horquilla` can support the English task title `Fork oil`; a generic oil change can't. These cases come from the deterministic matcher's regression test: | Input | Available tasks | Expected match | | --- | --- | --- | | `cambio de aceite` | Fork oil, Final drive oil, Engine oil, Brake fluid | Engine oil | | `aceite de horquilla` | Fork oil, Engine oil | Fork oil | | `cambio de aceite` | Fork oil, Final drive oil | None | The last row is the useful one to steal. Removing the reasonable candidate should not promote an unreasonable one. The helper returns `nil` and leaves a choice for the rider. This is a product convention, not proof that every unspecified oil change means engine oil. The task remains a proposal. The next part of the feature has to treat it that way. ## A review screen needs controls for the fields that can be wrong The next change added a task picker to the service form when task options are supplied. It includes `None`. In the one-line entry flow, saving now resolves the link from the edited draft's task title. That last detail matters. Updating the label while saving the original link would leave the bug intact behind a nicer screen. The form itself warns that a linked service marks the task done and resets the reference for its next due date. This isn't just choosing a label for the history list. The proposed task carries meaning elsewhere in the app. I had asked the rider to confirm a decision while withholding the control needed to change it. No improvement in extraction quality makes that a sensible interface. ## The rules have limits, and one fallback still escapes them Here's where the neat “a regex fixed my AI” story breaks down. While checking the source for this article, an agent found a gap my incident note didn't capture. The deterministic matcher abstains when all the remaining oil tasks name unmentioned components. But the function combining that result with the model's choice rejects an unjustified component **only when a deterministic alternative exists**. If the model picks `Fork oil` and the helper has no alternative, the model's choice can survive. That's a finding from the current code, not another result I observed on the phone. It also means the table's last row describes the helper, not the complete proposal function. The picker provides a way out, but the fallback still needs its own regression case. There are less subtle limits too. A separator followed by three digits is treated as a thousands separator. That suits these odometer inputs; I wouldn't copy the convention into an app that needs three decimal places. Job words and component names come from finite lists. Someone has to maintain them. ## Start with a model response you know is wrong The cheapest useful check is at the boundary that turns generated fields into a form draft. Take a real failing input and inject the wrong answer there. This is adapted from Rydger's regression test and uses its project types: ```swift let request = OneLineEntryRequest( text: "oil 60 € a 12.300 km", now: Date(timeIntervalSince1970: 1_793_900_000), locale: Locale(identifier: "en_US"), currency: "EUR", odometerKm: 12_000, items: ["Oil change"] ) let wrong = OneLineEntryReading( kind: "expense", odometerKm: 12.3, amount: 60, category: "maintenance" ) let result = OneLineEntryOnDevice.proposal(from: wrong, request: request) #expect(result?.odometerKm == 12_300) #expect(result?.kind == .service) ``` Then remove the good task candidate. With only `Fork oil` available, feed a generic oil change and a model response that insists on linking it. Test the final proposal, not just the helper. That's the missing case in my implementation. ## Sources - Apple, [Foundation Models](https://developer.apple.com/documentation/foundationmodels), read November 8, 2026, for the scope of guided generation. - My November 5 device tests and the private Rydger repository: `OneLineEntryTextHints`, the proposal logic in `OneLineEntryOnDevice`, and `ServiceRecordForm`. An agent checked the article's claims against the current code. The cited tests were read, not rerun for this article; this is not a measurement of post-fix model accuracy. **Related reading:** [the checks around a model that keep its mistakes from becoming your app's behavior](/en/blog/harness-engineering-why-your-agent-fails/). --- **P.S.** Which AI-filled field in your app is hardest for a user to correct? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/ia-local-extraccion-reglas/ Lang: es # IA local en iOS: cuando 12.300 km se convierten en 12,3 > La IA local leyó mal los km de Rydger y eligió aceite de horquilla. Qué saqué del modelo, cómo se corrige la tarea y qué sigue sin cubrir el arreglo. **Respuesta corta:** la IA local de mi iPhone leyó `12.300 km` como 12,3 kilómetros. El arreglo fue dar prioridad a reglas que leen los datos explícitos de la frase y dejar que el usuario cambie la tarea propuesta. La parte incómoda: una de esas reglas todavía no manda en todos los caminos del código. El 5 de noviembre estaba probando la entrada en una línea de [Rydger](https://www.rydger.com/), mi app de mantenimiento para motos y coches, con el iPhone configurado en inglés. Yo escribía los números a la española. El modelo de Apple que se ejecuta en el móvil se comió los miles; además, `oil` no contaba como mantenimiento. Esta frase tampoco salía bien: ```text cambio de aceite en Motos Pepe 89,90 € a 15.000 km ayer ``` En la misma prueba, con una BMW F 850 GS, «cambio de aceite» acabó asociado a `Fork oil`, el aceite de horquilla. El formulario enseñaba la tarea como texto fijo. Veía el error y no podía cambiarlo. No tengo un benchmark del modelo ni una tasa de fallos. Tengo esas pruebas en el móvil, los cambios que salieron de ellas y los tests de regresión. Con eso basta para revisar dónde estaba dejando decidir a la IA más de la cuenta. ## Un número válido puede ser el kilometraje equivocado Rydger usa Foundation Models para convertir la frase en una estructura Swift. La [generación guiada de Apple](https://developer.apple.com/documentation/foundationmodels) garantiza que la respuesta encaje en los tipos definidos. Eso ayuda con la forma de los datos. No decide si ese punto separa miles. `12.3` cabe perfectamente en un `Double`. Es positivo. Un schema que solo pida un número mayor que cero lo acepta tan tranquilo, aunque yo haya escrito doce mil trescientos kilómetros. Ahí está el hueco que no tapa «valida la salida del modelo». Hay que comprobar qué relación tiene el valor con lo que escribió la persona. Y el idioma del teléfono no obliga a nadie a escribir los números como espera ese idioma. Mi móvil estaba en inglés; yo seguía siendo de Málaga. ## Lo que la frase dice explícitamente tiene prioridad El primer arreglo añadió `OneLineEntryTextHints`: reglas para leer kilómetros, importes en euros y expresiones como «ayer». Si encuentran un valor, ese valor manda sobre el del modelo. La precedencia se ve en esta línea de `OneLineEntryOnDevice.proposal`: ```swift let amount = OneLineEntryTextHints.amount(in: request.text) ?? positive(reading.amount) ``` No se trata de extraer cualquier número que aparezca. Los kilómetros necesitan una unidad reconocida; el importe necesita una referencia explícita al euro. Así, `12.300 km` no acaba también como gasto. El parser trata los grupos de tres cifras como miles y admite la coma decimal de `89,90 €`. Son convenciones de esta entrada, con límites que cuento abajo. Para «ayer», la regla parte del día de referencia de la petición. No le vuelve a preguntar al modelo qué día era ayer. Si no encuentra una expresión que conozca, conserva el valor propuesto por el modelo. El test `theDeviceTestSentence` usa la frase de Motos Pepe y le inyecta una respuesta deliberadamente mala: gasto, 15 km y 8.990 de importe. **Esa respuesta es una fixture del test, no una captura literal de lo que contestó el iPhone.** Espera un servicio a 15.000 km por 89,90 €, con la fecha de ayer, y conserva el taller que sí venía en la respuesta. Es el test que me interesa: aunque el modelo insista en el valor malo, la regla gana. Que mañana acierte no es motivo para quitarla. ## Encontrar «oil» no identifica qué aceite se cambió El segundo fallo estaba en el enlace con las tareas de mantenimiento. Había varias con `oil` en el nombre y se cogía la primera. En esa moto fue `Fork oil`. El orden de una lista estaba decidiendo qué pieza había mantenido. La corrección introduce una distinción pequeña: una tarea que menciona una pieza que la frase no nombra pierde frente a una candidata sin esa especificidad. Si escribo «aceite de horquilla», queda justificado elegir esa tarea. Si escribo «cambio de aceite», no. Estos son casos del test del selector determinista, no nuevas pruebas en el móvil: | Frase | Tareas disponibles | Resultado esperado | | --- | --- | --- | | `cambio de aceite` | Fork oil, Final drive oil, Engine oil, Brake fluid | Engine oil | | `aceite de horquilla` | Fork oil, Engine oil | Fork oil | | `cambio de aceite` | Fork oil, Final drive oil | Ninguna | La tercera fila importa más que la primera. Si solo hay candidatos demasiado específicos, el selector devuelve `nil`. «No he encontrado una tarea» es algo que el usuario puede resolver en el formulario. Adivinar una pieza que no he mencionado le complica el trabajo al usuario. Eso tampoco demuestra que un cambio genérico sea siempre de aceite de motor. Es la preferencia de producto que recoge esta regla, no conocimiento mecánico infalible. ## La revisión necesita un sitio donde corregir Después, el formulario de servicio ahora tiene un selector de tarea, incluida la opción de no enlazar ninguna. El flujo de entrada en una línea guarda la selección modificada, en vez de recuperar la propuesta original. Antes, pedir que revisara los datos tenía una pega bastante obvia: el dato que estaba mal no se podía tocar. Había construido una pantalla de revisión a la que le faltaba precisamente esa revisión. Además, el propio formulario avisa de que enlazar el servicio marca la tarea como hecha y actualiza los datos con los que se calcula el próximo vencimiento. El nombre de la tarea no es una etiqueta decorativa. Cambiarlo afecta a lo que la app considera que ya se ha mantenido. **El cambio que hace el usuario tiene que conservarse al guardar.** Un selector que cambia el texto pero deja intacto el enlace original sería el mismo fallo, con más interfaz. ## Las reglas también se equivocan, y queda un hueco Sería cómodo terminar con «una regex lo arregló». La comprobación del código para este artículo encontró una pega que mi nota de la incidencia no recogía. El selector determinista sí devuelve `nil` cuando solo encuentra aceites de piezas no mencionadas. Pero la función que mezcla su resultado con el del modelo solo descarta una elección como `Fork oil` **si hay una alternativa determinista**. Si el modelo propone horquilla y la regla no encuentra alternativa, esa propuesta puede quedarse. Es una conclusión de leer el código actual, no otra prueba que haya hecho en el teléfono. Así que la tercera fila de la tabla describe al selector, no garantiza el comportamiento de toda la función. Falta cubrir ese caso en la mezcla final. El selector del formulario permite corregirlo, pero no convierte la propuesta en correcta. Los números tienen su propia letra pequeña. Interpretar un separador seguido de tres cifras como miles sirve para estas lecturas del cuentakilómetros. No copiaría esa convención a una app que necesite tres decimales. Y la lista de trabajos y piezas es finita: añadir idiomas o aceptar nombres nuevos obliga a mantenerla. ## Empieza con una respuesta del modelo que sabes que está mal Antes de retocar el prompt, cogería una frase que ya haya fallado y probaría la función que prepara el formulario con una respuesta falsa. Este fragmento adapta el test de Rydger; los tipos son del proyecto: ```swift let request = OneLineEntryRequest( text: "oil 60 € a 12.300 km", now: Date(timeIntervalSince1970: 1_793_900_000), locale: Locale(identifier: "en_US"), currency: "EUR", odometerKm: 12_000, items: ["Oil change"] ) let wrong = OneLineEntryReading( kind: "expense", odometerKm: 12.3, amount: 60, category: "maintenance" ) let result = OneLineEntryOnDevice.proposal(from: wrong, request: request) #expect(result?.odometerKm == 12_300) #expect(result?.kind == .service) ``` Eso comprueba quién manda cuando hay desacuerdo. Después añadiría el caso sin alternativa: solo `Fork oil` disponible, cambio genérico en la frase y el modelo empeñado en enlazarlo. Es justo el hueco que queda en mi función. ## Fuentes - Apple, [Foundation Models](https://developer.apple.com/documentation/foundationmodels), consultado el 8 de noviembre de 2026: alcance de la generación guiada. - Mis pruebas del 5 de noviembre y el código de Rydger, repo privado: las reglas de `OneLineEntryTextHints`, su uso en `OneLineEntryOnDevice` y el selector de `ServiceRecordForm`. Para este artículo, un agente contrastó las afirmaciones con el código actual; los tests citados se leyeron, no se volvieron a ejecutar. No he medido aquí la precisión del modelo después del cambio. **Lectura relacionada:** [qué comprueba el harness cuando el modelo se equivoca](/blog/harness-engineering-por-que-falla-tu-agente/). --- **P.D.** ¿Tu formulario deja corregir todo lo que propone la IA, o hay algún dato que se queda fijo? Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/iphone-duo-simulator-ui-tests/ Lang: en # Testing a SwiftUI app on the iPhone Duo simulator, headless > Rydger UI tests on the iPhone Duo simulator: Cancel and Save vanished, SpringBoard crash-looped, and the inner screen needed a workaround. Here are the fixes **Short answer:** on the iPhone Duo simulator, Cancel and Save vanished from my app's sheets as soon as the form scrolled. The agent on the Duo story tried eight fixes and none worked. One line did: `toolbarVerticalBehavior(.disabled)`. Getting there also cost me a SpringBoard crash loop, a simulator my own cleanup script deleted, and a test that couldn't tap a field. Each one is below, with the fix. The app is Rydger, a SwiftUI app with an iOS 18 deployment target. The setup: Xcode 27.2, the iOS 27.1 simulator runtime, headless, the way my agents run every test. ## Cancel and Save vanished as soon as the form scrolled Rydger's add and edit vehicle forms live in a sheet: a `NavigationStack`, a `Form`, and a toolbar with `.cancellationAction` and `.confirmationAction` items. On an iPhone 17 Pro simulator, both add-vehicle UI tests pass. On the Duo, they failed. The test that edits the plate failed with "Failed to tap Save", and the accessibility tree from the failed run showed an empty navigation bar. The agent working on the Duo story reproduced it with a minimal `Form` and, by its own account, tried eight variants: removing the top fade, the drag indicator and the keyboard Done button, changing `contentMargins`, the principal toolbar item, `safeAreaInset`, `presentationSizing(.page)` and forcing `toolbarVisibility`. None brought the buttons back. It logged the bug as unresolved and moved on. ## One modifier brings them back Grok's search pointed me to [Sarun's post on sheets on the Duo](https://sarunw.com/posts/sheets-and-fold-avoidance-on-iphone-duo/): on the closed device in portrait, iOS moves a sheet's close and confirm buttons into a vertical bar, and you can turn that behavior off. He suggests turning it off for one-button sheets. Mine have two. I never saw a vertical bar in the simulator, only buttons that disappeared on scroll, but disabling the behavior brought them back. The modifier ships in the iOS 27.2 SDK and works back to iOS 27.1: ```swift private extension View { /// iPhone Duo (iOS 27.1+) moves a sheet's Cancel and Save into a vertical toolbar, /// and on the 27.1 simulator both vanish once the form scrolls: keep the usual bar. @ViewBuilder func horizontalToolbar() -> some View { if #available(iOS 27.1, *) { toolbarVerticalBehavior(.disabled) } else { self } } } ``` Applied to the shared sheet, the next run showed Cancel and Save still in the bar after scrolling (y=112 in the accessibility tree). The plate test still failed, for a different reason further down. I asked Grok to search X and the web for this bug between September 10 and November 5. It found no reports, so I can't say whether Apple considers it a bug or intended behavior. ## Faking a fold with simctl crash-looped SpringBoard To capture the inner screen, the agent tried to "open" the device by turning its screens on and off with `xcrun simctl io screenConfig … power`. The simulator's SpringBoard then crashed about every five seconds: 14 crash reports between 18:18:50 and 18:20:20, all but the first an assertion in `-[SBMainDisplayConfigurationTransformer transformDisplayConfiguration:]`, and each one popped up a macOS crash dialog on my screen. An hour later, another agent ran the same `screenConfig` call on a second Duo simulator, and within a second it was crash-looping the same way. A fresh Duo simulator that never saw a `screenConfig` call booted headless with `simctl boot` and logged no SpringBoard crashes. Blake Crosley [hit something similar](https://blakecrosley.com/blog/xcode-27-1-beta-iphone-duo-simulator) in September: powering off the outer display "crashed the simulator's system shell". Don't fake a fold with `screenConfig`. ## My own cleanup script deleted the simulator The fresh simulator then shut down on me twice and finally vanished from `simctl list`. My repo has a cleanup script for finished worktrees, and its `--orphans` mode shuts down and deletes every simulator named "Rydger Agent " whose worktree no longer exists. I had named the test device "Rydger Agent duo-check", and other agent sessions were cleaning up their own work on the same Mac. At 20:35 another agent session, cleaning up its own worktrees, ran it, and its output listed "Simulator duo-check": the name matched the rule and no worktree with that name existed. The two shutdowns before that I can't explain. A device named "Duo Capture (Rydger)" has survived since. ## There is no supported way to fold the simulator `simctl` has no posture command. An [Apple Developer Forums thread](https://developer.apple.com/forums/thread/847883) asks for one, and Apple hasn't answered. In Xcode 27.2 the simulator window is Device Hub, which has the pose buttons, but my automation tool couldn't click inside its window because it couldn't tell which window it was looking at. What worked was [duoctl](https://github.com/skarol/duoctl), a small open-source tool that sends hinge events to the simulator through private HID calls. An agent read its code before running it: a Python wrapper that calls `xcrun` and `codesign` and compiles a helper that runs inside the simulator, with no network calls. It works headless with Xcode 27.2: ```text $ duoctl -d open && duoctl -d state "hingeAngle": 180.0, "activeScreen": "inner", "orientation": "landscape", "sizePoints": [951.0, 669.0] ``` It's private API, so the next Xcode can break it. For now it's the only way I found to open the device from a script. ## Capture the inner screen from the Mac, not from XCTest Two more traps once the device is open: - **Screenshots.** [Another developer reports](https://x.com/vladimirchama/status/2114720281101287768) that XCTest screenshots of the inner screen come out black, and only the active screen renders, so I never looked at them. `simctl io screenshot --display=` from the Mac works, and `duoctl screenshot` picks the screen for you. - **Taps.** On the inner screen, XCUITest never reported my elements as hittable, even after I rotated to portrait, but `element.tap()` still worked. So the store-screenshot test pauses at each frame and the Mac takes the picture: ```swift func snap(_ app: XCUIApplication, _ name: String) { if let pause = ProcessInfo.processInfo.environment["SNAP_HOST_PAUSE"].flatMap(Double.init) { print("SNAP-HOST-READY \(name)") Thread.sleep(forTimeInterval: pause) } // ... the usual XCTAttachment } ``` ```bash TEST_RUNNER_SNAP_HOST_PAUSE=4 xcodebuild test-without-building … | while IFS= read -r line; do case "$line" in *SNAP-HOST-READY*) name=${line##*SNAP-HOST-READY } duoctl -d "$SIM" screenshot "out/$name.png";; esac done ``` On those runs the agent skipped the hittable check and rotated the interface to portrait, and the test then stepped through all six store frames on the open device, in English and Spanish. ## The UI test scrolled the field above the sheet's bar Back to the plate test. With Save fixed, it failed with "Neither element nor any descendant has keyboard focus". The scroll loop had pushed the plate field up to y=75, and the sheet's toolbar starts at y=106. The swipes carried the field past the bar and the tap missed it; I didn't measure why it happens on the Duo and not on the iPhone. An agent changed the loop to swipe slowly, up or down, until the field sits below the bar, and reran it: it passes on the Duo and on an iPhone 17 Pro. ## App Store Connect has its own iPhone Duo slot Apple will require these screenshots [starting in April 2027](https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications/) for any app using the iOS 27.1 SDK or later. The slot takes the outer screen at 1398 × 2034 and the inner one at 2007 × 2853 in portrait, plus landscape versions. Product pages that include them show a badge saying the app is made for iPhone Duo. The simulator's screens are exactly those sizes, so the raw frames fit. One catch: Apple doesn't accept screenshots with an alpha channel, and my inner-screen PNGs from the simulator had one. My upload tool refused them before sending them, and converting to JPEG fixed it. ## What still doesn't work - **The first tap.** With the number pad showing, the first tap on "More details" in the add-vehicle form doesn't open it on the Duo. On the iPhone 17 Pro it does. I haven't figured out why. - **Tent posture.** App Store Connect only asks for the outer and inner screens, so I didn't check tent mode at all. - **The trade-off of the fix.** `toolbarVerticalBehavior(.disabled)` opts out of the vertical bar Apple designed for the closed device. My buttons are back, but my sheets don't behave the way Apple intended on the Duo. - **The simulator isn't the device.** On X, iOS developer [Ehsan Azish](https://x.com/ehzish) wrote that a Duo layout that looked right with the Xcode release candidate was wrong on the physical device: the tab bar fell back to the regular iPhone layout. I asked whether the simulator showed it too. "Only on device." Until I get my hands on one, everything above is "works in the simulator". ## First move If you build your app with the iOS 27.1 SDK: - **Run your sheet UI tests on a fresh Duo simulator, headless.** The vanishing-toolbar bug never appears on a regular iPhone. - **If buttons vanish, try `.toolbarVerticalBehavior(.disabled)`** on the content inside the sheet's `NavigationStack`. It keeps the buttons and gives up Apple's closed-device bar. - **Leave `screenConfig` out of your scripts.** It crash-loops SpringBoard. - **Check every simulator's name against your cleanup rules.** Mine matched one, and another agent's cleanup deleted it. - **Capture the inner screen from the Mac, not from XCTest,** and export JPEG for App Store Connect. ## Sources - Sarun Wongpatcharapakorn, [Sheets and fold avoidance on iPhone Duo](https://sarunw.com/posts/sheets-and-fold-avoidance-on-iphone-duo/), read November 5, 2026. - Blake Crosley, [Xcode 27.1 Beta: Your App in the iPhone Duo Simulator](https://blakecrosley.com/blog/xcode-27-1-beta-iphone-duo-simulator), read November 5, 2026. - Apple, [Screenshot specifications](https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications/), read November 5, 2026. - [duoctl](https://github.com/skarol/duoctl), tag v0.2.1. - What I based this on: SpringBoard `.ips` files in `~/Library/Logs/DiagnosticReports/`, the xcresult bundles of each run and Rydger's commits of November 5, 2026. The repo is private. **Related reading:** [Claude Code skills vs subagents and the shared simulator](/en/blog/claude-code-skills-vs-subagents/) and [the overloaded Mac and the agent's botched report](/en/blog/claude-code-ios-parallel-agents-crash-reports/). --- **P.S.** Have you tested on a real iPhone Duo yet? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz) what the simulator got wrong. --- URL: https://www.oscargallegoruiz.com/blog/simulador-iphone-duo-tests-ui/ Lang: es # Simulador del iPhone Duo: tests de SwiftUI sin ventana > Tests de UI de Rydger en el simulador del iPhone Duo: Cancelar y Guardar desaparecían, SpringBoard se colgaba en bucle y la pantalla interior pedía un apaño **Respuesta corta:** en el simulador del iPhone Duo, Cancelar y Guardar desaparecían de las hojas de mi app en cuanto el formulario hacía scroll. El agente que llevaba lo del Duo probó ocho arreglos y ninguno funcionó. Una línea sí: `toolbarVerticalBehavior(.disabled)`. Por el camino me tocó además un SpringBoard colgándose en bucle, un simulador que me borró mi propio script de limpieza y un test que no conseguía tocar un campo. Va todo abajo, con su arreglo. La app es Rydger, en SwiftUI y con iOS 18 como versión mínima. El entorno: Xcode 27.2, el runtime de iOS 27.1 y el simulador sin ventana, que es como mis agentes lanzan todos los tests. ## Cancelar y Guardar desaparecían en cuanto el formulario hacía scroll Las pantallas de alta y edición de vehículo de Rydger son una hoja: un `NavigationStack`, un `Form` y una barra con `.cancellationAction` y `.confirmationAction`. En un simulador de iPhone 17 Pro pasan los dos tests de alta de vehículo. En el Duo fallaban los dos. El que edita la matrícula moría con «Failed to tap Save», y el árbol de accesibilidad del fallo mostraba la barra de navegación vacía. El agente que llevaba la historia del Duo lo reprodujo con un `Form` mínimo y, según su propio informe, probó ocho variantes: quitar el fundido de arriba, el indicador de arrastre y el botón Done del teclado, tocar `contentMargins`, el elemento `.principal` de la barra, `safeAreaInset`, `presentationSizing(.page)` y forzar `toolbarVisibility`. Ninguna devolvió los botones. Entregó la rama con el bug anotado como pendiente. ## Un modificador los devuelve La búsqueda de Grok me llevó al [post de Sarun sobre las hojas en el Duo](https://sarunw.com/posts/sheets-and-fold-avoidance-on-iphone-duo/): con el móvil cerrado y en vertical, iOS pasa los botones de cerrar y confirmar de las hojas a una barra vertical, y ese comportamiento se puede desactivar. Él recomienda desactivarlo en hojas con un solo botón. Las mías tienen dos. En el simulador nunca vi la barra vertical, solo botones que desaparecían al hacer scroll, pero al desactivarla volvieron. El modificador viene en el SDK de iOS 27.2 y funciona desde iOS 27.1: ```swift private extension View { /// iPhone Duo (iOS 27.1+) moves a sheet's Cancel and Save into a vertical toolbar, /// and on the 27.1 simulator both vanish once the form scrolls: keep the usual bar. @ViewBuilder func horizontalToolbar() -> some View { if #available(iOS 27.1, *) { toolbarVerticalBehavior(.disabled) } else { self } } } ``` Con eso puesto en la hoja compartida, en la siguiente pasada Cancelar y Guardar seguían en la barra después del scroll (y=112 en el árbol de accesibilidad). El test de la matrícula siguió fallando, por otro motivo que cuento más abajo. Le pedí a Grok que buscara este bug en X y en la web entre el 10 de septiembre y el 5 de noviembre y no encontró a nadie que lo mencionara. Así que no sé si Apple lo considera un bug o si es el comportamiento previsto. ## Simular el pliegue con simctl colgó SpringBoard en bucle Para capturar la pantalla interior, el agente intentó «abrir» el móvil encendiendo y apagando sus pantallas con `xcrun simctl io screenConfig … power`. A partir de ahí, el SpringBoard del simulador se reiniciaba más o menos cada cinco segundos: 14 crash reports entre las 18:18:50 y las 18:20:20, todos menos el primero con una aserción en `-[SBMainDisplayConfigurationTransformer transformDisplayConfiguration:]`, y cada uno con su aviso de macOS en mi pantalla. Una hora después, otro agente lanzó la misma llamada a `screenConfig` en un segundo simulador de Duo, y nada más hacerlo ese también entró en bucle. Un simulador de Duo nuevo, en el que nadie usó `screenConfig`, arrancó sin ventana con `simctl boot` y no dejó ni un fallo de SpringBoard. A Blake Crosley [le pasó algo parecido](https://blakecrosley.com/blog/xcode-27-1-beta-iphone-duo-simulator) en septiembre: apagar la pantalla exterior tumbaba la interfaz del sistema del simulador. Nada de `screenConfig` para simular el pliegue. ## Mi propio script de limpieza me borró el simulador Después, el simulador nuevo se me apagó dos veces y acabó desapareciendo de `simctl list`. Mi repo tiene un script que limpia los worktrees terminados, y su modo `--orphans` apaga y borra cualquier simulador que se llame «Rydger Agent » si ese worktree ya no existe. Yo había llamado al de pruebas «Rydger Agent duo-check», y en el mismo Mac había otras sesiones de agentes recogiendo lo suyo. A las 20:35, otra sesión de agentes que limpiaba sus worktrees lo lanzó, y en su salida aparecía «Simulator duo-check»: el nombre cumplía la regla y no existía ningún worktree con ese nombre. Los dos apagados de antes no sé explicarlos. Uno llamado «Duo Capture (Rydger)» ha sobrevivido desde entonces. ## No hay forma oficial de plegar el simulador `simctl` no tiene ningún comando de postura. Hay un [hilo en los foros de Apple](https://developer.apple.com/forums/thread/847883) que lo pide y Apple no ha contestado. En Xcode 27.2 la ventana del simulador es Device Hub, que tiene los botones de postura, pero mi herramienta de automatización no lograba pulsar dentro de su ventana: no identificaba cuál era. Lo que funcionó fue [duoctl](https://github.com/skarol/duoctl), una herramienta pequeña de código abierto que manda eventos de bisagra al simulador con llamadas HID privadas. Un agente leyó el código antes de ejecutarlo: un script de Python que llama a `xcrun` y `codesign` y compila un helper que corre dentro del simulador, sin tocar la red. Funciona sin ventana con Xcode 27.2: ```text $ duoctl -d open && duoctl -d state "hingeAngle": 180.0, "activeScreen": "inner", "orientation": "landscape", "sizePoints": [951.0, 669.0] ``` Como usa API privada, la próxima versión de Xcode puede cargárselo. Hoy por hoy es la única forma que he encontrado de abrir el móvil desde un script. ## Captura la pantalla interior desde el Mac, no desde XCTest Con el móvil abierto hay dos trampas más: - **Capturas.** [Otro desarrollador cuenta](https://x.com/vladimirchama/status/2114720281101287768) que las capturas de XCTest de la pantalla interior salen en negro, y solo se dibuja la pantalla que está encendida, así que ni las miré. `simctl io screenshot --display=` desde el Mac sí funciona, y `duoctl screenshot` elige la pantalla por ti. - **Toques.** En la pantalla interior, XCUITest nunca marcó mis elementos como pulsables (`isHittable`), ni girando a vertical, aunque `element.tap()` sí llegaba. Así que el test de capturas de la tienda se para en cada pantalla y la foto la hace el Mac: ```swift func snap(_ app: XCUIApplication, _ name: String) { if let pause = ProcessInfo.processInfo.environment["SNAP_HOST_PAUSE"].flatMap(Double.init) { print("SNAP-HOST-READY \(name)") Thread.sleep(forTimeInterval: pause) } // ... the usual XCTAttachment } ``` ```bash TEST_RUNNER_SNAP_HOST_PAUSE=4 xcodebuild test-without-building … | while IFS= read -r line; do case "$line" in *SNAP-HOST-READY*) name=${line##*SNAP-HOST-READY } duoctl -d "$SIM" screenshot "out/$name.png";; esac done ``` En esas pasadas, el agente se saltó la espera a que el elemento fuera pulsable y giró la interfaz a vertical; así el test recorrió las seis pantallas de la tienda con el móvil abierto, en inglés y en español. ## El test subía el campo por encima de la barra de la hoja Vuelvo al test de la matrícula. Con Guardar arreglado, fallaba con «Neither element nor any descendant has keyboard focus». El bucle de scroll había subido el campo de la matrícula hasta y=75, y la barra de la hoja empieza en y=106. Los deslizamientos llevaban el campo más allá de la barra y el toque no llegaba a él; no medí por qué pasa en el Duo y no en el iPhone. Un agente cambió el bucle para que deslice despacio, hacia arriba o hacia abajo, hasta dejar el campo por debajo de la barra, y lo volvió a pasar: funciona en el Duo y en un iPhone 17 Pro. ## App Store Connect tiene un hueco propio para el iPhone Duo Apple pedirá estas capturas [a partir de abril de 2027](https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications/) a toda app compilada con el SDK de iOS 27.1 o posterior. El hueco admite la pantalla exterior a 1398 × 2034 y la interior a 2007 × 2853 en vertical (y sus versiones en horizontal), y las fichas que las incluyen muestran una insignia que indica que la app está hecha para el iPhone Duo. Las pantallas del simulador miden justo eso, así que las capturas en bruto encajan. Un detalle: Apple no acepta capturas con canal alfa y los PNG de la pantalla interior lo tenían. Mi herramienta de subida los rechazó antes de enviarlos; en JPEG pasaron. ## Lo que todavía no funciona - **El primer toque.** Con el teclado numérico abierto, el primer toque en «Más detalles» del alta de vehículo no abre la pantalla en el Duo. En el iPhone 17 Pro sí. No he encontrado por qué. - **La postura de tienda de campaña.** App Store Connect solo pide la pantalla exterior y la interior, así que ni la he mirado. - **El precio del arreglo.** `toolbarVerticalBehavior(.disabled)` renuncia a la barra vertical que Apple diseñó para el móvil cerrado. Los botones han vuelto, pero las hojas no se comportan en el Duo como Apple pensó. - **El simulador no es el dispositivo.** En X, el desarrollador de iOS [Ehsan Azish](https://x.com/ehzish) contó que un diseño para el Duo que se veía bien con la release candidate de Xcode salió mal en el dispositivo físico: la barra de pestañas volvía a la de un iPhone normal. Le pregunté si también pasaba en el simulador: «solo en el dispositivo». Hasta que tenga uno en la mano, todo lo de arriba es «funciona en el simulador». ## Por dónde empezar Si compilas tu app con el SDK de iOS 27.1: - **Pasa los tests de UI de tus hojas por un simulador de Duo nuevo, sin ventana.** En un iPhone normal no verás que desaparecen los botones. - **Si desaparecen, prueba `.toolbarVerticalBehavior(.disabled)`** en el contenido del `NavigationStack` de la hoja. Recuperas los botones y pierdes la barra que Apple pensó para el móvil cerrado. - **Deja `screenConfig` fuera de tus scripts.** Cuelga SpringBoard en bucle. - **Compara el nombre de cada simulador con tus reglas de limpieza.** El mío encajaba, y la limpieza de otro agente lo borró. - **Captura la pantalla interior desde el Mac, no desde XCTest,** y exporta en JPEG para App Store Connect. ## Fuentes - Sarun Wongpatcharapakorn, [Sheets and fold avoidance on iPhone Duo](https://sarunw.com/posts/sheets-and-fold-avoidance-on-iphone-duo/), leído el 5 de noviembre de 2026. - Blake Crosley, [Xcode 27.1 Beta: Your App in the iPhone Duo Simulator](https://blakecrosley.com/blog/xcode-27-1-beta-iphone-duo-simulator), leído el 5 de noviembre de 2026. - Apple, [Screenshot specifications](https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications/), leído el 5 de noviembre de 2026. - [duoctl](https://github.com/skarol/duoctl), etiqueta v0.2.1. - En qué me baso: los `.ips` de SpringBoard en `~/Library/Logs/DiagnosticReports/`, los xcresult de cada pasada y los commits de Rydger del 5 de noviembre de 2026. El repo es privado. **Lectura relacionada:** [subagentes o skills en Claude Code y el simulador compartido](/blog/subagentes-o-skills-claude-code/) y [el Mac saturado y el informe que falló](/blog/claude-code-ios-agentes-paralelo-crash-reports/). --- **P.D.** ¿Has probado ya en un iPhone Duo de verdad? Cuéntame en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz) en qué te engañó el simulador. --- URL: https://www.oscargallegoruiz.com/en/blog/claude-code-ios-parallel-agents-crash-reports/ Lang: en # Claude Code on iOS: spotted the overload, botched the report > Several Claude Code agents ran in parallel on my iOS app and maxed out a 12-core Mac. One spotted it in a crash report. Its summary had three false claims. **Short answer:** On Sunday I had several Claude Code agents working on Rydger, my iOS app, and my 12-core Mac hit a load average of 422. One agent read a single line in a crash report and saw right away that the machine was saturated. Its explanation, never fully confirmed: too many simulator boots and builds at once. Then the same agent wrote me a summary with three false claims, and I came close to publishing it as this post. It started with a crash report from MobileCal, the iOS Calendar app, running inside the simulator. When we counted later, the reports folder held 141 of them from the past two days. I pasted the MobileCal one into an agent and asked what was going on. The summary I got back later even suggested a title (in Spanish, translated here): "A load of 422 and 74 zombie processes." There were no zombies. ## One line in the MobileCal report showed the CPU was maxed out The report was a `0x8BADF00D`, the iOS watchdog's code, which Apple says is pronounced "ate bad food." MobileCal had 30 seconds to launch and ran out of time. The useful part was near the top, in the termination reason, under `WatchdogCPUStatistics`: ```text "Elapsed total CPU time (seconds): 360.720 (user 292.190, system 68.530), 100% CPU", "Elapsed application CPU time (seconds): 1.802, 0% CPU" ``` In those 30 seconds of wall-clock time, MobileCal got 1.8 seconds of CPU while the system as a whole used 360. According to [Apple's docs](https://developer.apple.com/documentation/xcode/addressing-watchdog-terminations), the total covers every process on every core, and a low number for the app means it was mostly idle, waiting on system resources. 360 CPU seconds in 30 wall-clock seconds works out to almost 12 cores busy the entire time, which is every core in my M2 Max. The thread running when the watchdog fired was still in `dyld_sim`, loading libraries. MobileCal never got as far as `main`. The agent spotted that and went straight to the machine instead of the code. Its first command line included `uptime` and a list of the booted simulators: ```text 11:53 up 13 days, 2:17, 2 users, load averages: 422.71 304.75 191.54 ``` Three simulators were booted, at least two agents were working, and a unit test suite was building in the background. Three of the top four CPU consumers belonged to the simulator runtime and had been running for only 2 to 4 seconds; the fourth was `ANECompilerService`. By the agent's own account, it had settled on an explanation about five minutes later: too many simulator boots and builds at once for 12 cores. That's the most likely story, but I didn't measure how much each part contributed. Next time simulator crash reports pile up, I'll open the `0x8BADF00D` ones first and compare the app's CPU time to the total. If the total gets close to wall-clock time multiplied by the core count, the problem is the Mac. That's one case, one report out of 141, so I treat it as a first check, not a rule. ## The other 140 reports didn't point at the cause Another agent recounted them on the Mac that afternoon: 139 of the 141 came from simulators, spread across 20 different simulators. - **94 `Trace/BPT trap: 5`** from simulator daemons such as `intelligencetasksd` (38 of them) and `AppIntentsLiveEntityService`. They kept showing up after the load came down, so overload isn't required to trigger them. Nobody has looked into why they crash yet. In chat, the agent blamed the `intelligencetasksd` ones on an iOS 27 runtime bug without checking. - **44 `XPC_EXIT_REASON_SIGTERM_TIMEOUT`**: daemons that don't exit in time when a simulator shuts down. I'd guess there are more of them under heavy load, but I haven't measured it. - **A single `0x8BADF00D`**, the MobileCal one. - **Two from the Mac itself**: an `upload-symbols` bus error nobody has analyzed, and one from a terminal multiplexer. ## The screenshot script rebooted the simulator for every language In my last post on subagents I wrote that [every worktree needs its own simulator](/en/blog/claude-code-skills-vs-subagents/). The agent capturing App Store screenshots was in its own worktree, but it was using the main checkout's simulator. Its script, `capture.sh`, did this for each of the 12 languages: shut down the simulator, boot it, and run `xcodebuild test`, which runs an incremental build step on every call. A comment explained why: back-to-back UI test runs without a reboot failed to launch the test runner with "Application failed preflight checks" (Busy). The language, though, already reached the app as a launch argument (`-AppleLanguages`), so no language ever needed its own build. The agent changed it to build once with `build-for-testing`, run each language with `test-without-building`, and reboot only before a retry, in case the Busy error comes back. The part that matters is still unchecked: nobody has run a full 12-language batch on the new script while watching the load, and there are no timings for the old one. And another problem is still open: capping how many simulators boot at once on the Mac. ## The agent's summary had three false claims Along the way, the agent found 74 Crashlytics `upload-symbols` processes. Firebase's `run` script forks one into the background with `&` on nearly every build. The oldest had been alive for 10 days. All true so far. The summary it gave me in chat also said: 1. **They were zombie processes.** They were sleeping (state S) at 0% CPU, with their parent still alive, so they were simply hung. And a process that uses no CPU doesn't add to the load. 2. **After the fix, the load dropped to 3.6.** It dropped on its own. It spiked to 148 at 12:03 when the agent reran the full test suite, then was down to around 8 by 12:09, about 11 minutes before anyone killed those processes. It came down on its own as the simulator boots and builds wound down. 3. **They were waiting for a dSYM that never shows up in Debug.** Rydger's Debug builds do produce a dSYM. I still don't know why they hung. All three match the story you'd expect: processes piling up sound like zombies, and a load drop right after a fix looks like the fix worked. Those sentences were going to be the title and the takeaways of this post. Another takeaway said the StoreKit tests failed at load 400 and passed at load 10. They failed in one run out of three, and one of the passing runs was a full suite with the load at 148, measured right as it finished. ## Twenty-three questions got the agent to retract all three claims Before writing, I sent the agent 23 questions and one instruction: paste the literal output of every command, and if something wasn't measured, say so instead of estimating. It came back with a document that opened (in Spanish) with "Corrections before we start" and retracted all three. It also fixed a comment it had left in Rydger's code repeating the dSYM story. This is a different problem from the one in my [AI agent verifier post](/en/blog/ai-agent-verifier-false-claims/). There, a second agent checks what's said about the code against the code, which is still there tomorrow. A machine's state isn't. That 422 load average can't be measured again, and there's no Activity Monitor screenshot. If nobody saves the `uptime` and `ps` output while the incident is live, the agent's summary becomes the only record. ## Even the corrected report miscounted The corrected document listed 92 SIGTRAP reports (84 + 8) and 41 SIGTERM timeouts (27 + 14). When another agent recounted them, with a loop that reads the `indicator` field in each `.ips` file, it got 94 and 44. The gap is small, but it says something: the questions made the document more honest about what wasn't measured, not more accurate about what was. And I got lucky: I only asked those questions because I was writing a post. ## Save the output before you ask for the summary While the incident is still live, save the output to a file in the repo. It's the one part you can't rerun. This is enough: ```bash { date; uptime; xcrun simctl list devices booted; ps -Ao pid,ppid,stat,pcpu,etime,command -r | head -40; ls -lt ~/Library/Logs/DiagnosticReports | head -50; } > incident-$(date +%F-%H%M).txt ``` Then, when the agent hands you its summary, send this: ```text For every number and every cause in your summary, cite the line in the evidence file that proves it. Mark anything that isn't there or that you inferred. ``` Before you accept it, count one number with your own command, or have an agent that didn't write the summary do it. The second agent's recount didn't match. ## Better still: let the runner save it On LinkedIn, [Roberto Gómez](https://www.linkedin.com/in/rgmez/), an iOS developer, pointed out the weak spot in the command above: it depends on someone remembering to run it while the incident is still live. Put it in a skill for the agent and the agent can skip it or get there too late. The suggestion was to take the capture away from the agent and put it in the script that launches the builds: a snapshot of the machine before starting and another whenever something fails. That way the only evidence doesn't depend on the same agent that later explains what happened. It's the better version, and I'm applying it to Rydger and WealthSim. The idea fits in a fifteen-line wrapper: ```bash #!/bin/bash # Snapshot before the run, and again if it fails or gets killed snap() { mkdir -p .incidents { echo "# $1 $(date '+%F %T') ${2:+exit=$2}" uptime; sysctl -n hw.ncpu xcrun simctl list devices booted ps -Ao pid,ppid,stat,pcpu,etime,command -r | head -40 ls -lt ~/Library/Logs/DiagnosticReports | head -50 } > ".incidents/$(date +%Y%m%d-%H%M%S)-$1.txt" 2>&1 } snap start "$@" & child=$! trap 'kill -TERM $child; snap killed TERM; exit 143' TERM INT wait $child; code=$? [ $code -ne 0 ] && snap fail $code exit $code ``` Put it in front of your usual command: `./run-with-capture.sh xcodebuild test -scheme MyApp -destination "id=$udid"`, and add `.incidents/` to `.gitignore`. Three details matter: - **It returns the command's own exit code**, so whatever depends on it keeps working. I tested it with a run that passes, one that fails with 3 and one I killed halfway: it returned 0, 3 and 143. - **The failure snapshot comes before any cleanup or retry.** If your script shuts the simulator down or retries the test, the snapshot has to happen first, or you'll never see what was there. - **It also captures when the run gets killed.** A timeout or a Ctrl-C is exactly when the machine was at its worst. A fuller version should list only the crash reports newer than the start of the run, and prune old snapshots so the folder doesn't grow forever. None of this prevents the overload. For that, Roberto suggests starting with one build or test run at a time through a shared runner, while the other agents keep reading and editing code, and raising the limit only after measuring. What the capture changes is that when you ask the agent for its summary, the evidence file already exists and nobody had to remember to save it. ## Sources - Apple: [Addressing watchdog terminations](https://developer.apple.com/documentation/xcode/addressing-watchdog-terminations), read November 1, 2026. - My evidence: the `.ips` files in `~/Library/Logs/DiagnosticReports/`, the agent's `uptime` and `ps` output, and Rydger's scripts. The repo is private. **Related reading:** [Claude Code skills vs subagents and the shared simulator](/en/blog/claude-code-skills-vs-subagents/) and [the verifier that sent back four builds out of five](/en/blog/ai-agent-verifier-false-claims/). --- **P.S.** Has an agent ever handed you a convincing summary that fell apart once you asked for proof? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/claude-code-ios-agentes-paralelo-crash-reports/ Lang: es # Claude Code en iOS: vio el Mac saturado y falló en el informe > Varios agentes de Claude Code en paralelo saturaron mi Mac con una app de iOS. Uno lo vio en un crash report; su resumen traía tres afirmaciones falsas **Respuesta corta:** el domingo tenía varios agentes de Claude Code trabajando a la vez en Rydger, mi app de iOS, y el Mac, con 12 núcleos, llegó a una carga de 422. Un agente leyó una línea de un crash report y vio enseguida que la máquina estaba saturada; su explicación, que nadie ha confirmado del todo, fue que había demasiados arranques de simulador y builds a la vez. Después escribió un resumen con tres afirmaciones falsas, y casi lo convierto en este artículo. Todo empezó con un crash report de MobileCal, el calendario de iOS, dentro del simulador. Cuando contamos después los de la carpeta, había 141, de dos días. Le pegué el de MobileCal a uno de los agentes y le pregunté qué pasaba. El resumen que me dio después traía hasta título para el artículo: «Una carga de 422 y 74 procesos zombi». No había ningún zombi. ## Una línea del informe de MobileCal ya decía que faltaba CPU El informe era un `0x8BADF00D`, el código del watchdog de iOS, que Apple pronuncia «ate bad food». MobileCal tenía 30 segundos para arrancar y no le dio tiempo. Lo útil estaba arriba, en el motivo de terminación, bajo `WatchdogCPUStatistics`: ```text "Elapsed total CPU time (seconds): 360.720 (user 292.190, system 68.530), 100% CPU", "Elapsed application CPU time (seconds): 1.802, 0% CPU" ``` En esos 30 segundos de reloj, MobileCal usó 1,8 segundos de CPU y el sistema entero, 360. Según la [documentación de Apple](https://developer.apple.com/documentation/xcode/addressing-watchdog-terminations), la primera cifra suma todos los procesos en todos los núcleos, y si la de la app es baja, la app estaba casi todo el rato parada esperando recursos del sistema. 360 segundos de CPU en 30 de reloj son casi 12 núcleos ocupados todo el rato, los 12 de mi M2 Max. El hilo que estaba en marcha cuando lo mataron seguía en `dyld_sim` cargando bibliotecas dinámicas: MobileCal ni siquiera llegó a `main`. El agente lo vio y fue directo a mirar la máquina en vez del código. Lo primero que lanzó incluía `uptime` y la lista de simuladores arrancados: ```text 11:53 up 13 days, 2:17, 2 users, load averages: 422.71 304.75 191.54 ``` Había tres simuladores arrancados, al menos dos agentes trabajando y una suite de tests compilando en segundo plano. Tres de los cuatro procesos que más CPU consumían eran del runtime del simulador y llevaban entre 2 y 4 segundos vivos; el otro era `ANECompilerService`. Según su propio resumen, unos cinco minutos después el agente tenía su explicación: demasiados arranques de simulador y builds a la vez para 12 núcleos. Es la más probable, pero no medí cuánto aportaba cada cosa. La próxima vez que me salgan crash reports del simulador, abriré primero los `0x8BADF00D` y compararé la CPU de la app con la total. Si la total se acerca al tiempo de reloj multiplicado por los núcleos, el problema es el Mac. Es un solo caso, uno de 141 informes, así que lo tomo como primera comprobación y no como regla. ## Los otros 140 informes no señalaban la causa Otro agente los volvió a contar en el Mac ese mismo mediodía: 139 de los 141 venían de simuladores, de 20 simuladores distintos. - **94 `Trace/BPT trap: 5`**, de daemons del simulador como `intelligencetasksd` (38) o `AppIntentsLiveEntityService`. Siguieron saliendo con la carga ya baja, así que no hace falta saturación para que salgan. Nadie ha mirado todavía por qué fallan; en el chat, el agente atribuyó los de `intelligencetasksd` a un bug del runtime de iOS 27 sin comprobarlo. - **44 `XPC_EXIT_REASON_SIGTERM_TIMEOUT`**: daemons que no terminan a tiempo cuando se apaga el simulador. Que salgan más con la máquina saturada es una hipótesis razonable, pero no la he medido. - **Un solo `0x8BADF00D`**, el de MobileCal. - **Dos del propio Mac**: un Bus error de `upload-symbols`, que nadie ha analizado, y otro de un multiplexor de terminal. ## El script de capturas reiniciaba el simulador en cada idioma En el post anterior sobre subagentes conté que [cada worktree necesita su propio simulador](/blog/subagentes-o-skills-claude-code/). El agente que hacía las capturas para el App Store trabajaba en su propio worktree, pero usaba el simulador del checkout principal. Su script, `capture.sh`, hacía esto en cada uno de los 12 idiomas: apagar el simulador, arrancarlo y lanzar `xcodebuild test`, que pasa por un build incremental en cada llamada. El comentario lo justificaba así: si se lanzaban tests de UI seguidos sin reiniciar, el runner no arrancaba y daba «Application failed preflight checks» (Busy). El idioma, en cambio, ya le llegaba a la app como argumento de lanzamiento (`-AppleLanguages`), así que ningún idioma necesitaba su propia compilación. El agente lo cambió para compilar una vez con `build-for-testing`, ejecutar cada idioma con `test-without-building` y reiniciar solo antes de un reintento, por si vuelve el error del Busy. Lo importante no está comprobado: nadie ha lanzado todavía una tanda de 12 idiomas con el script nuevo mirando la carga, y del viejo no hay tiempos. Y otro problema sigue sin resolver: limitar cuántos simuladores arrancan a la vez en el Mac. ## El resumen del agente tenía tres afirmaciones falsas De paso, el agente encontró 74 procesos `upload-symbols` de Crashlytics. Los deja en segundo plano el script `run` de Firebase, con un `&`, casi en cada build. El más antiguo llevaba 10 días vivo. Hasta ahí, todo cierto. Pero el resumen que me dio en el chat decía además: 1. **Que eran procesos zombi.** Estaban dormidos (estado S), al 0 % de CPU y con su proceso padre vivo: colgados. Y un proceso que no usa CPU no aporta carga. 2. **Que tras el arreglo la carga bajó a 3,6.** Bajó sola. Hubo un repunte a 148 a las 12:03, cuando el agente volvió a lanzar la suite completa de tests, y a las 12:09 ya rondaba 8, unos 11 minutos antes de matar esos procesos. Fue bajando sola mientras terminaban los arranques y los builds. 3. **Que esperaban un dSYM que en Debug nunca llega.** Los builds Debug de Rydger sí generan el dSYM. Sigo sin saber por qué se colgaban. Las tres encajan con lo que esperarías leer: procesos que se acumulan suenan a zombis, y una carga que baja después de un arreglo parece obra del arreglo. Esas frases iban a ser el título y las lecciones del artículo. Otra lección decía que los tests de StoreKit fallaban con carga 400 y pasaban con carga 10. Fallaron en una ejecución de tres, y una de las que pasaron fue una suite completa con la carga en 148, medida justo al terminar. ## Las 23 preguntas retiraron las tres frases Antes de escribir le mandé 23 preguntas y una instrucción: pega la salida literal de cada comando, y si algo no se midió, dilo y no lo estimes. Volvió con un documento que empezaba por «Correcciones antes de empezar» y retiraba las tres frases. También corrigió el comentario que había dejado en el código de Rydger, que repetía lo del dSYM. No es el mismo caso que el del [verificador de agentes](/blog/verificador-agente-ia-mentira/). Allí otro agente compara lo que se dice del código con el propio código, que sigue ahí al día siguiente. El estado de una máquina no sigue ahí. La carga de 422 ya no se puede volver a medir, y no hay ninguna captura del Monitor de Actividad. Si la salida de `uptime` y `ps` no se guarda mientras el incidente sigue en curso, el resumen del agente se queda como la única prueba. ## Hasta el documento corregido contaba mal El documento corregido ponía 92 informes SIGTRAP (84 + 8) y 41 de SIGTERM (27 + 14). Cuando otro agente los recontó, con un bucle que lee el campo `indicator` de cada `.ips`, salieron 94 y 44. La diferencia es pequeña, pero dice algo: las preguntas hicieron el documento más honesto con lo que no se midió, no más exacto con lo que sí. Y tuve suerte: solo hice esas preguntas porque iba a publicar un artículo. ## Guarda la salida antes de pedirle el resumen Mientras el incidente siga en curso, guarda la salida en un fichero del repo, porque es lo único que no se puede repetir. Con esto basta: ```bash { date; uptime; xcrun simctl list devices booted; ps -Ao pid,ppid,stat,pcpu,etime,command -r | head -40; ls -lt ~/Library/Logs/DiagnosticReports | head -50; } > incidente-$(date +%F-%H%M).txt ``` Después, cuando el agente te dé el resumen, mándale esto: ```text Para cada cifra y cada causa del resumen, cita la línea del fichero de pruebas que la demuestra. Si algo no está ahí o es una deducción, márcalo como tal. ``` Y antes de darlo por bueno, cuenta una cifra con tu propio comando, o pídeselo a un agente que no haya escrito el resumen. Al segundo agente, el recuento le salió distinto. ## Mejor todavía: que la guarde el runner [Roberto Gómez](https://www.linkedin.com/in/rgmez/), desarrollador de iOS, me señaló en LinkedIn el punto débil del comando anterior: depende de que alguien se acuerde de lanzarlo mientras el incidente sigue vivo. Si se lo pides al agente en una skill, se lo puede saltar o llegar tarde. La propuesta es sacar la captura del agente y meterla en el script que lanza los builds: una foto de la máquina antes de empezar y otra cada vez que algo falle. Así la única prueba no depende del mismo agente que luego explica lo que pasó. Es la versión buena, y la estoy aplicando en Rydger y en WealthSim. La idea cabe en un envoltorio de quince líneas: ```bash #!/bin/bash # Captura antes de la ejecución, y otra vez si falla o la matan snap() { mkdir -p .incidents { echo "# $1 $(date '+%F %T') ${2:+exit=$2}" uptime; sysctl -n hw.ncpu xcrun simctl list devices booted ps -Ao pid,ppid,stat,pcpu,etime,command -r | head -40 ls -lt ~/Library/Logs/DiagnosticReports | head -50 } > ".incidents/$(date +%Y%m%d-%H%M%S)-$1.txt" 2>&1 } snap start "$@" & child=$! trap 'kill -TERM $child; snap killed TERM; exit 143' TERM INT wait $child; code=$? [ $code -ne 0 ] && snap fail $code exit $code ``` Lo usas delante del comando de siempre: `./run-with-capture.sh xcodebuild test -scheme MiApp -destination "id=$udid"`. Mete `.incidents/` en el `.gitignore`. Tres detalles importan: - **Devuelve el mismo código de salida** que el comando, así que lo que dependa de él sigue funcionando. Lo he probado con una ejecución que acaba bien, una que falla con 3 y una que mato a mitad: devuelve 0, 3 y 143. - **La captura del fallo va antes de cualquier limpieza o reintento.** Si tu script apaga el simulador o reintenta el test, la foto tiene que salir antes, o ya no verás lo que había. - **Captura también cuando lo matan.** Un timeout o un Ctrl-C son justo los casos en que la máquina estaba peor. En una versión más completa conviene listar solo los crash reports posteriores al inicio de la ejecución y borrar las capturas antiguas para que la carpeta no crezca sin fin. Esto no evita la saturación. Para eso, Roberto propone empezar con un solo build o una sola ejecución de tests a la vez, a través de un runner compartido, mientras el resto de agentes sigue leyendo y editando código, y subir ese límite solo después de medir. Lo que cambia con la captura es que, cuando le pidas el resumen al agente, el fichero de pruebas ya existe y nadie ha tenido que acordarse de guardarlo. ## Fuentes - Apple: [Addressing watchdog terminations](https://developer.apple.com/documentation/xcode/addressing-watchdog-terminations), consultada el 1 de noviembre de 2026. - Caso propio: los informes `.ips` de `~/Library/Logs/DiagnosticReports/`, la salida de `uptime` y `ps` del agente, y los scripts de Rydger. El repositorio es privado. **Lectura relacionada:** [subagentes o skills y el simulador compartido](/blog/subagentes-o-skills-claude-code/) y [el verificador que devolvió cuatro de cinco](/blog/verificador-agente-ia-mentira/). --- **P.D.** ¿Algún agente te ha dado un resumen convincente que luego no aguantaba las pruebas? Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/claude-code-skills-vs-subagents/ Lang: en # Claude Code skills vs subagents: the shared simulator bug > Anthropic and an October paper question when subagents pay off. My case: parallel agents sharing one iOS simulator. When subagents still earn their place. **Short answer:** I'm keeping subagents, but I'm splitting work differently. Anthropic says to divide work by context, not by specialty, and an October paper finds that what breaks parallel subagents most is what they share. Mine broke on something as dumb as an iOS simulator. I now use subagents to read, search, and verify, and let them write in parallel only when each one has its own resources. Nine days ago I wrote up how I [hand Rydger stories to subagents](/en/blog/claude-code-subagents-stories-worktrees/). Rydger is my iOS and Android app for tracking car and motorcycle maintenance. Opus coordinates, Sonnet implements, every story gets its own worktree. Since then, two things have bugged me, both impressions I haven't measured: it burns a lot of tokens, and most of the time the whole thing feels like a black box, with the work spread across contexts I never see. This week, two pieces landed that seem to argue against that setup. An [Anthropic post](https://claude.com/resources/articles/building-agents-when-to-fold-subagents-into-your-main-agent-loop) from October 22 makes the case for folding subagents into the main agent as skills and tools. And a [paper](https://arxiv.org/abs/2610.10263), a preprint with one run per task, compares Codex, Claude Code, and Kimi Code with and without parallel subagents: on a 100-task sample of SWE-bench Verified, Claude Code drops from 83% to 59% when it's allowed to spawn them. Then there's my own failure: Rydger's UI tests kept failing for no reason whenever several agents ran them at once. ## The random red tests came from one shared virtual iPhone The simulator is the virtual iPhone Xcode runs UI tests on. Every worktree used the same one. Two `xcodebuild` runs on the same simulator corrupt its CoreData state, and perfectly good tests fail. On top of that, when the simulator was shut down, `xcodebuild` booted it and shut it down again on every run. About 28 seconds each time. The fix is one simulator per worktree, created on first use and left running. Rydger's script does more, but the idea fits in a few lines: ```bash # One simulator per worktree: created on first use, then left booted name="Agent $(basename "$(git rev-parse --show-toplevel)")" udid=$(xcrun simctl list devices available | grep -E "^ +$name \(" | grep -oE '[0-9A-F-]{36}' | head -1) [ -n "$udid" ] || udid=$(xcrun simctl create "$name" "iPhone 17 Pro") xcrun simctl bootstatus "$udid" -b >/dev/null xcodebuild test -scheme MyApp -destination "id=$udid" ``` A second script for UI tests builds once and spreads the test classes across four of the worktree's simulators, longest class first. Xcode's own parallel testing option still took 615 seconds: it clones and boots fresh simulators on every run, and it queued both screenshot classes on the same one. The screenshot class, which was half the total time, is now two classes that run at the same time. Since each worktree got its own simulator, I haven't seen a false failure: all 35 UI tests passed five runs in a row, though I never wrote down how often they failed before. The table measures something else, speed, which comes mostly from not booting the simulator on every run and from spreading the classes: | Run | Before | After | | --- | --- | --- | | UI tests (35 tests) | 1,062 s | 324–370 s | | Full unit run | 47–52 s | 19–26 s | | A single unit suite | 33 s | 8 s | No tests removed. The UI test time after the change varies by run, hence the range. The time isn't what bugs me. A red test stopped meaning "the code is wrong", and an agent that sees a red test goes and fixes the code. **Worktrees isolate files. Nothing else.** ## Anthropic keeps subagents and says to split by context The version making the rounds is "one agent with skills beats an orchestrator with subagents." The post is more careful than that, and worth reading in full before you delete anything. It's about agents built on Claude Platform for large companies, customer-facing ones, where every team ships its own subagent and a central team puts an orchestrator on top. Its examples are customer-facing enterprise agents, not coding agents. In those comparisons, a single agent with skills "frequently" came out ahead on quality, often at lower cost and latency. Frequently, not always. It keeps subagents for three cases: when the main agent's context gets bloated enough to hurt results, when parallel tasks need a fresh context you can throw away afterward, and when one agent can't pick the right tool or has conflicting instructions. It also calls them effective for verification, parallel work, and splitting permissions. The rule I'm taking away: if you split, split by context. Give each subagent a piece of work that needs little from the rest of the system and hands back a compact result. Split by problem type and you get what they call a telephone game, where every handoff loses fidelity. Give every team its own subagent and the architecture ends up as a copy of the org chart, Conway's law applied to agents. On context, my story split passes: a story is a chunk of work with a visible result, not "the iOS agent" and "the Android agent." On shared resources it failed, and that rule wouldn't have caught it. ## The paper's most common failure is shared state, and my simulator fits The setup is fair: subagents weren't forced. In concurrent mode each agent decided whether to spawn them; in sequential mode the delegation tools were turned off. 354 tasks, over 2,000 runs, and over $20,000 in API spend, with configurations frozen in July 2026. Claude Code ran Opus 5 and, in concurrent mode, `ultracode` with Dynamic Workflow, which isn't quite the same as spawning subagents with the Agent tool. The authors limit their claims to those agents and benchmarks. Claude Code's 83% to 59% on SWE-bench Verified is the headline number, and its decline across all benchmarks combined is statistically significant. With subagents, token use runs 1.4 to 3.3 times that of sequential mode, and mean runtime goes up in 14 of 15 agent-benchmark pairs. The paper's conclusion is that subagents pay off more the longer the task, and that they should be turned on when needed, not by default. For Claude Code, the four long-horizon benchmarks are mixed: it **improves** on two and drops from 42.7% to 26.7% on RepoZero. My stories look more like a bounded SWE-bench task than building a whole repo, so I'm assuming the bad half of the headline applies to me. The most useful part is their failure taxonomy. The biggest category, 33%, is shared state and merge: agents reading or modifying shared files or environments without coordinating. Lost global context is the smallest, 9%. A simulator several agents use at once fits that definition. The paper doesn't classify iOS simulators, so the comparison is mine. Cognition landed in a similar place in [its April post](https://cognition.com/blog/multi-agents-working): what works is several agents contributing intelligence while writes stay single-threaded. ## The black box is two summaries per task The [subagents docs](https://code.claude.com/docs/en/sub-agents) explain my other complaint. A subagent starts with a fresh, isolated context and doesn't see the conversation. The main agent writes it a delegation message summarizing the task, and the subagent returns only a summary. Whatever didn't make it into the first summary, the subagent never learns. Whatever didn't make it into the second, the main agent never sees. When something goes sideways, the full trace lives in the subagent's context, not yours. There's one exception I hadn't noticed: forks inherit the main conversation instead of starting fresh. For a task that leans on what you've already discussed, a fork loses less than a regular subagent. And every subagent counts against your usage limit, even when its work ends up in the trash. I haven't measured my own token spend, so I won't claim savings. ## Subagents read and verify; parallel writes only when nothing is shared Here's what I've already changed, merged in Rydger or already live in my skills: - **One simulator per worktree** and the UI test script described above. The script that removes a worktree also deletes its simulators. - **A fixed test order in the testing skill:** while iterating, `swift test` and only the suites the agent touched; the full unit suite once before each commit; UI tests once at merge. - **One fewer handoff in my agent-team skill.** A Haiku agent used to do the research and pass the facts to a Sonnet agent that implemented and re-checked them. Now the same agent researches and implements. Reviewers still run in parallel, but only one runs the tests; the rest just read. And this is how I'm splitting work from now on: - **Subagents to read.** "Find every place this function is used and give me the list" is the textbook case: the subagent reads lots of files, I just get the list. - **Subagents to verify.** A reviewer with a clean context that never saw how the code was written. - **Parallel writes only when nothing is shared.** Files, branches, generated files, simulators, ports. If something is shared, I separate it first or run the work in series. - **Team procedures in skills.** What used to live in a specialist subagent's prompt goes into a skill the main agent loads when it needs it. ## One project and one simulator don't settle anything My case is one project and one shared resource: I parallelized without checking what my agents shared, and that doesn't prove a single agent is better. And removing subagents breaks things too. Anthropic's example is a support agent with a shipping specialist: folding one subagent into another cut latency, but the agent started answering without asking that specialist for the delivery date. The failure only showed up in one of two runs, which is why they say to run every case more than once. ## Start by listing what your agents share Before you add or remove a subagent, write down what your agents use at the same time when they run in parallel: generated files, simulators, emulators, ports, local databases. Everything on that list needs its own copy per agent or has to run in series. That's what I did, just later than I should have. If you then want to drop a subagent, Anthropic suggests writing about ten end-to-end cases with the expected result first, running each one more than once with and without the subagent, and removing them one at a time. I haven't done that yet. If the version without the subagent scores the same or better, it goes. ## Sources - Anthropic: [Building agents: When to fold subagents into your main agent loop](https://claude.com/resources/articles/building-agents-when-to-fold-subagents-into-your-main-agent-loop) (October 22, 2026) and the [Claude Code subagents docs](https://code.claude.com/docs/en/sub-agents), read October 30, 2026. - Li, Li, Jiang, and Lou: [When Sub-Agents Work in Parallel](https://arxiv.org/abs/2610.10263), arXiv, October 7, 2026. Preprint. - Cognition: [Multi-Agents: What's Actually Working](https://cognition.com/blog/multi-agents-working), April 2026. - My own case: Rydger's simulator scripts and testing skill. The repo is private; the timings come from runs before and after the change. **Related reading:** [how I hand stories to subagents](/en/blog/claude-code-subagents-stories-worktrees/) and [why your agent fails without a harness](/en/blog/harness-engineering-why-your-agent-fails/). --- **P.S.** What were your parallel agents sharing that you hadn't noticed? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/subagentes-o-skills-claude-code/ Lang: es # Subagentes o skills en Claude Code: el fallo del simulador > Anthropic y un paper de octubre cuestionan cuándo compensan los subagentes. Mi caso: agentes en paralelo con un simulador de iOS compartido. Cuándo usarlos. **Respuesta corta:** no voy a dejar de usar subagentes, pero sí a repartirlos de otra forma. Anthropic recomienda dividir el trabajo por contexto y no por especialidad, y un paper de octubre encuentra que lo que más rompe a los subagentes en paralelo es lo que comparten. A mí me pasó con algo tan tonto como un simulador de iOS. Ahora uso subagentes para leer, buscar y verificar, y para escribir en paralelo solo cuando cada uno tiene sus propios recursos. Hace nueve días publiqué cómo [reparto entre subagentes las stories de Rydger](/blog/claude-code-subagentes-objetivos-stories/), mi app de iOS y Android para el mantenimiento de la moto o el coche. Opus coordina, Sonnet implementa, cada story va en su worktree. Desde entonces tengo dos quejas, las dos de impresión y sin medir: se van muchos tokens, y muchas veces todo parece una caja negra, con el trabajo repartido en contextos que no veo. Esta semana han llegado dos lecturas que parecen ir en contra de ese flujo. Un [post de Anthropic](https://claude.com/resources/articles/building-agents-when-to-fold-subagents-into-your-main-agent-loop) del 22 de octubre propone meter los subagentes dentro del agente principal como skills y tools. Y un [paper](https://arxiv.org/abs/2610.10263), todavía sin revisión por pares y con una sola ejecución por tarea, compara Codex, Claude Code y Kimi Code con y sin subagentes en paralelo: en una muestra de 100 tareas de SWE-bench Verified, Claude Code baja del 83% al 59% cuando puede lanzarlos. Y luego está mi fallo: las pruebas de UI de Rydger fallaban sin motivo cuando varios agentes las ejecutaban a la vez. ## Los tests rojos sin motivo venían de un iPhone virtual compartido El simulador es el iPhone virtual de Xcode donde se ejecutan las pruebas de UI. Todos los worktrees usaban el mismo. Dos ejecuciones de `xcodebuild` sobre el mismo simulador le corrompen el estado de CoreData, y fallan tests que no tienen ningún problema. Además, con el simulador apagado, `xcodebuild` lo encendía y lo apagaba en cada ejecución. Unos 28 segundos cada vez. El arreglo es darle a cada worktree su propio simulador, creado la primera vez y siempre encendido. El script de Rydger hace más cosas, pero la idea cabe en esto: ```bash # Un simulador por worktree: se crea la primera vez y se queda encendido name="Agent $(basename "$(git rev-parse --show-toplevel)")" udid=$(xcrun simctl list devices available | grep -E "^ +$name \(" | grep -oE '[0-9A-F-]{36}' | head -1) [ -n "$udid" ] || udid=$(xcrun simctl create "$name" "iPhone 17 Pro") xcrun simctl bootstatus "$udid" -b >/dev/null xcodebuild test -scheme MiApp -destination "id=$udid" ``` Para las pruebas de UI hay otro script que compila una vez y reparte las clases entre cuatro simuladores del worktree, empezando por la más larga. La opción de paralelismo de Xcode se quedaba en 615 segundos: crea y arranca simuladores nuevos en cada ejecución y metía las dos clases de capturas en el mismo. La clase de capturas, que era la mitad del tiempo, ahora son dos que se ejecutan a la vez. Desde que cada worktree tiene su simulador no me han vuelto a salir fallos falsos: las 35 pruebas de UI pasaron cinco veces seguidas, aunque no tengo apuntado cuántas veces fallaban antes. La tabla mide otra cosa, la velocidad, que viene sobre todo de no encender el simulador en cada ejecución y de repartir las clases: | Ejecución | Antes | Después | | --- | --- | --- | | Pruebas de UI (35 tests) | 1062 s | 324–370 s | | Pruebas unitarias completas | 47–52 s | 19–26 s | | Una sola suite unitaria | 33 s | 8 s | Sin quitar ningún test. El después de las pruebas de UI cambia según la ejecución, de ahí el rango. Lo que me molesta no es el tiempo. Es que un test rojo dejó de significar «el código está mal», y un agente que ve un test rojo intenta arreglar el código. **Los worktrees separan los ficheros; no separan nada más.** ## Anthropic mantiene los subagentes y pide dividir por contexto El resumen que circula es «un solo agente con skills gana a un orquestador con subagentes». El post es más matizado, y conviene leerlo entero antes de borrar nada. Habla de agentes construidos en Claude Platform para empresas grandes, de cara al cliente, donde cada equipo monta su subagente y un equipo central pone un orquestador encima. Sus ejemplos son agentes de cara al cliente, no de código. En sus comparativas, un agente con skills ganó a menudo en calidad, muchas veces con menos coste y latencia. A menudo, no siempre. Mantiene los subagentes para tres casos: cuando el contexto del agente principal empeora y se nota en los resultados, cuando hay tareas en paralelo con un contexto que se puede tirar al terminar, y cuando un solo agente no sabe elegir herramienta o tiene instrucciones contradictorias. Dice además que son buenos para verificar, para trabajar en paralelo y para separar permisos. La regla que me llevo: si divides, divide por contexto. Dale a cada subagente un trabajo que necesite poco del resto y que devuelva un resultado compacto. Cuando se divide por tipo de problema, lo describen como un teléfono escacharrado donde cada traspaso pierde fidelidad. Y cuando cada equipo tiene su subagente, la arquitectura acaba siendo una copia del organigrama: la ley de Conway aplicada a agentes. Por contexto, mi reparto por stories pasa: una story es un trozo de trabajo con su resultado visible, no «el agente de iOS» y «el agente de Android». Por recursos compartidos no pasó, y esa regla no lo habría detectado. ## El fallo más común del paper es el estado compartido, y mi simulador encaja El diseño es razonable: los subagentes no se forzaban. En el modo concurrente cada agente decidía si lanzarlos; en el secuencial se desactivaban las herramientas de delegación. 354 tareas, más de 2.000 ejecuciones y más de 20.000 dólares de API, con las configuraciones de julio de 2026. Claude Code iba con Opus 5 y, en el modo concurrente, con `ultracode` y Dynamic Workflow, que no es exactamente lanzar subagentes con la herramienta Agent. Los autores limitan sus conclusiones a esos agentes y esos benchmarks. El 83% → 59% de Claude Code en SWE-bench Verified es el dato más llamativo, y su caída en el conjunto de los benchmarks es estadísticamente significativa. Con subagentes se gastan entre 1,4 y 3,3 veces los tokens del modo secuencial, y el tiempo medio sube en 14 de las 15 combinaciones de agente y benchmark. La conclusión del paper es que los subagentes compensan más cuanto más larga es la tarea, y que conviene activarlos cuando hacen falta, no por defecto. En Claude Code, los cuatro benchmarks largos dan un resultado mixto: **mejora** en dos y baja en RepoZero del 42,7% al 26,7%. Mis stories se parecen más a una tarea acotada de SWE-bench que a construir un repositorio entero, así que me aplico la parte mala del titular. Lo más útil es su clasificación de fallos. La categoría más grande, un 33%, es estado compartido y merge: agentes que leen o modifican ficheros o entornos compartidos sin coordinarse. La pérdida de contexto global es la más pequeña, un 9%. Un simulador que usan varios agentes a la vez encaja en esa definición. El paper no clasifica simuladores de iOS, así que la comparación es mía. Cognition llegó a una conclusión parecida en [su post de abril](https://cognition.com/blog/multi-agents-working): lo que funciona son varios agentes aportando inteligencia mientras las escrituras siguen en un solo hilo. ## La caja negra son dos resúmenes en cada delegación Mi otra queja tiene explicación en la [documentación de subagentes](https://code.claude.com/docs/en/sub-agents). Un subagente empieza con un contexto nuevo y aislado; no ve la conversación. El agente principal le escribe un mensaje de delegación que resume la tarea, y el subagente devuelve solo un resumen. Lo que no entra en el primer resumen, el subagente no lo sabe. Lo que no entra en el segundo, el principal no lo ve. Si algo sale raro, la traza completa está en el contexto del subagente, no en el tuyo. Hay una excepción que no conocía: los forks heredan la conversación del principal en vez de empezar de cero. Para un encargo que depende de lo que ya hemos hablado, un fork pierde menos que un subagente normal. Y cada subagente cuenta para el límite de uso aunque su trabajo acabe en la papelera. No he medido cuántos tokens me cuestan, así que no voy a poner una cifra de ahorro. ## Subagentes para leer y verificar; para escribir, solo si no comparten nada Esto ya está hecho, fusionado en Rydger o ya activo en mis skills: - **Un simulador por worktree** y el script de pruebas de UI que he descrito arriba. El script que borra un worktree borra también sus simuladores. - **Orden fijo de pruebas en la skill de testing:** mientras itera, `swift test` y solo las suites tocadas; la suite unitaria completa una vez antes de cada commit; la de UI, una vez al fusionar. - **Un traspaso menos en mi skill de equipo de agentes.** Tenía un agente que investigaba con Haiku y le pasaba los datos a otro que implementaba con Sonnet, que los volvía a comprobar. Ahora investiga e implementa el mismo agente. Los revisores siguen en paralelo, pero solo uno ejecuta los tests; los demás leen. Y así reparto a partir de ahora: - **Subagentes para leer.** «Busca dónde se usa esta función y devuélveme la lista» es el caso de manual: el subagente lee muchos ficheros y yo solo recibo la lista. - **Subagentes para verificar.** Un revisor con contexto limpio que no ha visto cómo se escribió el código. - **Escrituras en paralelo solo si no comparten nada.** Ficheros, ramas, ficheros generados, simuladores, puertos. Si comparten algo, primero lo separo o lo pongo en serie. - **Los pasos del equipo, en skills.** Lo que antes iba en el prompt de un subagente especialista va a una skill que el agente principal carga cuando la necesita. ## Un proyecto y un simulador no bastan para dar la razón a nadie Mi caso es un proyecto y un recurso compartido: yo paralelicé sin mirar qué compartían los agentes, y eso no prueba que un solo agente sea mejor. Y quitar subagentes también rompe cosas. El ejemplo de Anthropic es un agente de soporte con un especialista de envíos: al fusionar un subagente con otro bajó la latencia, pero el agente empezó a contestar sin preguntarle la fecha de entrega a ese especialista. El fallo solo salió en una de las dos ejecuciones, y por eso piden repetir cada caso. ## Empieza por la lista de lo que comparten tus agentes Antes de quitar o añadir un subagente, apunta qué usan tus agentes a la vez cuando trabajan en paralelo: ficheros generados, simuladores, emuladores, puertos, bases de datos locales. Cada cosa de esa lista necesita una copia por agente o ir en serie. Es lo que hice yo, tarde. Si después quieres quitar un subagente, Anthropic propone escribir antes unos diez casos de principio a fin con el resultado esperado, ejecutar cada uno más de una vez con el subagente y sin él, y quitarlos de uno en uno. Yo todavía no lo he hecho. Si sin el subagente sale igual o mejor, sobra. ## Fuentes - Anthropic: [Building agents: When to fold subagents into your main agent loop](https://claude.com/resources/articles/building-agents-when-to-fold-subagents-into-your-main-agent-loop) (22 de octubre de 2026) y la [documentación de subagentes de Claude Code](https://code.claude.com/docs/en/sub-agents), consultadas el 30 de octubre de 2026. - Li, Li, Jiang y Lou: [When Sub-Agents Work in Parallel](https://arxiv.org/abs/2610.10263), arXiv, 7 de octubre de 2026. Preprint. - Cognition: [Multi-Agents: What's Actually Working](https://cognition.com/blog/multi-agents-working), abril de 2026. - Caso propio: scripts de simuladores y skill de testing de Rydger. El repositorio es privado; los tiempos son los de las ejecuciones antes y después del cambio. **Lectura relacionada:** [cómo reparto las stories entre subagentes](/blog/claude-code-subagentes-objetivos-stories/) y [por qué falla tu agente sin harness](/blog/harness-engineering-por-que-falla-tu-agente/). --- **P.D.** ¿Qué compartían tus agentes en paralelo que no habías visto? Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/claude-code-no-hype-agent-workflow/ Lang: en # Claude Code Without the Hype: How This Site Gets Built > How I build this site with Claude Code agents: worktrees, adversarial verifiers, a night queue and a smoke test. Plus the three-month contact form 500. **Short answer:** I hand work off in batches, and each task goes to an agent in its own git worktree, and the roles run on models of different sizes and prices: one researches, one builds, one tries to break what was built, one fixes whatever survives, and an advisor looks at the whole batch. Big tasks queue up overnight as labeled GitHub issues. There is no CI. I run the checks locally, and after deploys that touch routing I run a smoke test by hand against production, for the things my machine can't see. I built that last step because the contact form returned a 500 for three months while every local check was green. A quick note up front: an agent drafted this post from the repo; the incidents are mine. How it was made is further down. The form failed on every submission from June 28, 2026 until October 6. Tests, types, build: all green on my machine the whole time. I saw nothing, because my machine couldn't see the failure. I found it on October 6. I honestly don't remember how, and I'm not going to make it up. What I do know is that nothing alerted me, because nothing was checking production. The cause is almost embarrassing. The edge middleware forwards dynamic requests by fetching `/_render` on the same host. With `trailingSlash: "always"`, Vercel responded to that fetch with a 308 to `/_render/`. A GET follows a redirect fine. A POST with a streamed body can't be replayed, because the body has already been consumed. `GET /api/geo/` kept working. The form's POST didn't. The fix, on October 6, was a small build integration that puts the `/_render` route ahead of the trailing-slash redirect in Vercel's output config. Neither a unit test nor the build ever sees that redirect: it's Vercel's routing, which runs on every Vercel deployment, previews included, and never on my machine. What follows is what I built after that, plus what was already in place before it happened. ## With no CI, the gate is me before the push This repo has no GitHub Actions. Everything runs locally, and Vercel builds `main` when I push. That's written down in `docs/CI_CD.md`. A pre-push hook does the work. In order: `astro check`, the regex lint, `docs:check` (which fails when a doc cites a file that doesn't exist), the Vercel config check, the public-images check, the blog lint and validation, and the unit tests. If any of them fails, no push. The unit suite is 475 tests in 33 files; measured on October 28, 2026, it takes 3 to 7 seconds depending on machine load. It's fast enough that every agent can run it after every change. The full build isn't run per agent. It runs once at the end, on the merged result. ## The smoke test covers what my machine can't see `pnpm smoke` hits the production routes whose behavior depends on Vercel's routing: the home page and the blog, the geolocation endpoint, the contact form and the firewall. For daytime work I run it by hand after any deploy that touches `src/pages/api/`, `astro.config.mjs` or `vercel.json`; the night agent runs it on its own, before and after each of its releases. Two decisions that came out of using it: - **It sends no email.** Both form POSTs either get caught by the time trap (no `ts` field) or fail validation. I'm checking that the route responds; whether Resend delivers is a separate question. - **A 429 from the form is logged as a skip.** The firewall allows 5 contact-form POSTs per hour per IP, and each smoke run spends 2. Otherwise a third run within the hour would turn a healthy site red. It only works from an IP with a firewall System Bypass: with bot protection on, a script gets the challenge regardless of its user agent, and a challenge tells you nothing about whether the site is healthy. To check a single route by hand without the bypass, use `vercel curl --deployment`. The script also keeps the request count low, because a burst of `curl` from my IP trips Vercel's DDoS mitigation and locks me out of my own site for a while. ## Each handed-off task gets its own worktree and five roles Per task, the chain is short. A researcher on a small model returns facts with a source, the date it was read and a list of what it couldn't confirm. A builder on a mid-size model implements on an `agency/` branch in a worktree of its own. A reviewer on a larger model is told to find what's wrong (I haven't measured how much it actually catches; more on that below). Only if a major or blocking issue survives does a fixer step in, in that same worktree. At the end an advisor reads the whole batch and tells me what to keep, what to cut and what to do next. Three rules I don't bend: - Verifiers are read-only. They look at the worktree; they don't touch it. - In the normal pipeline, agents commit to their branch and nothing else. No push, no merge. - No pipeline agent touches the main checkout. It stays on `main`, clean, and it's where I work: I do the merging there, run the full build once, then delete the worktrees and the merged branches. Anything I hold back stays on its branch. That rule already existed, and an agent broke it. On the morning of October 28, 2026 I ran a daytime batch: three issues plus a type-check cleanup. The first run used the harness's built-in worktree isolation, which refused to start because `.claude` is a symlink in this repo. Meanwhile, a research agent I'd asked to do research only implemented a fix and left it on a branch in the main checkout. I caught it when I reviewed the batch. On the second run, the research prompt said explicitly that it was read-only, and each builder created its own worktree by hand in a sibling folder. I still check "don't touch main" with `git status`. ## The night queue: issues with a label Small things go in `.skeptic/backlog.md`, one line each with how it's verified. Big things are GitHub issues labeled `night`. A night agent picks up both, builds each one with the same chain, and leaves a report for the morning. Unlike the normal pipeline it does publish what survives: it watches production for a while using the smoke routes and reverts if a route fails or errors climb. The part I was most careful about is what stays out. Environment variables, secrets, deploy config, domains and billing are never built at night. They go to the backlog as proposals for a human, because a test can't prove them safe and some can't be undone. It also ignores any issue from someone without write access. My repo is private, but the rule is written for a public one, where anyone can open an issue with instructions inside. Every acceptance criterion has to be checkable with a test or a command the repo already has. If it isn't, the task goes back to the backlog marked "needs testable criteria" instead of being built blind. A concrete case: on the night of October 27, 2026 I opened six issues labeled `night`. The night agent built and released three of them by about 1:15 a.m. UTC: a test that checks every `relatedSlug` pair and every home anchor resolves, accessibility coverage for several new pages, and the cookie consent module. It left the other three alone. Removing the Sentry leftovers and an obsolete config option both touch build or deploy config, so they're my call. Upgrading Vitest to version 5 is a major version bump, and no e2e test covers the test runner itself, so it skipped that one too. The next morning they went into the daytime batch I described above. The pipeline did the Sentry cleanup and the Vitest upgrade, and the config option is the very fix the research agent implemented without being asked. I reviewed it (the built HTML came out byte-identical) and merged it as is. One night isn't a base rate, though: I haven't counted how often the night queue ships something it shouldn't or skips something it could have done. ## I pulled BotID from the form This is a separate incident, even though its second round landed on October 6, the same day as the 500 fix. I tried Vercel BotID on the form twice, and both times it broke it. The first time it blocked real visitors. The second time, on October 6, it was live for about 17 minutes and blocked me, with "Message blocked" in a regular browser. It's gone. The honeypot, the time trap, the link filter and the firewall's per-IP limit remain. The rule I took from it: a protection I can't test from a regular browser isn't protection, it's a bet. ## What this doesn't fix Four problems, and the first one bothers me most. For daytime work I run the smoke test by hand after the production deploy, so I still find a routing bug only after the site is live. It isn't automated, and it doesn't run against previews yet. And I only run it when the change touches `src/pages/api/`, `astro.config.mjs` or `vercel.json`: a change outside those three paths could bring a 500 back and nobody would see it, because I wouldn't run the check at all. And the smoke test only runs when I run it: nothing runs it on a schedule or alerts on production errors, so a failure that doesn't come from a deploy (a platform change, an expired key) would go unseen the same way. With no CI, my machine is the only gate, and the hook can be skipped with `--no-verify`. If I'm in a rush one day and skip it, or an agent does, nothing sits behind it to stop that push. I haven't measured how many bugs the verifiers catch on real tasks. I use the workflow anyway, but the repo keeps no per-batch record of what each verifier found. And the checks I write today are still the ones I think of. The ones I don't think of, I find when something breaks, like the form did. ## How I made this The agent used the `write-article` skill. What I asked it for, in essence: Spanish first, then English, each written in its own language rather than translated; nothing internal from my day job; only figures measured in this repo, with dates; and a claims list with proof for each one. The agent read the git history, the repo docs, the smoke script, the pre-push hook, the night backlog and the `night` issues, and ran the unit suite to measure it. Anything it couldn't confirm in those sources, it left out. Then a panel of reviewers with no context read it. One of them caught that the draft had the October 27 night wrong, and it was corrected against that night's report. The pipeline roles are short prompts: inline in the workflow script for the day pipeline, `roles/` files in the night skill. What changes between them is the model and the sentence saying what's expected: the researcher returns sourced facts, the verifier's job is to find failures. ## Sources Everything in this post comes from this site's private repo: git history, docs, the smoke script, the pre-push hook and the issues. You can't open those, but the incidents in this post (the contact form 500, BotID and the research agent that wrote code) are logged in the [lab](/en/lab/), each with what happened, how it was caught and what changed. The test and issue figures were measured on October 28, 2026. ## Your first move Don't copy my pipeline. Do one thing this week: write a twenty-odd-line script that hits the two or three production routes your local setup can't reproduce (redirects, dynamic endpoints, firewall rules), and fails if any of them doesn't respond as expected. Here's the skeleton: ```ts const BASE = process.env.SMOKE_URL ?? "https://your-domain.com"; const post = (path: string, fields: Record) => { const body = new FormData(); for (const [k, v] of Object.entries(fields)) body.append(k, v); // Browsers send Origin on a form POST; without it a CSRF check answers 403. return fetch(BASE + path, { method: "POST", body, headers: { origin: BASE }, redirect: "manual" }); }; const checks: [string, () => Promise, number][] = [ ["home", () => fetch(`${BASE}/`, { redirect: "manual" }), 200], // A POST with a body is where my 500 lived. A valid `ts` and a bad email // get past the time trap and fail validation, so no email goes out. ["form", () => post("/api/contact/", { ts: String(Date.now() - 60_000), name: "x", email: "bad", message: "short" }), 400], ]; let failed = 0; for (const [name, run, want] of checks) { const res = await run(); const ok = res.status === want; if (!ok) failed++; console.log(`${ok ? "ok " : "FAIL"} ${name}: ${res.status}`); } process.exit(failed ? 1 : 0); export {}; // makes it a module, so top-level await works ``` Swap in your own routes and status codes: the bad POST should get your endpoint's validation error, not a 500. I ran this exact script against this site on October 28, 2026 and both checks printed `ok`. If you have bot protection, it will challenge the script. Add your IP to the firewall bypass list, or all you'll see is challenges and 429s. Run it after every deploy, and on a schedule too, so a break that doesn't come from a deploy still shows up. If you have agents working in the repo, add a second thing: a `night` issue label and a rule that every issue carrying it says how it's verified. **Related reading:** [how I split subagents by stories and worktrees](/en/blog/claude-code-subagents-stories-worktrees/), and why [a verifier can lie too](/en/blog/ai-agent-verifier-false-claims/). --- **P.S.** Ever had a bug your local checks couldn't see, that you only found out about from a user? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/spec-driven-development-openspec-friction/ Lang: en # Spec-Driven Development: Where OpenSpec Chafes in Daily Use > What spec-driven development is, where OpenSpec chafes after months of daily use, and what Anthropic, Willison and Hashimoto lean on instead of the spec **Short answer:** spec-driven development (SDD) means writing down what a change has to do, as requirements and acceptance scenarios in Markdown, before the agent touches any code, and having the agent build against that document. OpenSpec, Spec Kit and Kiro are the best-known tools. In 2026, for the people whose workflows I've read, it's no longer the center of the workflow: the effort goes into giving the agent a check that comes back pass or fail, and the spec, when there is one, is short (Anthropic suggests having Claude interview you to produce it). Step away from AI for two or three weeks and it feels like years went by. Everyone's talking about SDD, harness engineering, grilling and software factories, and you can't tell whether you missed a revolution or a few new names for the same thing. The first one, SDD, got me. I went to look up what spec-driven development actually was and found out I'd been doing it for months. I use OpenSpec every day, on this site and on [Rydger](/en/blog/claude-code-subagents-stories-worktrees/). I just didn't know it had a name. One caveat up front: OpenSpec is the only SDD tool I run daily. I've read about Spec Kit, Kiro and BMAD but haven't lived with them, and the people I quote below are the ones whose workflows I think are worth reading, not a survey. So the rest of the vocabulary doesn't throw you, here are three terms you'll hear this week: - **Harness engineering:** everything that guides and checks the agent; the spec is one of its guides. I covered it in [this post](/en/blog/harness-engineering-why-your-agent-fails/). - **Grilling:** having the agent interview you relentlessly before anything gets written. - **Software factory:** spec in, software out, no human review. The opposite end of the spectrum from what I'm arguing for here. ## I'd been doing SDD for months without the label GitHub popularized the idea when it launched Spec Kit in September 2025, pitching the spec as "a contract for how your code should behave." Birgitta Böckeler, writing on martinfowler.com, sorted it into three levels that make the rest of the noise easier to place: - **Spec-first:** write the spec, let the agent build, and the spec isn't necessarily kept once the task is done. - **Spec-anchored:** the spec stays in the repo and evolves with the code. - **Spec-as-source:** the spec is the source file and the code is generated from it. OpenSpec is spec-anchored. Each change lives in `openspec/changes//` as four pieces: `proposal.md` (why and what changes), delta specs with requirements and `WHEN … THEN …` scenarios, `design.md` (how) and `tasks.md` (the checklist). When you're done you archive the change, and its deltas merge into the project's living specs. The rest of the map, one line each: | Tool | What you get | Best fit | | --- | --- | --- | | [Spec Kit](https://github.com/github/spec-kit) | constitution, spec, plan, tasks, implement | New features with fuzzy requirements | | [OpenSpec](https://github.com/Fission-AI/OpenSpec) | proposal, delta specs, design, tasks, archive | Changes to a system that already exists | | [Kiro](https://kiro.dev/docs/specs/) | AWS's IDE with requirements, design and tasks built in | Same, if you're willing to switch editors | | [BMAD](https://github.com/bmad-code-org/BMAD-METHOD) | a simulated team: analyst, PM, architect, dev | Whole products with several roles; the heaviest of the four, though its README says small changes go straight to build | That table is my reading of their docs, not a recommendation from any of them. ## Where OpenSpec chafes when you use it every day The friction doesn't show up in a demo. It shows up after months with the tool, and it clusters in four places. **`explore` stays shallow.** It's supposed to be the thinking and research step before you propose. In practice it reads what's in front of it and comes back fast. It doesn't do the research I'd do by hand: reading the docs and checking how other people solved the same problem. **`propose` doesn't ask enough questions.** When there's a gap, it fills it with a reasonable assumption and moves on. Those assumptions get written down with the same confidence as the things you actually decided, and then you have to hunt them down. That's a pattern I see often, not something I've counted. **The Markdown is long, and long reviews degrade.** Four files per change is a lot of text to read carefully before a single line of code exists. The problem is the volume, not the reader. Böckeler said it in October 2025 after trying Kiro and Spec Kit: _"I'd rather review code than all these markdown files."_ Thoughtworks' Radar warned in November 2025 that some of these tools generate spec files that are long and hard to review. **Closing a change is pure ceremony.** When you archive, it first asks you to sync the delta specs into the living ones, then archives: one more review gate that neither writes code nor checks it. That's the price of a living spec, and you pay it on every change, small ones included. On a small fix, Böckeler compared the workflow to using a sledgehammer to crack a nut. ## The honest part: a living spec does earn its keep This site has an OpenSpec change called `improve-seo-ai-visibility`, proposed on October 6. Every task is done except one: re-measure 28 days after the deploy. That task is still sitting in `tasks.md`, and no chat session would have remembered it for me. To be fair, a GitHub issue would have held the reminder too. What the issue doesn't hold is the requirement next to it, with its scenarios, in the same repo as the code it describes. That's the promise of spec-anchored: a year from now, someone can read why the code is the way it is. On a three-week-old change, that's still more promise than payoff. I also like that every task ends in a concrete "verify …", so the agent knows what to check before it ticks the box. And SDD isn't dead. Spec Kit shipped four releases between October 16 and October 27, 2026, and the April 2026 Radar put OpenSpec in _Assess_, which in Thoughtworks terms means worth exploring. ## What they do now: a short spec and a check the agent can run I read how four people whose work I follow describe their own workflow, plus Anthropic's guide. They agree more than you'd expect. - **Anthropic's Claude Code best practices** suggest that when you don't know exactly what you want, you have Claude interview you until it can write the spec to a `SPEC.md`, then build from a fresh session. And the line that sums it all up: _"Give Claude something it can run that comes back pass or fail."_ - **Boris Cherny**, who leads Claude Code, in a January thread: five Claudes in parallel, most sessions starting in plan mode, and what he calls the most important thing for good results, giving Claude a way to verify its work. I covered his point about writing loops instead of prompts in [another post](/en/blog/stop-prompting-write-loops/). - **Simon Willison**, in his agentic engineering guide: red/green TDD (write the test, confirm it fails, then write the code) and run the existing tests before you start. - **Mitchell Hashimoto**, in February: _"If you give an agent a way to verify its work,"_ it fixes its own mistakes more often than not. And a repeated agent mistake gets a line in `AGENTS.md` or a script so it stops recurring. - **Böckeler** again, in April, on harness engineering: guides before the agent acts (rules, specs) and sensors after (tests, linters, type checks). The spec becomes one guide among several. This is partly SDD under another name: the interview plus `SPEC.md` is textbook spec-first. The difference is where the effort goes. Classic SDD puts it into writing and reviewing Markdown, so the guarantee rests on a person reading it carefully. This puts it into a scenario that becomes a failing test, which then goes red without anyone watching. It isn't free either. A test written by the same agent that wrote the code can pass while checking the wrong thing, so the review doesn't disappear: it moves to the test. And a green command says nothing about a design decision no command can check. ## Three of the frictions have a fix; the fourth doesn't Here's what I'd try for each, based on the above: | What you're running into | What I'd try | | --- | --- | | `explore` doesn't really research | Send subagents to research first, with a specific question and sources | | `propose` papers over gaps with assumptions | Interview first (Matt Pocock's "grill me," or Anthropic's version), spec second | | Four Markdown files to review | A short spec, with every `WHEN … THEN …` scenario turned into a test | | Sync and archive on every change | Keep only the specs that need to last up to date; treat the rest as disposable | The last row has no clean fix. If you want the spec to survive, somebody has to sit through the ceremony. What you get to choose is which changes are worth it. ## What to learn next, cheapest first 1. **One pass/fail command per project.** Tests, types, linter, whatever you have, behind a single command the agent can run. It's the point all five sources share. 2. **Scenarios become tests.** The `WHEN … THEN …` in your spec is already a test written in English. Ask the agent to write it first and confirm it fails. 3. **A short `AGENTS.md` that grows one mistake at a time.** Every time the agent repeats an error, one line or one script. And prune: the April Radar flags agent instruction bloat under _Caution_ because those files get long and start contradicting themselves. 4. **Interview before the spec.** This goes straight at the `propose` problem. I wrote up how I do it with [`grill-with-docs`](/en/blog/agent-skills-coding-workflow/). 5. **A reviewer with a clean context.** A session or subagent that checks the diff against the spec without having seen your conversation. Anthropic's guide is blunt about it: handing the same task to a subagent doesn't make the answer better, but a fresh reviewer does help. 6. **Parallel work in worktrees, and loops.** Last. A worktree is cheap to try and so is a small loop; the Radar's caution is about swarms of agents running at once, and that's where most of the noise comes from. On this site I already run 1, 3 and 4: a pre-push hook that runs `astro check`, lint and the tests before every push, a short `AGENTS.md`, and `grill-with-docs`. I built number 5 as [a verifier](/en/blog/ai-agent-verifier-false-claims/). Step two is the one Willison and Pocock push hardest. Here it is with a made-up booking example: ```ts // spec: WHEN room R1 is booked 10:00-11:00 // and someone books R1 for 10:30-11:30 // THEN the API returns 409 and stores nothing it("rejects an overlapping booking", async () => { await book({ room: "R1", from: "10:00", to: "11:00" }); const res = await book({ room: "R1", from: "10:30", to: "11:30" }); expect(res.status).toBe(409); expect(await countBookings("R1")).toBe(1); }); ``` ## Before your next `propose` You don't need to drop OpenSpec. A "verify …" written in prose is something the agent interprets; a command with an exit code isn't. So do one thing: go through your next change's `tasks.md` and make sure every task ends in a command the agent can run that comes back pass or fail. For a task with no command, like a design decision or a doc, write down what you'd observe when it's done (a file that exists, a URL that answers) or mark it as human-checked on purpose. The ones a command can't confirm for you are where your attention should go. **Related reading:** the step I added before OpenSpec, to decide what deserves a spec at all, is in [the Rydger subagents post](/en/blog/claude-code-subagents-stories-worktrees/). ## Sources - GitHub, [Spec Kit launch post](https://github.blog/ai-and-ml/generative-ai/spec-driven-development-with-ai-get-started-with-a-new-open-source-toolkit/) (September 2, 2025). - Birgitta Böckeler, [_Understanding Spec-Driven-Development: Kiro, spec-kit, and Tessl_](https://www.martinfowler.com/articles/exploring-gen-ai/sdd-3-tools.html) (October 15, 2025) and [_Harness engineering_](https://martinfowler.com/articles/exploring-gen-ai/harness-engineering.html) (April 2, 2026). - Thoughtworks Technology Radar: [spec-driven development](https://www.thoughtworks.com/radar/techniques/spec-driven-development) (November 2025), [OpenSpec](https://www.thoughtworks.com/radar/tools/openspec) and [agent instruction bloat](https://www.thoughtworks.com/radar/techniques/agent-instruction-bloat) (vol. 34, April 2026). - Anthropic, [Claude Code best practices](https://code.claude.com/docs/en/best-practices) (read October 28, 2026). - Boris Cherny, [thread on his Claude Code workflow](https://threadreaderapp.com/thread/2007179832300581177.html) (January 2, 2026). - Simon Willison, [_Agentic Engineering Patterns_](https://simonwillison.net/guides/agentic-engineering-patterns/). - Mitchell Hashimoto, [_My AI Adoption Journey_](https://mitchellh.com/writing/my-ai-adoption-journey) (February 5, 2026). - Matt Pocock, [skills](https://github.com/mattpocock/skills), including `grill-me`. - My OpenSpec experience comes from daily use; the `improve-seo-ai-visibility` change is in this site's repo. --- **P.S.** Do you use SDD every day too? I'd love to know which part you stopped doing and never missed. Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/claude-code-sin-humo-flujo-agentes/ Lang: es # Claude Code sin humo: el flujo de agentes de esta web > Cómo hago esta web con agentes de Claude Code: worktrees, verificadores, cola de noche y un smoke test. Y el 500 de tres meses que explica el smoke test. **Respuesta corta:** las tareas que delego en lote las hace cada una un agente en su propio worktree, con roles en modelos de distinto tamaño y precio: uno investiga, otro implementa, un tercero intenta romper lo hecho, otro arregla lo que sobreviva y un asesor mira el conjunto. Las tareas grandes entran por la noche como issues con una etiqueta. No hay CI: los checks los ejecuto yo en local y, después de los deploys que tocan el enrutado, lanzo a mano un smoke test contra producción que prueba lo que el local no puede ver. Ese último paso lo monté porque el formulario de contacto estuvo devolviendo un 500 durante tres meses con todos los checks en verde. Una aclaración antes de seguir: este post lo redactó un agente a partir del repo; los incidentes los viví yo. Cómo se hizo lo cuento más abajo. El formulario falló en cada envío desde el 28 de junio de 2026 hasta el 6 de octubre. Tests, tipos y build, todo en verde en mi máquina durante esos tres meses. Yo no vi nada porque no había nada que ver desde donde miraba. Lo encontré el 6 de octubre; cómo exactamente no lo recuerdo, y no me lo voy a inventar. Lo que sí sé es que nada me avisó, porque no había ningún check contra producción. La causa tiene gracia, de la mala. El middleware de borde reenvía las peticiones dinámicas pidiendo `/_render` en el mismo host. Con `trailingSlash: "always"`, Vercel contestaba a esa petición con un 308 hacia `/_render/`. Un GET sigue una redirección sin problema. Un POST con el cuerpo en streaming no puede, porque el cuerpo ya se consumió. El `GET /api/geo/` funcionaba, el POST del formulario no. El arreglo, el 6 de octubre, fue una pequeña integración de build que pone la ruta de `/_render` por delante de la redirección de la barra final en la config de salida de Vercel. Ni un test unitario ni el build ven esa redirección: es enrutamiento de Vercel, que existe en cualquier deploy de Vercel, previews incluidas, y nunca en mi máquina. Todo lo que viene ahora es lo que monté después, y lo que ya tenía montado antes de que esto pasara. ## Sin CI, el filtro soy yo antes del push No hay GitHub Actions en este repo. Todo se ejecuta en local y Vercel construye `main` cuando hago push. Lo documento tal cual en `docs/CI_CD.md`. El peso lo lleva un hook de pre-push que ejecuta, en este orden, `astro check`, el lint de regex, `docs:check` (que falla si un documento cita un fichero que no existe), la comprobación de la config de Vercel, la de imágenes públicas, el lint y la validación de los posts, y los tests unitarios. Si falla algo, no hay push. La suite unitaria tiene hoy 475 tests en 33 ficheros; medida el 28 de octubre de 2026, tarda entre 3 y 7 segundos según lo cargada que esté la máquina. Esa velocidad es lo que permite que cada agente la ejecute tras cada cambio sin que nadie lo piense dos veces. El build completo no lo lanza cada agente. Se lanza una vez, al final, sobre el resultado ya fusionado. ## El smoke test cubre lo que mi máquina no puede ver `pnpm smoke` pide a producción las rutas que dependen de cómo enruta Vercel: la home y el blog, el endpoint de geolocalización, el formulario de contacto y el firewall. En el trabajo de día lo lanzo a mano después de cada deploy que toque `src/pages/api/`, `astro.config.mjs` o `vercel.json`; el agente de noche lo lanza por su cuenta, antes y después de sus propias publicaciones. Un par de decisiones que salieron de usarlo: - **No envía correos.** Los dos POST al formulario o caen en la trampa de tiempo (no llevan el campo `ts`) o no pasan la validación. Compruebo que la ruta responde; que Resend entregue es otra cuestión. - **Un 429 del formulario se anota como «saltado».** El firewall deja 5 POST al formulario por hora y por IP, y cada ejecución del smoke gasta 2. Si no, a la tercera ejecución en la misma hora un sitio sano daría rojo. Solo funciona desde una IP con un System Bypass del firewall: con la protección contra bots activa, a un script le sueltan el reto de verificación sea cual sea su user agent, y un reto no te dice si el sitio está bien o mal. Para mirar una ruta suelta a mano sin bypass queda `vercel curl --deployment`. Además, el script hace pocas peticiones, porque una ráfaga de `curl` desde mi IP activa la mitigación de DDoS de Vercel y me deja fuera de mi propia web durante un rato. ## Cada tarea delegada en su worktree, con cinco roles El flujo por cada tarea es una cadena corta. Primero investiga un agente con un modelo pequeño, que devuelve hechos con fuente, fecha de lectura y una lista de lo que no pudo confirmar. Después implementa otro con un modelo intermedio, en una rama `agency/` dentro de su propio worktree. Luego revisa otro con un modelo más grande, que tiene el encargo explícito de encontrar lo que está mal (cuánto caza de verdad no lo tengo medido; vuelvo a eso abajo). Solo si queda algún fallo bloqueante o grave, entra un agente que lo arregla en ese mismo worktree. Al final, un asesor mira el lote entero y me dice qué mantener, qué cortar y qué hacer después. Tres reglas que no se negocian: - Los verificadores son de solo lectura. Miran el worktree, no lo tocan. - En el pipeline normal, los agentes hacen commit en su rama y nada más. No hay push ni merge. - Ningún agente del pipeline toca el checkout principal: se queda en `main` y limpio, y ahí trabajo yo. Fusiono yo, lanzo el build completo una vez, borro los worktrees y las ramas ya fusionadas. Solo conserva su rama lo que se queda sin fusionar. Esa regla ya existía, y un agente se la saltó. La mañana del 28 de octubre de 2026 lancé una tanda de día con tres issues y una limpieza de tipos. La primera pasada usaba el aislamiento por worktree del propio harness, que se negó a arrancar porque en este repo `.claude` es un enlace simbólico. Mientras tanto, un agente al que le había pedido que solo investigara implementó un arreglo y lo dejó en una rama del checkout principal. Lo vi al revisar la tanda. En la segunda pasada, el prompt de investigación decía de forma explícita que era de solo lectura, y cada constructor creó su propio worktree a mano en una carpeta hermana. Aun así, «no toques el principal» lo compruebo con `git status`. ## La cola de noche: issues con una etiqueta Lo pequeño va en `.skeptic/backlog.md`, una línea por tarea con cómo se comprueba. Lo grande es un issue de GitHub con la etiqueta `night`. Un agente de noche recoge ambos, construye cada elemento con la misma cadena de arriba y deja un informe para la mañana. Este sí publica lo que sobrevive: vigila producción un rato con las rutas del smoke y revierte si falla una ruta o suben los errores. Donde más cuidado puse es en qué se queda fuera. Variables de entorno, secretos, configuración de deploy, dominios y facturación no se construyen de noche: pasan al backlog como propuesta para que las haga una persona. Un test no puede demostrar que sean seguras, y algunas no se pueden deshacer. Tampoco se acepta un issue de alguien sin permiso de escritura en el repo: mi repo es privado, pero la regla está pensada para uno público, donde cualquiera puede abrir un issue con instrucciones dentro. Cada criterio de aceptación tiene que poder comprobarse con un test o con un comando que el repo ya tenga. Si no, la tarea vuelve al backlog con «necesita criterios comprobables» en vez de construirse a ciegas. Un ejemplo concreto: la noche del 27 de octubre de 2026 abrí seis issues con la etiqueta `night`. El agente de noche construyó y publicó tres hacia la 1:15 UTC: un test que comprueba que cada pareja `relatedSlug` y cada ancla de la home apuntan a algo que existe, la cobertura de accesibilidad de varias páginas nuevas y el módulo de consentimiento de cookies. Los otros tres no los tocó. Dos de ellos, quitar los restos de Sentry y una opción de configuración obsoleta, tocan la config de build o de deploy, así que decido yo. Pasar Vitest a la versión 5 es un salto de versión mayor, y como ningún e2e cubre el propio runner de tests, tampoco lo construyó. Por la mañana entraron en la tanda de día de la que hablaba arriba: la cadena hizo lo de Sentry y lo de Vitest, y la opción de configuración es justo el arreglo que el agente de investigación implementó sin que se lo pidiera. Lo revisé (el HTML generado salía idéntico byte a byte) y lo fusioné tal cual. Una noche no es una estadística: no he contado cuántas veces la cola de noche publica algo que no debía o deja fuera algo que podía hacer. ## Quité BotID del formulario Esto es otro incidente, aunque su segunda parte cayera el mismo 6 de octubre que el arreglo del 500. Probé Vercel BotID en el formulario dos veces y las dos lo rompió: la primera bloqueó a visitantes reales; la segunda, el 6 de octubre, estuvo puesto unos 17 minutos y me bloqueó a mí, con «Message blocked» desde un navegador normal. Lo quité. Se quedan el honeypot, la trampa de tiempo, el filtro de enlaces y el límite por IP del firewall. De ahí saqué una regla para el flujo: una protección que no puedo probar desde un navegador normal no es una protección, es una apuesta. ## Lo que este flujo no arregla Cuatro pegas, y la primera es la que más me escuece. En el trabajo de día el smoke test lo lanzo yo, a mano, después del deploy a producción, así que un fallo de enrutado lo sigo descubriendo con la web ya publicada. No está automatizado ni se lanza todavía contra las previews. Y solo lo lanzo cuando el cambio toca `src/pages/api/`, `astro.config.mjs` o `vercel.json`: un cambio fuera de esas tres rutas podría traer otro 500 y nadie lo vería, porque ni siquiera lanzaría el check. Y el smoke test solo corre cuando yo lo lanzo: nada lo ejecuta de forma periódica ni avisa de errores en producción, así que un fallo que no venga de un deploy (un cambio de la plataforma, una clave que caduca) pasaría igual de desapercibido. Sin CI, mi máquina es la única puerta, y el hook se salta con `--no-verify`. Si un día tengo prisa y lo uso, o lo usa un agente, no hay nada detrás que lo pare. Tampoco tengo medido cuántos fallos cazan los verificadores en tareas reales. El flujo existe, pero en el repo no hay un registro por lote de qué encontró cada uno. Y los checks que escribo hoy siguen siendo los que se me ocurren a mí. Los que no se me ocurren los descubro cuando algo se rompe, como pasó con el formulario. ## Cómo lo hice Al agente, que usó la skill `write-article`, le pedí en esencia: escribir primero en español y después en inglés, pensando cada versión en su idioma y sin traducir; no meter nada interno de mi trabajo; no meter ninguna cifra que no esté medida en este repo y fechada; y dejar una lista de afirmaciones con su prueba. El agente leyó el historial de git, la documentación del repo, el script del smoke test, el hook de pre-push, el backlog de noche y los issues con la etiqueta `night`, y ejecutó la suite unitaria para medirla. Lo que no pudo confirmar en esas fuentes lo dejó fuera. Después pasó por un panel de revisores que lo leyeron sin contexto, y uno de ellos pilló que el relato de la noche del 27 estaba mal contado: se corrigió con el informe de esa noche delante. Los roles del pipeline son prompts cortos: en el flujo de día van dentro del script del workflow, y en el de noche son ficheros `roles/` de la skill. Lo que cambia entre ellos es el modelo y la frase que dice qué se espera: el investigador devuelve hechos con fuente, el verificador tiene que buscar fallos. ## Fuentes Todo sale del repo privado de esta web: historial de git, documentación, el script del smoke test, el hook de pre-push y los issues. Eso no lo puedes abrir, pero los incidentes que salen aquí (el 500 del formulario, BotID y el agente que implementó cuando solo tenía que investigar) están en el [laboratorio](/lab/), cada uno con qué pasó, cómo se detectó y qué cambió. Las cifras de los tests y de los issues están medidas el 28 de octubre de 2026. ## Por dónde empezar No copies mi pipeline. Haz una sola cosa esta semana: escribe un script de unas veinte líneas que pida a producción las dos o tres rutas que tu entorno local no puede reproducir (redirecciones, endpoints dinámicos, reglas de firewall) y que falle si algo no devuelve lo esperado. El esqueleto cabe en esto: ```ts const BASE = process.env.SMOKE_URL ?? "https://tu-dominio.com"; const post = (path: string, fields: Record) => { const body = new FormData(); for (const [k, v] of Object.entries(fields)) body.append(k, v); // El navegador manda Origin en un POST de formulario; sin él, un check CSRF da 403. return fetch(BASE + path, { method: "POST", body, headers: { origin: BASE }, redirect: "manual" }); }; const checks: [string, () => Promise, number][] = [ ["home", () => fetch(`${BASE}/`, { redirect: "manual" }), 200], // Un POST con cuerpo: aquí es donde estaba mi 500. Con un `ts` válido y un // email malo pasa la trampa de tiempo y falla la validación: no sale ningún correo. ["form", () => post("/api/contact/", { ts: String(Date.now() - 60_000), name: "x", email: "bad", message: "short" }), 400], ]; let failed = 0; for (const [name, run, want] of checks) { const res = await run(); const ok = res.status === want; if (!ok) failed++; console.log(`${ok ? "ok " : "FAIL"} ${name}: ${res.status}`); } process.exit(failed ? 1 : 0); export {}; // lo convierte en módulo, para que funcione el await de nivel superior ``` Cambia las rutas y los estados por los tuyos: el POST malo debería dar el error de validación de tu endpoint, no un 500. Este mismo script lo lancé contra esta web el 28 de octubre de 2026 y los dos checks salieron `ok`. Si tienes protección contra bots, al script le va a plantar un reto: añade tu IP al bypass del firewall o solo verás retos y 429. Lánzalo después de cada deploy y también programado, para que un fallo que no venga de un deploy salga igual. Si tienes agentes trabajando en el repo, añade una segunda cosa: una etiqueta `night` y la norma de que cada issue que la lleve diga cómo se comprueba. **Lectura relacionada:** el [reparto de subagentes por stories y worktrees](/blog/claude-code-subagentes-objetivos-stories/) y por qué [un verificador también puede mentir](/blog/verificador-agente-ia-mentira/). --- **P.D.** ¿Has tenido alguna vez un fallo que tus checks locales no podían ver y del que te enteraste por un usuario? Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/spec-driven-development-openspec-chirria/ Lang: es # Spec-driven development: uso OpenSpec a diario y chirría > Qué es el spec-driven development, dónde chirría OpenSpec tras meses de uso diario y qué hacen ahora Anthropic, Willison o Hashimoto para no depender de él **Respuesta corta:** spec-driven development (SDD) es escribir en Markdown qué tiene que hacer un cambio (requisitos y escenarios de aceptación) antes de que el agente toque código, y que el agente implemente a partir de ese documento. OpenSpec, Spec Kit y Kiro son las herramientas más conocidas. En 2026, en los flujos que he leído, ya no es el centro: el esfuerzo va a que el agente pueda comprobar su trabajo con algo que acabe en verde o en rojo, y la spec, cuando la hay, es corta (Anthropic propone sacarla de una entrevista). Desconectas dos o tres semanas de la IA y al volver parece que han pasado años. Todo el mundo habla de SDD, harness engineering, grilling y software factories, y tú no sabes si te has perdido una revolución o unas cuantas palabras nuevas para lo mismo. A mí me pasó con el SDD. Me puse a investigar qué era eso del spec-driven development y resultó que lo llevaba haciendo meses. Uso OpenSpec a diario en esta web y en [Rydger](/blog/claude-code-subagentes-objetivos-stories/). No sabía que tenía nombre. Una advertencia antes de seguir: OpenSpec es la única herramienta de SDD que uso a diario. Spec Kit, Kiro y BMAD los he leído, no los he sufrido. Y la gente que cito más abajo es mi selección de flujos que merecen la pena, no una encuesta. Y para que no te pierdas con el resto del vocabulario, tres palabras que vas a oír esta semana: - **Harness engineering:** todo lo que guía y comprueba al agente; la spec es una de sus guías. Lo expliqué en [este post](/blog/harness-engineering-por-que-falla-tu-agente/). - **Grilling:** que el agente te entreviste sin piedad antes de escribir nada. - **Software factory:** entra la spec, sale el software, y nadie lo revisa. El extremo opuesto a lo que defiendo aquí. ## Llevaba meses haciendo SDD sin saber que se llamaba así La idea la popularizó GitHub con Spec Kit en septiembre de 2025: la spec como «un contrato de cómo debe comportarse tu código». Birgitta Böckeler, en martinfowler.com, la ordenó en tres niveles que sirven para no perderse: - **Spec-first:** escribes la spec, el agente implementa, y no hace falta conservarla al terminar. - **Spec-anchored:** la spec se queda en el repo y evoluciona con el código. - **Spec-as-source:** la spec es la fuente de verdad y el código se genera desde ella. OpenSpec es spec-anchored. Cada cambio vive en `openspec/changes//` con cuatro piezas: `proposal.md` (por qué y qué cambia), unas specs delta con requisitos y escenarios `WHEN … THEN …`, `design.md` (cómo) y `tasks.md` (la checklist). Cuando terminas, archivas el cambio y sus deltas se integran en las specs vivas del proyecto. El resto del mapa, en una línea cada una: | Herramienta | Qué te da | Para qué sirve | | --- | --- | --- | | [Spec Kit](https://github.com/github/spec-kit) | constitución, spec, plan, tareas, implementación | Features nuevas con requisitos difusos | | [OpenSpec](https://github.com/Fission-AI/OpenSpec) | propuesta, delta specs, diseño, tareas, archivo | Cambios sobre un sistema que ya existe | | [Kiro](https://kiro.dev/docs/specs/) | IDE de AWS con requisitos, diseño y tareas integrados | Lo mismo, si aceptas cambiar de editor | | [BMAD](https://github.com/bmad-code-org/BMAD-METHOD) | un equipo simulado: analista, PM, arquitecto, dev | Producto entero con varios roles; la más pesada, aunque su README dice que los cambios pequeños van directos a build | La tabla es mi lectura de sus docs, no una recomendación de ninguna de ellas. ## Dónde chirría OpenSpec cuando lo usas todos los días Las fricciones no salen en una demo. Salen cuando llevas meses con la herramienta, y son cuatro. **`explore` se queda en la superficie.** Debería ser la fase de pensar e investigar antes de proponer. En la práctica lee lo que tiene a mano y da la tarea por terminada enseguida. La investigación que haría yo, ir a la documentación y mirar cómo lo han resuelto otros, no la hace. **`propose` no pregunta todo lo que debería.** Donde hay un hueco, mete una suposición razonable y sigue. El problema es que esas suposiciones quedan escritas con la misma seguridad que lo que sí decidiste, y luego toca cazarlas. No es algo que haya contado, es lo que veo a menudo. **El Markdown es largo, y una revisión larga se degrada.** Cuatro ficheros por cambio es mucho texto que leer con atención antes de escribir una sola línea de código. El problema es el volumen, no quien lee. Böckeler lo dijo en octubre de 2025, probando Kiro y Spec Kit: _"I'd rather review code than all these markdown files"_. Y el Radar de Thoughtworks avisó en noviembre de 2025 de que algunas herramientas generan specs largas y difíciles de revisar. **Cerrar un cambio es pura ceremonia.** Al archivar, primero te pide sincronizar las specs delta con las vivas y luego archiva: otro punto de control, que ni escribe código ni lo comprueba. Es el precio de mantener la spec viva, y se paga en cada cambio, también en los pequeños. Con un fix pequeño, Böckeler lo comparó con matar moscas a cañonazos. ## La parte honesta: la spec viva sí aporta algo En esta web tengo un cambio de OpenSpec, `improve-seo-ai-visibility`, propuesto el 6 de octubre. Todas las tareas están cerradas menos una: volver a medir 28 días después del deploy. Esa tarea sigue ahí, en `tasks.md`, esperando, y ninguna sesión de chat la habría recordado por mí. Todo hay que decirlo: una issue de GitHub también habría guardado el recordatorio. Lo que la issue no guarda es el requisito al lado, con sus escenarios, en el mismo repo que el código que describe. Ese es el valor que promete spec-anchored: que dentro de un año alguien pueda leer por qué el código es así. En un cambio de tres semanas todavía es más promesa que resultado. También me gusta que cada tarea termine en un "verify …" concreto: el agente sabe qué tiene que comprobar antes de marcar la casilla. Y el SDD no está muerto. Spec Kit sacó cuatro versiones entre el 16 y el 27 de octubre de 2026, y el Radar de abril de 2026 puso OpenSpec en _Assess_, que en su idioma significa "merece la pena explorarlo". ## Lo que hacen ahora: una spec corta y un check que el agente pueda ejecutar Leí cómo describen su propio flujo cuatro personas a las que sigo, más la guía de Anthropic. Coinciden más de lo que parece. - **La guía de Claude Code de Anthropic** propone, cuando no sabes bien lo que quieres, pedirle a Claude que te entreviste hasta poder escribir la spec en un `SPEC.md`, y luego construir desde una sesión nueva. Y la frase que lo resume todo: _"Give Claude something it can run that comes back pass or fail."_ - **Boris Cherny**, responsable de Claude Code, en un hilo de enero: cinco Claudes en paralelo, casi todas las sesiones empiezan en plan mode, y lo que considera más importante para sacarle buenos resultados: darle a Claude una forma de verificar su trabajo. Lo de que ahora escribe loops en vez de prompts lo conté en [otro post](/blog/deja-de-promptear-escribe-loops/). - **Simon Willison**, en su guía de _agentic engineering_: TDD red/green (el test primero, comprobar que falla, luego el código) y ejecutar los tests antes de empezar. - **Mitchell Hashimoto**, en febrero: si le das al agente una forma de verificar su trabajo, la mayoría de las veces se corrige solo. Y cada error repetido del agente gana una línea en `AGENTS.md` o un script para que no vuelva. - **Böckeler**, en abril, con harness engineering: guías antes de que el agente actúe (reglas, specs) y sensores después (tests, linters, tipos). La spec pasa a ser una guía más. En parte esto es SDD con otro nombre: la entrevista y el `SPEC.md` son spec-first de manual. La diferencia está en dónde va el esfuerzo. En el SDD clásico lo pones en escribir y revisar Markdown, así que la garantía depende de una lectura humana. Aquí lo pones en un escenario que se convierte en un test que falla, y que después se pone en rojo sin que nadie esté mirando. Tampoco es gratis. Un test que escribe el mismo agente que escribe el código puede pasar comprobando lo que no era, así que la revisión no desaparece: se muda al test. Y un comando en verde no dice nada de una decisión de diseño que ningún comando puede comprobar. ## Tres fricciones tienen arreglo; la cuarta no Esto es lo que probaría yo con cada una, a partir de lo anterior: | Lo que te pasa | Lo que probaría | | --- | --- | | `explore` no investiga en serio | Lanzar subagentes a investigar antes, con una pregunta concreta y fuentes | | `propose` rellena huecos con suposiciones | Una entrevista primero (el "grill me" de Matt Pocock, o la de Anthropic), y la spec después | | Cuatro ficheros de Markdown que revisar | Spec corta, y cada escenario `WHEN … THEN …` convertido en test | | Sync y archive en cada cambio | Mantener viva solo la spec de lo que tiene que durar; el resto, usar y tirar | La última fila no tiene arreglo limpio. Si quieres que la spec sobreviva, alguien tiene que pasar por la ceremonia. Lo que puedes elegir es en qué cambios compensa. ## Qué aprender después, de lo más barato a lo más caro 1. **Un comando que dé verde o rojo en cada proyecto.** Tests, tipos, linter, lo que tengas, detrás de un solo comando que el agente pueda ejecutar. Es el punto en el que coinciden las cinco fuentes. 2. **Que los escenarios se conviertan en tests.** El `WHEN … THEN …` de tu spec ya es un test escrito en prosa. Pídele al agente que lo escriba primero y que compruebe que falla. 3. **Un `AGENTS.md` corto que crece error a error.** Cada vez que el agente repite una equivocación, una línea o un script. Y quita lo que sobre: el Radar de abril pone las instrucciones infladas en _Caution_ porque acaban largos y con reglas que se contradicen. 4. **Entrevista antes de la spec.** Esto ataca directamente la fricción de `propose`. Ya conté cómo lo hago con [`grill-with-docs`](/blog/agent-skills-flujo-codigo/). 5. **Un revisor con el contexto limpio.** Una sesión o un subagente que revisa el diff contra la spec sin haber visto tu conversación. La guía de Anthropic lo deja claro: pasarle la misma tarea a un subagente no mejora la respuesta; uno que no haya visto tu razonamiento sí aporta. 6. **Paralelo con worktrees, y loops.** Lo último. Un worktree es barato de probar y un loop pequeño también; la cautela del Radar es por los enjambres de muchos agentes a la vez, que es lo que más ruido mete. En esta web ya tengo el 1, el 3 y el 4: un hook de pre-push que pasa `astro check`, el lint y los tests antes de cada push, un `AGENTS.md` corto y `grill-with-docs`. El 5 lo monté como [un verificador](/blog/verificador-agente-ia-mentira/). El paso dos es en el que más insisten Willison y Pocock. Con un ejemplo de reservas inventado: ```ts // spec: WHEN la sala R1 está reservada de 10:00 a 11:00 // y alguien reserva R1 de 10:30 a 11:30 // THEN la API devuelve 409 y no guarda nada it("rechaza una reserva que se solapa", async () => { await book({ room: "R1", from: "10:00", to: "11:00" }); const res = await book({ room: "R1", from: "10:30", to: "11:30" }); expect(res.status).toBe(409); expect(await countBookings("R1")).toBe(1); }); ``` ## Antes de tu próximo `propose` No hace falta que dejes OpenSpec. Un "verify …" en prosa lo interpreta el agente; un comando con código de salida, no. Así que haz una cosa: revisa el `tasks.md` del próximo cambio y asegúrate de que cada tarea termine en un comando que el agente pueda ejecutar y que salga en verde o en rojo. Si una tarea no tiene comando, como una decisión de diseño o un documento, apunta qué verías al terminarla (un fichero que existe, una URL que responde) o márcala a propósito como revisión humana. Las que ningún comando puede confirmar por ti son las que merecen tu atención. **Lectura relacionada:** el paso que añadí antes de OpenSpec para decidir qué merece una spec está en [el post de los subagentes de Rydger](/blog/claude-code-subagentes-objetivos-stories/). ## Fuentes - GitHub, [lanzamiento de Spec Kit](https://github.blog/ai-and-ml/generative-ai/spec-driven-development-with-ai-get-started-with-a-new-open-source-toolkit/) (2 de septiembre de 2025). - Birgitta Böckeler, [_Understanding Spec-Driven-Development: Kiro, spec-kit, and Tessl_](https://www.martinfowler.com/articles/exploring-gen-ai/sdd-3-tools.html) (15 de octubre de 2025) y [_Harness engineering_](https://martinfowler.com/articles/exploring-gen-ai/harness-engineering.html) (2 de abril de 2026). - Thoughtworks Technology Radar: [spec-driven development](https://www.thoughtworks.com/radar/techniques/spec-driven-development) (noviembre de 2025), [OpenSpec](https://www.thoughtworks.com/radar/tools/openspec) y [agent instruction bloat](https://www.thoughtworks.com/radar/techniques/agent-instruction-bloat) (vol. 34, abril de 2026). - Anthropic, [buenas prácticas de Claude Code](https://code.claude.com/docs/en/best-practices) (leído el 28 de octubre de 2026). - Boris Cherny, [hilo sobre su flujo con Claude Code](https://threadreaderapp.com/thread/2007179832300581177.html) (2 de enero de 2026). - Simon Willison, [_Agentic Engineering Patterns_](https://simonwillison.net/guides/agentic-engineering-patterns/). - Mitchell Hashimoto, [_My AI Adoption Journey_](https://mitchellh.com/writing/my-ai-adoption-journey) (5 de febrero de 2026). - Matt Pocock, [skills](https://github.com/mattpocock/skills), incluida `grill-me`. - Mi experiencia con OpenSpec es de uso diario; el cambio `improve-seo-ai-visibility` está en el repo de esta web. --- **P.D.** ¿Tú también usas SDD a diario? Me interesa sobre todo qué parte has dejado de hacer y no has echado de menos. Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/ai-agent-verifier-false-claims/ Lang: en # AI Agent Verifier: Four of Five Builds Needed a Fix > Agents write two things: code your tests run, and claims about it nobody checks. A batch where a verifier caught four bad builds, the prompt and its limits **Short answer:** a coding agent's tests check its code, not what it says about its code, and that second part is where most of its confident mistakes end up. Give a separate agent, in a fresh context and on a stronger model, the job of tracing every claim back to the code or source behind it, and tell it to fail when unsure. In one batch of five tasks, that verifier sent four builds back for a fix before any of them reached the main branch, and let the fifth through. An agent hands you two kinds of output. One is code, which your tests execute. The other is everything it says about that code: the page copy, the README, the PR description, the figures in a table, the line that says "tests pass". Nothing executes that second kind. It costs the model nothing to write, and it reads exactly as confident when it's wrong. Most review setups I've seen, mine included until recently, point the second agent at the first kind. Here's what happened when I pointed it at both. ## A verifier sent four of five builds back, and two had tests for the bug This evening I ran five independent tasks in parallel on the repo behind my calculators. Each one was built by an agent on Sonnet in its own git worktree, then checked by a separate agent on Opus that could read the branch but not change it. If the verifier found anything serious, a third agent fixed it on the same branch. | Task | What the verifier caught | | --- | --- | | Page publishing an S&P 500 annual returns dataset | The text said three columns were copied "without recalculation". The extractor computes one of them from index levels and divides inflation by 100. Also a JSON-LD licence that would read as covering someone else's data, and a placeholder DOI in the BibTeX. | | November rate block for the I bond calculator | Semiannual inflation printed 100 times too small, and a 12-month comparison that ignored the three months of interest you lose cashing in early (31 CFR 359.7). | | Public MCP server for the calculators | The I bond fixed rate shown 100 times too small: a decimal printed with a % sign. | | Drafts for Show HN and Medium | Wrong posting time and a wrong reading of the Hacker News rule on promotion. | | A Spanish data page tracking monthly Euríbor and CPI | Nothing serious. It went through without a fix. | Each of the four has a fix commit on its branch, five to ten minutes after the build. The part that worries me is the tests. The I bond build shipped tests for the 12-month comparison and its break-even rate, the exact area with the cash-in bug. The MCP build shipped a test for the I bond tool, the one with the wrong rate. Both passed. The agent wrote the code and the tests from the same wrong assumption, so they agreed with each other. The I bond one is the one I'd have hated to ship. A rate shown at a hundredth of its value on a page about savings is the kind of mistake a reader screenshots. I need to own one more data point. The first drafts of this post got the batch wrong twice: once saying three tasks had passed clean, once saying the fifth had left an empty branch. Both times I'd read the branches while agents were still committing and written down a stale reading as fact. Both times the reviewer I'd set on the draft re-ran `git log` and failed it. The post you're reading is the corrected version. ## The instruction is six lines The setup above has a lot of plumbing, but the part doing the work is the verifier's brief. Trimmed to what matters, it says: ```text Your job is to find what is wrong, not to approve. For every claim the output makes about how something works, find the code or the cited source that makes it true. A claim nothing supports is a failure. Recompute at least two worked examples and compare them with the code. Report what was asked for and is missing, and what was done that nobody asked for. When unsure, fail. ``` Keep the last line. Without it, doubt resolves to "probably fine", and that's the default you're paying a second agent to override. ## A second model shares blind spots, so treat it as a filter The obvious objection is that you've asked one language model to mark another's homework. Same family, similar prompts, a real chance they agree on the same wrong answer. That's correct, and it's why I don't treat a pass as proof. What reduces it, in order of cost: a fresh context, so the verifier never sees the reasoning that produced the work, only the brief and the finished branch; a different and stronger model for the check than for the build; and moving each class of bug the verifier finds into a deterministic test, so next time it's caught without asking anyone's opinion. The I bond fix already did a little of that: it added a render test for the block text. What it doesn't reduce is the failure you never see. I can tell you the verifier caught four builds and passed one. I can't tell you whether that one, or any of the fixed ones, still has something it waved through, because measuring that means planting known bugs and counting the misses, and I haven't done it. ## I haven't measured the cost, and one batch is not a rate I haven't measured the tokens. Each task costs at least one build call and one verify call; this batch also paid for research, four fixes and one final review across the batch. Everything was committed within a quarter of an hour of the first build. The result is one batch on one repo. It shows the approach catches things my tests don't. It doesn't give you a rate to plan around. ## I've published it as two agent skills The run above used `agency`, a skill I'd been using privately in Claude Code. Today I cleaned it up and published it as [skeptic-agents](https://github.com/garbarok/skeptic-agents), MIT licensed. `skeptic-build` runs a batch through research, build, verify and fix; `skeptic-research` looks at one question from several angles in parallel and writes a sourced plan. Publishing changed three things. Correctness and the repo's written standards are now reviewed separately and reported side by side, an idea I took from the `code-review` skill in [Matt Pocock's skills](https://github.com/mattpocock/skills), which are the ones I use most. Every task now carries a brief with acceptance criteria and an out-of-scope list, so the verifier has a contract to check against. And the role prompts live inside each skill, because the installer copies only the skill's folder and my private version depended on files that never left my machine. One caveat before you install it. Everything in this post ran in Claude Code's workflow mode on the old version. The skill also has instructions for agents with subagents and for agents without them; the install works on those, but I haven't watched either run a real batch. ```bash npx skills@latest add garbarok/skeptic-agents ``` Claude Code, Codex and Copilot CLI can install it as a plugin instead; the README has those commands. ## Start with one document an agent wrote Take the last thing an agent wrote for you that makes claims (a README, a PR description, a page with numbers) and give it to a fresh session with the six lines above and read access to the code. Fix whatever it can't back up. If it finds something, that's your case for adding the step to how your team reviews agent work. **Related reading:** the verifier is one layer of the [harness around an agent](/en/blog/harness-engineering-why-your-agent-fails/), and the way I split work across subagents comes from [how I build Rydger](/en/blog/claude-code-subagents-stories-worktrees/). ## Sources - [garbarok/skeptic-agents](https://github.com/garbarok/skeptic-agents), version 0.1.0, MIT licence. - [mattpocock/skills](https://github.com/mattpocock/skills), whose `code-review` skill is the source of the two-axis review. - The batch: five tasks run on 27 October 2026 in the private repo behind my calculators. Evidence from one run, not a measured error rate. - Interest penalty on early I bond redemption: [31 CFR 359.7](https://www.ecfr.gov/current/title-31/subtitle-B/chapter-II/subchapter-A/part-359/subpart-A/section-359.7). --- **P.S.** If you've measured how often an LLM reviewer misses planted bugs, I'd like to see the numbers. Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/verificador-agente-ia-mentira/ Lang: es # Verificador de agentes de IA: devolvió cuatro de cinco > Un agente escribe código que tus tests ejecutan y frases sobre ese código que nadie revisa. Una tanda con cuatro builds devueltos, el prompt y sus límites **Respuesta corta:** los tests de un agente comprueban su código, no lo que dice de su código, y ahí es donde acaban la mayoría de sus errores dichos con seguridad. Pon a otro agente, en un contexto limpio y con un modelo más fuerte, a buscar el código o la fuente que respalda cada afirmación, y dile que si duda, suspenda. En una tanda de cinco tareas, ese verificador devolvió cuatro builds a arreglar antes de que llegaran a la rama principal, y dejó pasar el quinto. Lo que te entrega un agente tiene dos partes. Una es código, y tus tests lo ejecutan. La otra es todo lo que cuenta sobre ese código: el texto de la página, el README, la descripción de la PR, las cifras de una tabla, la frase de "los tests pasan". Esa segunda parte no la ejecuta nadie. Al modelo le sale gratis y suena igual de convincente cuando está mal. Casi todos los montajes de revisión que he visto, el mío incluido hasta hace poco, ponen al segundo agente a mirar la primera parte. Lo interesante pasa cuando le pides que mire las dos. ## Seis líneas de instrucciones hacen casi todo el trabajo Antes de contar qué pasó, el prompt, que es lo que te puedes llevar aunque no uses nada mío. Recortado a lo que importa, al verificador le digo esto: ```text Tu trabajo es encontrar lo que está mal, no aprobar. Para cada afirmación sobre cómo funciona algo, busca el código o la fuente citada que la hace verdad. Una afirmación sin respaldo es un fallo. Recalcula al menos dos ejemplos y compáralos con el código. Señala lo que se pidió y falta, y lo que se hizo sin que nadie lo pidiera. Si dudas, suspende. ``` No quites la última línea. Sin ella, la duda acaba en "seguramente está bien", y para eso no hace falta pagar a un segundo agente. ## Cuatro de cinco builds volvieron, y dos traían tests del fallo Esta tarde he lanzado cinco tareas independientes en paralelo en el repo de mis calculadoras. Cada una la construía un agente con Sonnet en su propio worktree de git, y la revisaba después otro agente con Opus que podía leer la rama pero no tocarla. Si el verificador encontraba algo serio, un tercer agente lo arreglaba en la misma rama. La tarea que mejor lo explica es una página para publicar un dataset con las rentabilidades anuales del S&P 500. El texto decía que las tres columnas se copiaban del fichero original "sin recalcular". El extractor, un script en Python que está en el repo desde septiembre, calcula una de ellas a partir del nivel del índice a final de año y divide la inflación entre 100. El verificador ha abierto el script, lo ha comparado con la página y la ha suspendido. De paso marcó un `license` en el JSON-LD que se leería como la licencia de unos datos que no son míos, y una entrada de BibTeX con un DOI de relleno. Otras tres también volvieron: - En el bloque de tipos de noviembre para la calculadora de bonos I, la inflación semestral salía 100 veces más pequeña, y la comparación a 12 meses no descontaba los tres meses de intereses que pierdes si rescatas antes de tiempo (31 CFR 359.7). - El servidor MCP público enseñaba el tipo fijo de esos mismos bonos 100 veces más pequeño: un decimal pintado con el símbolo de porcentaje. - Los borradores para Show HN y Medium tenían mal la hora de publicación y malinterpretaban la regla de Hacker News sobre autopromoción. La quinta, una página de datos en español con el Euríbor y el IPC del mes, pasó sin nada serio y no necesitó arreglo. Cada una de esas cuatro tiene su commit de arreglo en la rama, entre cinco y diez minutos después del build. Lo que me preocupa son los tests. El build de los bonos traía tests de la comparación a 12 meses y de su tipo de equilibrio, justo la zona del fallo del rescate. El del MCP traía un test de la herramienta de bonos, la del tipo mal puesto. Los dos pasaban. El agente escribió el código y los tests con la misma suposición equivocada, y claro, se daban la razón. El de los bonos es el que menos me habría gustado publicar. Un tipo de interés que se ve cien veces más pequeño en una página de ahorro es de los errores que alguien te captura y te reenvía. Y me toca contar otra cosa. Los primeros borradores de este artículo contaron mal la tanda dos veces: una decía que tres tareas habían salido limpias y otra, que la quinta había dejado la rama vacía. Las dos veces había mirado las ramas con los agentes todavía haciendo commits y di por buena una lectura que ya no lo era. Las dos veces el revisor que puse sobre el borrador volvió a ejecutar `git log` y lo suspendió. Lo que estás leyendo es la versión corregida. ## Un segundo modelo no prueba nada, solo filtra La objeción es evidente: le has pedido a un modelo de lenguaje que corrija los deberes de otro. Misma familia, prompts parecidos y bastantes papeletas para que se equivoquen en lo mismo. Es así, y por eso un aprobado no lo tomo como prueba de nada. Hay tres cosas que lo reducen, de la más barata a la más cara. Un contexto limpio, para que el verificador no vea el razonamiento que produjo el trabajo, solo el brief y la rama terminada. Un modelo distinto y más fuerte para revisar que para construir. Y convertir cada tipo de fallo que encuentra en un test determinista, para que la próxima vez lo pille sin preguntarle a nadie. El arreglo de los bonos ya hizo un poco de eso: añadió un test que comprueba el texto del bloque. Lo que no reduce es el fallo que no ves. Sé que el verificador devolvió cuatro builds y aprobó uno. No sé si en ese, o en los arreglados, se le escapó algo, porque para medirlo habría que meter fallos conocidos a propósito y contar los que se le escapan, y no lo he hecho. Tampoco he medido los tokens. Cada tarea cuesta como mínimo una llamada para construir y otra para verificar; esta tanda además pagó la investigación, cuatro arreglos y una revisión final del conjunto. Todo estaba en commits en un cuarto de hora desde el primer build. Es una tanda en un repo: enseña que esto pilla lo que mis tests no pillan, pero no te da una tasa con la que planificar. ## Lo he publicado como dos agent skills La tanda de arriba la hizo `agency`, una skill que llevaba tiempo usando en privado con Claude Code. Hoy la he limpiado y la he publicado como [skeptic-agents](https://github.com/garbarok/skeptic-agents), con licencia MIT. `skeptic-build` pasa una tanda de tareas por investigar, construir, verificar y arreglar; `skeptic-research` mira una pregunta desde varios ángulos a la vez y deja un plan con fuentes. Al publicarla he cambiado tres cosas. La revisión de corrección y la de las normas escritas del repo van ahora por separado y salen una al lado de la otra; la idea es de la skill `code-review` de [las skills de Matt Pocock](https://github.com/mattpocock/skills), que son las que más uso. Cada tarea lleva un brief con criterios de aceptación y una lista de lo que queda fuera, para que el verificador tenga un contrato contra el que revisar. Y los prompts de cada rol van dentro de la skill, porque el instalador solo copia esa carpeta y mi versión privada dependía de ficheros que nunca salían de mi ordenador. Una advertencia antes de instalarla: todo lo de este artículo se ejecutó en el modo workflow de Claude Code con la versión antigua. La skill también trae instrucciones para agentes con subagentes y sin ellos; la instalación funciona ahí, pero no he visto a ninguno de los dos sacar adelante una tanda real. ```bash npx skills@latest add garbarok/skeptic-agents ``` En Claude Code, Codex y Copilot CLI también se instala como plugin; los comandos están en el README. ## Empieza por un documento que te haya escrito un agente Coge lo último que te haya escrito un agente con afirmaciones dentro (un README, la descripción de una PR, una página con cifras) y pásaselo a una sesión nueva con las seis líneas de arriba y acceso de lectura al código. Arregla lo que no pueda respaldar. Si encuentra algo, ya tienes el argumento para meter este paso en cómo revisa tu equipo el trabajo de los agentes. **Lectura relacionada:** el verificador es una de las capas del [harness que rodea a un agente](/blog/harness-engineering-por-que-falla-tu-agente/), y el reparto entre subagentes sale de [cómo trabajo en Rydger](/blog/claude-code-subagentes-objetivos-stories/). ## Fuentes - [garbarok/skeptic-agents](https://github.com/garbarok/skeptic-agents), versión 0.1.0, licencia MIT. - [mattpocock/skills](https://github.com/mattpocock/skills), de cuya skill `code-review` viene la revisión en dos ejes. - La tanda: cinco tareas del 27 de octubre de 2026 en el repo privado de mis calculadoras. Es lo que pasó en una ejecución, no una tasa de error medida. - Penalización por rescatar antes de tiempo un bono I: [31 CFR 359.7](https://www.ecfr.gov/current/title-31/subtitle-B/chapter-II/subchapter-A/part-359/subpart-A/section-359.7). --- **P.D.** Si has medido cada cuánto se le escapan fallos plantados a un revisor LLM, me interesan los números. Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/claude-code-subagents-stories-worktrees/ Lang: en # Claude Code subagents: my workflow from idea to merge > Claude Code subagents in Rydger: Opus coordinates stories, Sonnet implements, Fable advises, with separate worktrees and shared tests across iOS and Android. **Short answer:** I use Claude Code subagents to implement Rydger stories while Opus coordinates dependencies. Sonnet handles much of the implementation, Haiku gets simpler tasks, and Fable is available for difficult decisions. The useful part is being able to step away for hours because each assignment says what can start, which branch it needs and what evidence must come back. The Android first-ride check in Rydger has an iOS story blocking it. The Swift implementation has to produce `first-ride-check-cases.json` before Kotlin can run those cases against the port. Putting two platform names on a plan hasn't made the work independent. The project is [Rydger](/en/apps/rydger/), my maintenance and running-cost app for motorcycles and cars. It started on iOS; I've also built an Android version. I now spend more time deciding what the product should achieve. I still care about implementation details, but I don't want every decision about who edits which file to need me at the keyboard. I've left agents writing and running tests, including UI checks in the iOS and Android simulators, while I worked on other things or left the computer. I haven't measured hours saved, but I no longer need to direct every implementation step. ## OpenSpec held the implementation plan; the objective came first My earlier routine was to prepare an OpenSpec change, then implement it. That still has a job. What needed more space was the conversation before the specification: is this idea worth building, and what would success look like? I work through that with Opus 5.5. We discuss the idea until it becomes a business objective, split that into epics, then turn an epic into stories. I approve the work before execution starts. The hierarchy is familiar project management. What changes is who can act on it. **A dependency written into a story is something the orchestrator can check without asking me to remember it.** GitHub holds the objective, epics and vertical stories. OpenSpec's `tasks.md` holds the engineering checklist. A story that changes app behaviour links the OpenSpec change and the tasks it covers. Completing the checklist doesn't tell me whether the business objective worked; that needs its own evidence. The project's `/epics`, `/stories` and `/pickup` skills connect those steps. They are local instructions I've put around Claude Code, not built-in commands everyone gets after installation. ## The Android story needed a Swift test fixture first One actual epic is about activation on the first ride: help someone set up automatic mileage, confirm that the first ride recorded, and show what to fix when it didn't. Two stories inside it carry the important dependency: | Story | Observable result | Required input | | --- | --- | --- | | Check the first ride on iOS | State rule, first-ride confirmation and a help screen | The iOS onboarding work | | Check the first ride on Android | Equivalent behaviour with Android's permissions and tracking setup | The iOS story's rule and shared test cases | The iOS story produces `first-ride-check-cases.json`. Kotlin runs the same cases in the Android story. That gives the port a concrete reference instead of asking a second agent to invent its own definition of a recorded first ride. Some integration details must differ. The iOS checklist includes a manual Shortcuts check; Android has Bluetooth and notification permissions to handle. Shared rule cases don't prove those platform integrations behave identically. The Android issue explicitly depends on the iOS issue. Running them together would mean implementing against a moving input. Different platforms do not automatically mean independent work. ## Opus holds the queue; the executors get bounded assignments I start the main agent, then let Claude choose how to delegate within the agreed scope. My current arrangement is Opus coordinating, Sonnet implementing, and Haiku doing easier work. That's a description of my setup, not a model comparison. Exploration comes before implementation. The worker needs enough context to understand the assigned slice, including the decisions that affect it. I can't assume it knows everything I discussed with the main agent. Anthropic documents the separate context and configuration in its [subagent guide](https://code.claude.com/docs/en/sub-agents). For difficult decisions, `.claude/agents/advisor.md` uses Fable. The advisor inspects the repo and returns a concrete recommendation for the executor. Its instructions say read-only, but its tools include `Bash`: that instruction alone is not a technical restriction on every possible write. Starting the orchestrator also doesn't authorize every later action. The project's written default leaves merges to me; when I ask an agent to merge, that is a specific delegation. Store submissions and steps marked `founder-action` remain mine to carry out. ## A separate worktree still owes you an integration Each implementation works in a different worktree. The directories stay separate while the agents edit. Incompatible changes can still meet later. I've had agents expect to touch different things, then collide in a shared file. The conflict gets resolved while integrating into the parent or epic branch. It hasn't been a reason to abandon the setup. It is work the setup still leaves someone to do. The first-ride Android PR records a less obvious collision. Regenerating translations removed strings from earlier work because those strings had been added directly to `strings.xml`. They needed to go into the manifest that feeds the generator. Git could accept the changes and the next regeneration could still erase them. That is why an assignment needs a base branch and an account of the artifacts it produces. With Claude Code's automatic worktree isolation, also check which branch the new worktree starts from; don't assume it is your epic branch. The [worktree workflow](https://code.claude.com/docs/en/worktrees) explains the mechanism. You still need an integration order. ## Green tests have a scope, including after a merge There's an obvious objection: the same agents can write an implementation and tests that agree on the wrong behaviour. They can. Acceptance criteria and shared fixtures give this port a reference, but they aren't proof that every device integration works. The PRs record different kinds of evidence, and those distinctions matter. The iOS PR records an initial failure in the new UI test, followed by passing reruns after the fix. The Android PR records unit tests and a manual emulator check; it explicitly says that this area added no instrumented tests. A road test using the real iOS Shortcut remains separate. Calling all of that automated end-to-end coverage would be generous in exactly the wrong direction. The rule I'd copy is to ask for the executed command, its result and what remains unverified. Repeat the affected checks after integration. A worker's report that everything looks fine isn't a substitute for execution evidence. That's the generate-and-check boundary I wrote about in [the harness article](/en/blog/harness-engineering-why-your-agent-fails/). | What you're seeing | First thing to inspect | | --- | --- | | Android is waiting for an iOS rule that keeps changing | Story dependencies and whether the base branch contains the required result | | Two workers changed the same file | Ownership and integration order, as well as worktree separation | | Regeneration removes changes that already merged | The generator's source of truth | | A worker reports that tests passed | The execution output and the behaviour those tests actually cover | ## Give one worker a story it can finish without guessing I'd start with one assignment. Before launching a second context, write down this much: ```text Observable result and acceptance criteria: Dependencies and evidence they are already integrated: Base branch and assigned worktree: Owned files or area; source of generated artifacts: Checks to execute and evidence to return: Open decisions and the condition for stopping to ask me: PR destination; who may approve and integrate: ``` The [downloadable kit](/downloads/claude-code-subagents-kit.zip) contains that worksheet in both languages, an orchestrator brief and an advisor restricted to reading tools. It is an adaptation for this article, not Rydger's private repository or an installed scheduler. A prompt requests behaviour; it doesn't enforce every instruction. Run one story and inspect the evidence it returns. Then add an independent story. If both need the same generated file, you've found a coordination decision worth making before parallel execution. Keep an eye on usage too: workers consume it even when you discard their output. Giving some tasks to Sonnet or Haiku doesn't establish that the whole process costs less: repeated exploration and retries count. Anthropic's [cost guide](https://code.claude.com/docs/en/costs) covers that side. I can stand behind the autonomy I've gained, but I don't yet have a savings figure to put beside it. Before the next session you leave running, write down the result it must bring back and the decision that should make it stop and ask you. Test that assignment first. ## Sources - Anthropic: [custom subagents](https://code.claude.com/docs/en/sub-agents), [parallel sessions with worktrees](https://code.claude.com/docs/en/worktrees), and [usage management](https://code.claude.com/docs/en/costs), checked October 21, 2026. - My Rydger delivery workflow and skills: the first-ride epic, its iOS and Android stories and their PRs. The repository is private. Those PR records describe their own verification runs; I haven't rerun the app suites for this article. **Related reading:** [the skills behind my coding workflow](/en/blog/agent-skills-coding-workflow/) and [how I connect that process with loops](/en/blog/stop-prompting-write-loops/). --- **P.S.** Where has parallel agent work cost you more effort: assigning the stories or integrating what comes back? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/claude-code-subagentes-objetivos-stories/ Lang: es # Subagentes de Claude Code: de una idea al merge en Rydger > Subagentes de Claude Code en Rydger: Opus orquesta, Sonnet implementa y Fable asesora, con stories, worktrees y pruebas compartidas entre iOS y Android. **Respuesta corta:** uso los subagentes de Claude Code para implementar stories de Rydger mientras Opus coordina las dependencias. Sonnet hace buena parte del trabajo, Haiku entra en tareas sencillas y Fable sirve de asesor cuando hay una decisión difícil. Lo que me permite apartarme del ordenador durante horas es dejar claro qué puede empezar, desde qué rama y cómo se comprueba el resultado. En la épica del primer trayecto de Rydger, la story de Android está bloqueada por la de iOS. Una tiene que dejar `first-ride-check-cases.json`; la otra lo necesita para comprobar la misma regla en Kotlin. Separar las plataformas no las hace independientes. El ejemplo más claro lo tengo en [Rydger](/apps/rydger/), mi app para llevar el mantenimiento y los gastos de la moto o del coche. Nació en iOS y he creado también la versión Android. Ahora dedico más tiempo a decidir qué tiene que conseguir la app. Sigo entrando en los detalles técnicos, pero ya no quiero ser quien reparte cada fichero a mano. He podido dejar agentes escribiendo y ejecutando tests, con pruebas de UI en los simuladores de iOS y Android, mientras yo hacía otras cosas. No tengo una medición de horas ahorradas ni una comparativa entre modelos. Lo que sí he ganado es margen para dejar de dirigir cada paso de la implementación. ## La especificación me decía qué construir; faltaba decidir para qué Con OpenSpec primero preparaba la especificación y después la implementaba. Me sigue sirviendo. Lo que me faltaba estaba un paso antes: discutir una idea hasta convertirla en algo que mereciera implementarse. Ahora empiezo hablando con Opus 5.5. Le voy planteando ideas, discutimos el alcance y acabamos con un objetivo de negocio. De ahí salen las épicas y, dentro de cada épica, las stories, que apruebo antes de ponerlas a trabajar. No he inventado la gestión de proyectos por tener un terminal abierto. El cambio práctico es que **las dependencias que antes interpretaba yo pasan a ser instrucciones que el orquestador puede consultar**. Si una story necesita el resultado de otra, esa relación queda escrita en GitHub. OpenSpec conserva su sitio: la story describe el resultado que alguien podrá usar y sus criterios de aceptación; el `tasks.md` de OpenSpec mantiene la checklist de ingeniería. Una story que cambia comportamiento enlaza el cambio y las tareas que cubre. No sustituyo una lista por otra ni doy por terminado el objetivo porque las casillas estén marcadas. Con las skills `/epics`, `/stories` y `/pickup` paso del objetivo a las stories y de ahí a implementarlas. Son instrucciones de mi proyecto, no comandos que aparezcan por instalar Claude Code. ## Android tenía que esperar a una fixture de iOS Una épica real se llama «Activar en la primera salida»: ayudar a quien acaba de configurar los kilómetros automáticos a comprobar que su primer trayecto se ha registrado. Dentro hay una pareja de stories que explica el sistema mejor que cualquier dibujo de agentes trabajando en paralelo: | Story | Qué tenía que dejar funcionando | Qué necesitaba antes | | --- | --- | --- | | Comprobar el primer trayecto en iOS | Regla de estado, tarjeta de confirmación y ayuda cuando algo falla | El onboarding de iOS | | Comprobar el primer trayecto en Android | El mismo comportamiento, adaptado a los permisos y al seguimiento de Android | La regla y los casos compartidos de la story de iOS | La primera crea `first-ride-check-cases.json`. La siguiente pasa esos casos en Kotlin. El objetivo no era que dos agentes inventaran cada uno qué significa «primer trayecto registrado», sino que las dos plataformas comprobaran la misma regla. Hay diferencias que no se pueden copiar: iOS tiene una comprobación manual del Atajo; Android tiene sus permisos de Bluetooth y notificaciones. Compartir los casos de la regla no convierte las integraciones de las dos plataformas en iguales. En GitHub, la story de Android depende expresamente de la de iOS. Lanzarlas a la vez habría obligado a un agente a trabajar contra algo que todavía podía cambiar. **Dos tareas para plataformas distintas también pueden tener una dependencia.** ## Opus coordina; los demás reciben un trabajo acotado Lanzo el agente principal y después dejo que Claude vaya decidiendo cómo delegar dentro del alcance acordado. Uso Opus como orquestador, Sonnet para implementar y Haiku para cosas más sencillas. Es mi reparto actual, no el resultado de un benchmark. Primero exploran el código y después implementan la parte asignada. El encargo tiene que incluir el contexto que afecta a esa story; no basta con confiar en que el subagente conozca todo lo que he hablado con el principal. La [documentación de subagentes](https://code.claude.com/docs/en/sub-agents) explica su contexto separado y cómo definirlos. Para las decisiones difíciles tengo `.claude/agents/advisor.md`, configurado con Fable. Inspecciona el repo y propone una recomendación concreta que el ejecutor lleva a cabo. Ese asesor tiene una instrucción de solo lectura, pero incluye `Bash`: la frase «no modifiques» no equivale a quitarle técnicamente toda capacidad de hacerlo. Tampoco doy permiso para cualquier cosa por arrancar el orquestador. La regla escrita del proyecto reserva los merges al fundador; si le encargo uno a un agente, esa autorización es concreta. Publicar en las tiendas y los pasos marcados como `founder-action` siguen reservados para mí. ## Los worktrees evitan pisarse mientras editan; los conflictos llegan al integrar Cada implementación va en un worktree diferente. Eso separa los directorios de trabajo, pero no hace desaparecer los cambios incompatibles. Me ha pasado: los agentes creen que van a tocar cosas diferentes y acaban cambiando algún fichero común. Luego hay que resolver el conflicto al integrar en la rama padre o en la rama de la épica. No me ha roto el sistema. Es parte del trabajo que sigue existiendo. Hay un ejemplo más discreto en la PR de Android del primer trayecto. Al regenerar las traducciones desaparecían unas cadenas que otro trabajo había añadido directamente a `strings.xml`. Hubo que incorporarlas al manifiesto que alimenta el generador. No era un conflicto de Git: el código se podía integrar y aun así perder contenido en la siguiente generación. Por eso una asignación necesita una rama base y una explicación de qué artefactos produce. Si usas el aislamiento automático de Claude Code, comprueba también desde qué rama crea el worktree; no des por hecho que será la rama de tu épica. La [guía de worktrees](https://code.claude.com/docs/en/worktrees) cubre el mecanismo; el orden de integración lo tienes que decidir tú. ## El test que pasa en una rama aún tiene que sobrevivir al merge La objeción es inmediata: «Si los agentes escriben el código y sus tests, pueden ponerse de acuerdo en estar equivocados». Sí. En este caso los criterios de aceptación y la fixture compartida dan una referencia concreta, pero no prueban por sí solos que todos los dispositivos se comporten bien. Cada PR deja constancia de lo que se comprobó. La de iOS registra un fallo inicial en el test de UI nuevo y una ejecución posterior que pasó tras corregirlo. La de Android registra tests unitarios y una comprobación manual en el emulador; también dice que esa parte no añadió tests instrumentados. Y la prueba en carretera con el Atajo real sigue siendo una comprobación aparte. No voy a llamar «cobertura automática de extremo a extremo» a esa mezcla. Mi regla para copiar este flujo es exigir el comando ejecutado, su resultado y lo que quedó sin comprobar. Al integrar, repetir las comprobaciones que pueda afectar la combinación. Un informe del agente diciendo «todo bien» no sustituye esa evidencia. Es la misma separación entre generar y comprobar que conté en [el artículo del harness](/blog/harness-engineering-por-que-falla-tu-agente/). | Si ves esto | Qué revisaría primero | | --- | --- | | Android espera a una regla que iOS aún está cambiando | La dependencia entre stories y si la rama base ya contiene el resultado | | Dos agentes cambian el mismo fichero | El reparto y el orden de integración, además de los worktrees | | Una regeneración borra cambios que ya estaban integrados | La fuente que consume el generador | | El agente dice que los tests pasan | La salida de la ejecución y qué demuestra realmente ese test | ## Empieza con una story que otro agente pueda entender No empezaría desplegando una cuadrilla de subagentes. Cogería una story y le escribiría este encargo, antes de abrir otro contexto: ```text Resultado visible y criterios de aceptación: Dependencias y evidencia de que ya están integradas: Rama base y worktree asignado: Ficheros o área de responsabilidad; fuente de los generados: Comprobaciones que debe ejecutar y evidencia que debe devolver: Decisiones pendientes y condición para parar y consultarme: Destino de la PR; quién puede aprobar e integrar: ``` Te dejo el [kit descargable](/downloads/claude-code-subagents-kit.zip), con esa ficha en ambos idiomas, un encargo para el orquestador y un asesor limitado a herramientas de lectura. Es una adaptación para este artículo; no es el repo privado de Rydger ni un scheduler listo para funcionar sin configuración. Los prompts piden un comportamiento, no lo garantizan. Empieza con una story y revisa qué ha hecho el agente y cómo lo ha comprobado. Después añade otra independiente. Si ambas necesitan el mismo fichero generado, acabas de encontrar una decisión que conviene resolver antes de darles trabajo en paralelo. Y mira el consumo: cada subagente cuenta para el límite de uso, aunque su trabajo no termine sirviendo. Elegir Sonnet o Haiku para una parte no demuestra que el flujo completo sea más barato: también cuentan la exploración repetida y los reintentos. Anthropic lo recoge en su [guía de costes](https://code.claude.com/docs/en/costs). Yo puedo afirmar que he ganado autonomía; todavía no puedo ponerle una cifra de ahorro. Antes de dejar la próxima sesión trabajando sola, escribe qué resultado te tiene que traer y en qué punto debe parar para preguntarte. Ese es el primer encargo que probaría. ## Fuentes - Anthropic: [subagentes personalizados](https://code.claude.com/docs/en/sub-agents), [sesiones paralelas con worktrees](https://code.claude.com/docs/en/worktrees) y [gestión del consumo](https://code.claude.com/docs/en/costs), consultadas el 21 de octubre de 2026. - Caso propio: flujo de entrega y skills de Rydger, con la épica del primer trayecto, sus dos stories de iOS y Android y sus PR. El repositorio es privado; las comprobaciones de esas PR son evidencia de esas ejecuciones, no una nueva ejecución hecha para este artículo. **Lectura relacionada:** [las skills con las que organizo mi flujo de código](/blog/agent-skills-flujo-codigo/) y [cómo conecto ese proceso con los loops](/blog/deja-de-promptear-escribe-loops/). --- **P.D.** ¿Qué te ha dado más trabajo al juntar subagentes: repartir las stories o integrar lo que vuelve? Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/wealthsim-calculator-first-session/ Lang: en # WealthSim: correct maths, a frustrating first session > WealthSim's preset and calculator disagreed. Fixing preview inputs, early ads and a disappearing result led to My Plan, with retention still unproven. Tap a preset in my iOS app and the projected balance could drop. The card had calculated one amount; the calculator produced another. Under the right conditions, that same tap could also trigger a full-screen ad. Quite an introduction to an app that asks you to trust its numbers. [WealthSim](/en/apps/wealthsim/) is my compound interest calculator, available on the web and as a native iOS app. You give it a starting balance, monthly contributions and return assumptions. It projects how the balance could grow. The review I recorded on October 5 exposed a mismatch: preset cards assumed no management fee, while applying a preset kept the calculator's existing fee. Further down the same screen, editing the controls scrolled the answer out of sight. I could trace the calculation through the code. Someone holding the phone had to scroll back up to discover what their last adjustment had done. ## The missing assertion connected two parts of the UI Both paths used `InvestmentProjector`. The preview passed zero for the management fee and inflation. `CalculatorSession.applyPreset` preserved the user's settings, whose defaults were a 0.25% annual fee and 2% inflation. The fee caused the nominal balance to differ. Inflation also belonged in the shared context, although it affects the today's-money reading. In the fix, I passed both active values into `PresetStrip.preview` so the card used the assumptions that would remain active after the tap. A correct formula test cannot catch every caller passing the wrong inputs. **The additional assertion was that accepting a preview should produce the balance it displayed.** This is the comparison from `FirstSessionUXTests.swift`, parameterized over the preset catalog and using the session's default settings: ```swift @Test(arguments: PresetCatalog.presets) func presetPreviewMatchesAppliedBalance(preset: Preset) throws { let session = CalculatorSession() let preview = PresetStrip.preview( for: preset, managementFee: try #require(Decimal(string: "0.25")), inflation: 2, currencyCode: session.currencyCode ) session.applyPreset(preset) #expect(preview.finalBalance == session.presentation?.finalBalance) } ``` That protects the initial configuration, not every fee a user might enter. Broader coverage would need more inputs. Its value is that it compares the preview and the applied result, rather than testing the financial formula once more in isolation. The same assertion fits a price card that changes at checkout or an estimate that changes when you save it. Keep the user's configuration in place, accept the preview, and compare the outcome. ## My ad counter treated exploring as a completed task The old coordinator had `actionsPerAd = 1`. Applying a preset called `onSignificantAction`, just as saving or reopening a scenario did. With consent, a prepared ad and the other eligibility conditions satisfied, someone's first exploratory tap could trigger an interstitial. That callback grouped together gestures with very different meanings. Trying a preset is how you find out whether the app does anything useful. I had made it an opportunity to interrupt that discovery. In the same fix, I removed the callback from `applyPreset` and protected the entire first session plus the first 24 hours after first launch, whichever ends later. After that protection, the counter requires three completed tasks and allows at most two interstitials per session. The task count survives app restarts. I also removed the banner above the calculator result. The free version still has ads; these changes reduce opportunities to show them while someone experiments with inputs. I do not have a before-and-after revenue comparison that prices that tradeoff. ## A live result needs to stay within sight of the control The old layout placed the result above the controls in a long scroll view. Recalculating on every edit did little for someone who could no longer see the answer. The redesign added `PinnedResultBar`. Once the large result scrolls past the top, a compact bar keeps the projected year and balance visible during editing. The chart also changed to bars separating contributions from interest. The projection engine did not need new maths for this. The interaction needed the answer to stay near the input. A screenshot of the initial viewport could look fine while missing the whole problem; you had to scroll to a control and change it. This is the review checklist I would reuse, ordered from a specific inconsistency to the larger product bet: | What the person encounters | What I changed | What I can verify | | --- | --- | --- | | A preset and its applied result disagree | Feed the active fee and inflation into the preview | Compare preview and result after applying the preset | | Exploration can trigger an ad | Exclude presets from the counter and protect first use | Check that the gesture cannot enable an interstitial | | Editing scrolls the answer away | Keep a compact balance visible | Move a control with the main result offscreen | | A saved projection offers no task for next month | Add My Plan and balance check-ins | Test the flow; whether anyone returns needs actual usage evidence | ## My Plan gives the projection something real to compare with A calculator can serve someone perfectly well in one visit. Closing it after getting an answer is not a failure. To make another visit worthwhile, I needed a task that would change over time. My Plan lets you turn a projection into a goal with an amount and date, then enter your actual balance each month and compare it with the plan's route. The free tier allows one active plan. A monthly reminder is optional, and notification permission is requested when you enable it. The distinction lives in `GoalPlan` and `PlanCheckIn`. A saved projection holds assumptions; a check-in records an observation. `PlanStore.logCheckIn` updates the month's entry if one already exists, so correcting October's balance does not produce a second October on the chart. There is a simplification behind that route. `PlanRoute` takes annual values from `InvestmentProjector` and interpolates between them for monthly comparisons. It is a reference built from the plan's assumptions, not a prediction of the market's path. Entering balances is also manual work. A reminder is only useful if the comparison earns that effort. What I want to find out next is whether someone logs a balance and returns in another month to compare it. A notification open alone would not tell me that the plan helped. ## I built more than I can currently validate The October 5 review recorded that App Store Connect was not providing retention data and that the app lacked product analytics to answer these questions. As of October 6, I cannot report a measured retention improvement from this redesign. There is another problem with the story I would like to tell: one commit bundled My Plan, the visual redesign and Pro features into one commit. Even if usage later rises, that bundle will not tell me which change caused it. It was substantially more work than fixing the preview and removing the top banner. If I repeated the process, I would start with those smaller fixes, watch someone unfamiliar with the app use the flow, and treat My Plan as a separate hypothesis. It costs more to build and depends on people wanting that monthly task. The preview mismatch and the early interruption could be fixed without making that bet. Pick one card in your product that previews an outcome. Record its value, take the action, and compare the result with the user's settings still applied. A mismatch gives you something concrete to fix before you open the roadmap. ## Sources and scope This account uses my October 5 UI review and WealthSim's private repository history, specifically the first-session commit and the redesign commit that added My Plan. The reproduced test is in `FirstSessionUXTests.swift`; monthly entries and the reference route are in `PlanStore.swift` and `PlanMath.swift`. These are code changes, not results from a retention experiment or confirmation that every feature is available on the App Store. **Related reading:** storing these records comes with its own decisions. In my other app, I wrote about [how SwiftData and CloudKit shape the model before anything syncs](/en/blog/cloudkit-sync-data-model-cost/). **Case study:** the [WealthSim case study](/en/apps/wealthsim/#caso) gathers the decisions and what went wrong in the app. --- **P.S.** Found a preview that promised something different from what its button did? Tell me the example on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/wealthsim-primera-sesion-mi-plan/ Lang: es # WealthSim: calcular bien no bastaba para usar la app > WealthSim mostraba un saldo en el preset y otro al abrirlo. Anuncios al explorar, resultados fuera de pantalla y el paso de calcular a revisar un plan. Una tarjeta de WealthSim mostraba un saldo. La tocabas y la calculadora te daba otro, más bajo. Con suerte, además, aparecía un anuncio a pantalla completa para darte tiempo a pensar cuál de los dos era el bueno. [WealthSim](/apps/wealthsim/) es mi calculadora de interés compuesto, con versión web y app nativa de iOS. Metes un capital inicial, una aportación mensual y unas hipótesis de rentabilidad; te devuelve una proyección. En la revisión del 5 de octubre encontré que la tarjeta del preset calculaba sin comisiones, pero al aplicarlo conservaba las de la calculadora. El mismo motor, dos entradas distintas que la pantalla presentaba como si fueran la misma. La revisión también señalaba que el resultado desaparecía al bajar a los controles. Yo podía explicar cada número mirando el código. La persona con el móvil tenía que fiarse de una cifra que cambiaba al tocarla y hacer scroll para ver qué había hecho su último ajuste. ## El test que faltaba estaba entre la tarjeta y el resultado La vista previa del preset llamaba a `InvestmentProjector` con comisión e inflación a cero. `CalculatorSession.applyPreset` conservaba las que ya tenía el usuario: por defecto, una comisión anual del 0,25 % y una inflación del 2 %. La comisión explicaba la diferencia en el saldo nominal. La inflación también tenía que viajar con el mismo contexto, aunque afecte a la lectura en dinero de hoy. En el arreglo pasé ambos valores a `PresetStrip.preview`, de modo que la tarjeta usara las mismas hipótesis que quedarían activas al tocarla. **La propiedad que quería proteger era la igualdad entre lo que la tarjeta enseña y lo que ocurre al aplicarla.** Tener tests de la fórmula no comprueba esa relación. En `FirstSessionUXTests.swift` quedó un test parametrizado con los presets del catálogo. Este es el fragmento que hace la comparación, usando los valores por defecto de la sesión: ```swift @Test(arguments: PresetCatalog.presets) func presetPreviewMatchesAppliedBalance(preset: Preset) throws { let session = CalculatorSession() let preview = PresetStrip.preview( for: preset, managementFee: try #require(Decimal(string: "0.25")), inflation: 2, currencyCode: session.currencyCode ) session.applyPreset(preset) #expect(preview.finalBalance == session.presentation?.finalBalance) } ``` Ese test tiene un límite: cubre la configuración inicial. Si mañana quiero proteger todas las combinaciones de comisiones editables, tendré que ampliar las entradas. Pero ya compara dos caminos de la app que antes podían discrepar sin que el test de la fórmula se enterara. La misma comprobación sirve para una tarifa que cambia al abrir el checkout o una estimación que cambia al guardarla. Antes de añadir otro caso al motor, compara la vista previa con el resultado de la acción que ofrece. ## Aplicar un preset contaba como ocasión para enseñar publicidad El coordinador de anuncios tenía `actionsPerAd = 1`. Aplicar un preset emitía `onSignificantAction`, igual que guardar o reabrir un escenario. Si había consentimiento, un anuncio preparado y se cumplían las demás condiciones, el primer gesto de exploración podía acabar en un interstitial. Para el contador eran acciones equivalentes. Para quien está probando la app, tocar un preset apenas es averiguar qué hace. En el mismo commit quité esa llamada de `applyPreset`. Añadí protección durante la primera sesión y las primeras 24 horas desde el primer arranque, hasta que terminen ambas. Después, el contador exige tres tareas completadas y permite como máximo dos interstitials por sesión. El contador de tareas se conserva entre arranques. También quité el banner que estaba encima del resultado. Sigue habiendo publicidad en la versión gratuita. Elegí reducir las interrupciones mientras alguien está probando valores, y acepté que eso elimina oportunidades de mostrar anuncios. No tengo una comparativa de ingresos que permita ponerle un precio a la decisión. ## El saldo tenía que seguir visible mientras movía el slider El resultado estaba encima de los controles dentro de un scroll largo. Podía actualizarlo en cada cambio y, aun así, obligar al usuario a subir para verlo. El cálculo era inmediato; comprobarlo no. El rediseño añadió `PinnedResultBar`: cuando la tarjeta grande sale por arriba, una barra compacta conserva el año y el saldo proyectado mientras editas. El gráfico también pasó a mostrar barras con aportaciones e intereses separados. Esto no necesitó una fórmula nueva. Necesitó mantener la respuesta cerca del gesto que la cambia. La captura bonita de la primera pantalla no enseñaba ese problema: había que bajar hasta un control y usarlo. La revisión de primera sesión me dejó esta tabla. El orden va de una inconsistencia concreta a una decisión de producto bastante más cara: | Lo que veía la persona | Cambio que hice | Qué puedo comprobar | | --- | --- | --- | | El preset y el resultado daban saldos distintos | Pasar las comisiones e inflación activas a la vista previa | Comparar preview y resultado tras aplicar el preset | | Explorar podía disparar un anuncio | Sacar los presets del contador y proteger el primer uso | Comprobar que ese gesto no habilita un interstitial | | Editar dejaba el resultado fuera de pantalla | Añadir la barra compacta del saldo | Mover un control con la tarjeta grande fuera de la vista | | Guardar una proyección no daba una tarea para el mes siguiente | Añadir «Mi plan» y el registro de saldo | Verificar el flujo; saber si alguien vuelve requiere observar uso real | ## Mi plan añade un saldo real a una curva hipotética Una calculadora puede cumplir su función en una sola visita. No considero que alguien que hace una cuenta y se va haya usado mal WealthSim. Para justificar otra visita necesitaba ofrecerle otra tarea. Con «Mi plan» puedes convertir una proyección en un objetivo con importe y fecha. Después registras tu saldo real cada mes y lo comparas con la trayectoria del plan. La versión gratuita permite un plan activo. El recordatorio mensual es opcional y pide permiso al activarlo. El cambio de modelo aparece en `GoalPlan` y `PlanCheckIn`. Una proyección guardada conserva hipótesis. Un registro mensual añade una observación de lo que ha pasado. `PlanStore.logCheckIn` actualiza la entrada del mes si ya existe: corregir el saldo de octubre no debe dibujar un segundo octubre. Hay una limitación que conviene explicar junto al gráfico. `PlanRoute` usa los resultados anuales de `InvestmentProjector` e interpola entre ellos para colocar los meses. La trayectoria es una referencia calculada con las hipótesis del plan; no representa cómo se moverá el mercado. Y registrar el saldo requiere trabajo manual. Si esa comparación no te sirve, un recordatorio solo añade una molestia. Por eso la pregunta que me interesa ahora es si alguien registra un saldo y vuelve otro mes a compararlo. Abrir una notificación, por sí solo, no me diría que el plan le resulta útil. ## Construí más de lo que todavía puedo validar La revisión del 5 de octubre dejó constancia de que no había datos de retención disponibles en App Store Connect y de que la app no tenía analítica de producto para responder a estas preguntas. A 6 de octubre, no puedo presentar este rediseño como una mejora medida de retención. Además, el rediseño metió «Mi plan», el cambio visual y funciones Pro en un mismo commit. Aunque después vea más uso, ese paquete no permite atribuírselo a una sola decisión. Fue bastante más trabajo que arreglar el preset y retirar el banner superior. Si repitiera el proceso, empezaría por esas correcciones pequeñas, comprobaría el recorrido con alguien que no conozca la app y dejaría «Mi plan» como una hipótesis separada. Tiene un coste de desarrollo mayor y depende de que la persona quiera llevar ese seguimiento. El anuncio temprano y la discrepancia del preset se podían corregir sin apostar por un hábito nuevo. Coge una sola tarjeta de tu producto que anticipe un resultado. Anota el valor, ejecuta la acción y compáralos manteniendo la configuración del usuario. Si no coinciden, ya tienes un arreglo concreto que hacer antes de abrir el roadmap. ## Fuentes y alcance Esta historia sale de la revisión de UI del 5 de octubre y del historial de mi repositorio privado de WealthSim, en concreto el commit de la primera sesión y el del rediseño con «Mi plan». El test reproducido está en `FirstSessionUXTests.swift`; el registro mensual y la trayectoria, en `PlanStore.swift` y `PlanMath.swift`. Son cambios de código, no resultados de un experimento de retención ni una confirmación de disponibilidad de cada función en la App Store. **Lectura relacionada:** al guardar estos datos también aparecen decisiones de persistencia. En mi otra app conté [cómo SwiftData y CloudKit condicionan el modelo antes de sincronizar nada](/blog/datos-locales-cloudkit-coste/). **Caso práctico:** el [caso de WealthSim](/apps/wealthsim/#caso) reúne las decisiones y lo que salió mal en la app. --- **P.D.** ¿Has encontrado una vista previa que prometía algo distinto a lo que hacía el botón? Cuéntame el caso en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/indie-ios-app-app-store-discovery/ Lang: en # App Store Discovery: Why My Indie iOS App Has Three Users > Rydger is live on the App Store with three users. Apple's search makes new indie apps invisible until you bring your own traffic. The cold start and my move. The email from Apple landed on a Sunday. "Your submission has been approved," the review complete, "eligible for distribution." Submission ID, timestamp, the polite corporate tone of a machine that just decided your work could exist on a phone. [Rydger](/en/apps/rydger/)'s live on the App Store. Three people have installed it. One's me. One's a friend I badgered into it. The third's a stranger I've never met, who found it through some search query or link I can't trace yet, and downloaded it without me asking. That third install's the only data point that matters, and it's a sample of one. Every indie launch post wants to write "early traction is promising" or "users are responding well." Every one you've read that phrased it that way was hiding a small number too. **Three users isn't a verdict on Rydger. It's what zero marketing looks like on the App Store.** The thing nobody tells you before you ship is that the App Store, by design, makes new indie apps invisible until you either pay Apple or bring your own audience. This post is the first channel I control. ## The App Store is a black box that pretends you don't exist Here's the part I didn't get until I had a live app and a dashboard reading "3." Apple's search and discovery aren't a level playing field. They reward apps that already have downloads, ratings, retention, momentum. A new app with none of those is, for practical purposes, unfindable through organic search. You rank for your own brand name once someone looks for it specifically. You don't rank for "motorcycle maintenance" or "car service tracker" or any of the queries your future users actually type, because the algorithm has no signal to rank you on yet. Cold start. This is the documented shape of every app-store ranking algorithm, and indie iOS devs have written about it for years. The apps that appear are the ones already appearing. The ones that don't stay invisible, and invisibility reads exactly like "nobody wants this," when the truer read is "nobody can find this yet." Apple sells you one escape hatch: Apple Search Ads. You bid on the keywords you wish you ranked for organically, pay per tap, and buy your way into the ranking signal the algorithm wants. It can move the number. It's also a treadmill: the moment you stop paying, you risk sliding back into the invisibility you started in, because you were renting the signal, not earning it. ## Why I'm not paying Apple to fix this yet I could turn on a small Search Ads budget tomorrow and watch the install number tick up. I'm not going to, and the reason isn't principle. It's sequencing. Rydger has no investors and no burn rate. I've got a day job, this is a side project, and the clock I'm racing is my own patience, not a runway. That's a strategic advantage most indie apps don't have, and spending it on paid installs before I have organic signal would burn the one edge I've got. Paying for traffic to a product I haven't proven retains is buying churn. The math doesn't care that it'd feel good to watch the number move. So the order runs the other way. Build the audience on channels I control, this blog being the first, before I need the App Store's algorithm to do my distribution. Then, if the data says paid acquisition pays back, turn it on. Not before. There's a lever I'm working that sits between "do nothing" and "pay Apple," and it's the one a senior indie dev asked about two seconds into reading the draft: **ASO, App Store Optimization.** Keyword-field density, title and subtitle keyword allocation, screenshot and icon conversion tests, product-page experiments. ASO is the cheapest move that actually shifts organic ranking, and I'm treating it as the first real acquisition work, ahead of any paid tap. It doesn't cost ad spend. It costs attention to the listing. ## What Rydger is today: free manual, paid passive Quick context, because the rest only makes sense if you know what shipped. Rydger's a maintenance and cost-of-ownership app for motorcycles and cars. You photograph your dashboard, it reads the kilometre reading, it reminds you when the chain's due or the ITV expires, and it tracks what the vehicle actually costs you per kilometre. The free tier covers one vehicle, photo and manual logging, reminders, expenses, and CSV export. The wedge, the reason I started building it, is **passive mileage tracking**, and it's shipped: a Shortcuts automation on your car's Bluetooth or CarPlay connection starts a background-GPS ride, and the ledger fills itself instead of you typing every fill-up by hand. That part's Pro, paid, and labelled Beta while I confirm it survives real riders. ## The honest part: the wedge shipped, but the activation gap is real I have to criticize the thing I just shipped. The conflict of interest is obvious: this is my app, I benefit from the click, and every claim here is load-bearing because of that. The passive engine is live, and it works on my devices. But it shipped as a Beta behind a Shortcuts setup most riders won't finish without hand-holding. The user has to author a Personal Automation on their CarPlay or Bluetooth-Device trigger, point it at Rydger's Start Ride intent, and grant Always-on location. That's three steps a stranger has to complete before the wedge they paid for does anything. Apple gives apps no programmatic API to create or query a user's Personal Automations, so I can't pre-wire it; the setup friction is the ceiling iOS allows, and I live inside it. The honest risk isn't "does the product exist." It exists. The risk is the gap between "feature shipped" and "feature works for a stranger who paid for it and opened the app twice." Three users can't tell me which side of that gap I'm on. Fifty might. There's a second honest snag. The original passive mechanism, in-app BLE beacon scanning, failed under iOS suspension: iOS coalesces background BLE discovery into a single callback, so rides either ran forever or ended mid-drive. I retired that path and pivoted to the Shortcuts and App-Intents mechanism that's shipping now. That pivot is why the Beta label is earned. The throwaway spike I built first proved a paired signal could survive a commute. The mechanism that actually shipped is different, and younger. ## The move: build the channel before you need it If you're about to ship a solo app, or you already have and the dashboard reads a number you don't want to talk about, here's what I'd do, ranked cheapest first. Each row maps what you're seeing to the next move, not the reassurance. | What you're seeing | The move | | --- | --- | | Live for weeks, installs in single digits | You're invisible, which is the default state. Pick one channel you control and write something honest there this week. | | Listing converts poorly (impressions but no installs) | ASO pass. Rewrite title, subtitle, and keyword field against the queries your users actually type. Free, ships in an afternoon. | | ASO done, still invisible | One owned-channel post (blog, newsletter, subreddit). Test whether the audience you already have is the right one. | | Owned channel brings strangers, they don't retain | The product's the problem, not discovery. Fix retention before spending on ads. | | Retention's real, ready to scale | Now Apple Search Ads makes sense. You're buying signal for a product that holds onto it. | The one move I'd make first, if I had to start over: write down the single technical question that can kill the business, prototype only that, throw the code away, and decide whether to proceed before you build the product. Everything else is downstream of that answer. The channel comes second. ## Channel one: letting this blog move the number This post is channel one. The experiment's simple: I write what shipping Rydger actually looks like, the people who read this blog decide whether to click through, and the dashboard tells me within a week whether the channel works. If one reader here installs the free tier and logs a real expense, I learn something the dashboard can't tell me: that the audience I already have, small as it is, is the right audience. If nobody clicks, I learn that too, and I try the next channel instead of paying Apple to paper over a distribution problem. I'm not in a hurry. Rydger has no runway, the passive engine's shipped as Beta and I'm watching whether real riders finish the Shortcuts setup, and I'd rather have fifty riders who found it through something I wrote than five hundred who forgot they installed it. The next post in this thread is one of two things: either the Beta held up across real devices and the Pro conversion is real, or the activation gap bit me and I'm writing about what I changed. I don't know which yet. If you ride a motorcycle or drive a car, Rydger's on the App Store. The free tier works today; the passive engine is Pro if you want it. [Rydger on the App Store](https://apps.apple.com/app/apple-store/id6788900298?ct=portfolio-blog-en&mt=8). ## Sources - The "app-store ranking rewards existing momentum" pattern is the documented shape of every ranking-algorithm store; indie iOS devs have written about the cold-start discovery problem for years. I'm leaning on that shared experience rather than a single citation. - The Apple Search Ads mechanics (bidding on keywords, paying per tap) come from [Apple's ads documentation](https://searchads.apple.com); the "treadmill" framing is my own read, not Apple's claim. - The three-user count is the actual App Store Connect figure at the time of writing. **Related reading:** the data-model half of this story is already on the blog. I wrote about [what CloudKit and SwiftData cost my schema, and the boundary check worth stealing](/en/blog/cloudkit-sync-data-model-cost/). **Case study:** the [Rydger case study](/en/apps/rydger/#caso) gathers the decisions and what went wrong in the app. --- **P.S.** Shipped something solo and watching a dashboard you don't want to talk about? I want to hear what your real number is, what channel you're trying, and whether it worked. Find me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/app-store-invisible-app-indie-ios/ Lang: es # App Store: por qué mi app iOS tiene tres instalaciones > Rydger suma tres instalaciones. La búsqueda de Apple hace invisibles las apps nuevas. Mi lectura del arranque en frío, del ASO y del próximo experimento. El correo de Apple llegó un domingo. "Tu envío ha sido aprobado", con la revisión completada, "listo para distribuir". ID de envío, timestamp, el tono corporativo y educado de una máquina que acaba de decidir si tu trabajo puede existir en un teléfono. [Rydger](/apps/rydger/) ya está en el App Store. App Store Connect marca tres instalaciones. Una es la mía. Otra es la de un amigo al que mareé hasta que la instaló. La tercera no sé atribuírsela a nadie que conozca: alguien encontró Rydger en una búsqueda o enlace que todavía no sé rastrear y se la descargó sin que yo le dijera nada. Sigue siendo un único caso. Podría vestir el dato de "tracción inicial" o decir que los usuarios están respondiendo bien. No lo voy a hacer. Tres instalaciones solo me dicen una cosa: he publicado una app sin marketing. Mi hipótesis es que Rydger todavía no aparece en búsquedas genéricas, pero con este volumen no puedo separar descubrimiento, ficha y activación. Para salir de ahí tengo que trabajar la ficha o atraer a mi propia audiencia. ## Tres instalaciones no explican dónde se rompe el recorrido Eso no lo entendí del todo hasta tener una app publicada y un dashboard que dice "3". El número es real, pero no explica qué ha pasado entre una persona que busca algo y una persona que instala. En el buscador y en el sistema de descubrimiento de Apple, no todas las apps juegan con las mismas cartas. Las que ya acumulan descargas, valoraciones y uso tienen señales que una app recién publicada todavía no tiene. Mi sospecha es que una app nueva tiene menos visibilidad en búsquedas orgánicas, pero no voy a presentar la fórmula del ranking como un hecho que pueda demostrar. Solo sé que Rydger no aparece, de momento, cuando pienso en búsquedas como "mantenimiento de moto" o "registro del mantenimiento del coche". Arranque en frío. Las apps que ya aparecen suelen tener algo de recorrido; las demás necesitan generar esa primera señal. La falta de visibilidad se puede interpretar como "nadie quiere esto", aunque con tres instalaciones todavía no sé si el problema es la demanda, la ficha o simplemente que nadie ha encontrado Rydger. Apple te ofrece una opción de pago: Apple Search Ads. Pujas por palabras clave y pagas cada vez que alguien toca el anuncio para aparecer como resultado patrocinado. Eso puede aumentar las instalaciones mientras pagas, pero no lo voy a presentar como una forma de mejorar el posicionamiento orgánico. Si dejo de pagar, dejo de comprar esa visibilidad. La metáfora de la cinta de correr es mía, no una promesa de Apple. ## Por qué no le estoy pagando a Apple todavía Podría poner mañana un presupuesto pequeño en Search Ads y ver cómo aumentan las instalaciones. No lo voy a hacer todavía: primero quiero saber si quienes llegan siguen usando el producto. Rydger no tiene inversores ni burn rate. Tengo mi trabajo principal, esto es un proyecto paralelo y no tengo una fecha límite para recuperar el gasto. Puedo esperar a tener una señal orgánica antes de comprar tráfico. Pagar por llevar visitas a un producto que todavía no he demostrado que retiene es pagar por usuarios que se irán. A las cifras les da igual que te haga ilusión ver cómo sube el número. Primero construiré audiencia en canales que controlo, empezando por este blog. Después, si los datos dicen que comprar tráfico sale rentable, lo probaré. No necesito convertir una hipótesis de distribución en un coste fijo. Estoy probando una opción intermedia entre "no hacer nada" y "pagarle a Apple": **ASO, App Store Optimization**. Voy a revisar las palabras clave del título, el subtítulo y el campo de keywords, además de las capturas y la ficha. No espero que un cambio me haga aparecer más arriba. Quiero medir si mejora la relación entre impresiones, visitas a la ficha e instalaciones. No cuesta dinero en publicidad. Cuesta dedicarle atención a la ficha. Mi hoja de seguimiento tendrá una fila por cambio: búsqueda, campo modificado, fecha, impresiones, visitas a la ficha e instalaciones. Una modificación cada siete días; nada de cambiarlo todo a la vez. ## Lo que está publicado y lo que todavía falla Rydger es una app para llevar el mantenimiento y saber cuánto cuesta tener una moto o un coche. Puedes registrar gastos, servicios y lecturas del cuentakilómetros, y recibir avisos de mantenimiento. El plan gratuito permite llevar un vehículo, registrar datos con fotos o a mano y exportar el historial a CSV. La función que me llevó a construirla es el **seguimiento automático del kilometraje**. Ya está publicada como función Pro de pago y aparece marcada como Beta: una automatización de Shortcuts usa el Bluetooth o CarPlay del vehículo para iniciar y detener un trayecto con GPS en segundo plano. El seguimiento registra la distancia; no mete por arte de magia cada repostaje o gasto en tu cuenta. ## La configuración de Shortcuts es el cuello de botella El motor automático es la parte más frágil de lo que he publicado. Lo estoy validando en mis dispositivos y no tengo una fuente independiente para estas conclusiones. Para usarlo, el usuario tiene que emparejar el vehículo y crear dos automatizaciones: una para cuando se conecte por Bluetooth o CarPlay y otra para cuando se desconecte. Tiene que activar la ejecución inmediata de ambas y elegir el vehículo. Para que el trayecto siga con el móvil bloqueado también necesita el permiso de ubicación con la opción «Siempre». La guía de configuración tiene varios pasos antes de que la función Pro haga algo útil. Apple no da a las apps una API para crear ni consultar las automatizaciones personales del usuario. Por eso no puedo preconfigurar ese recorrido. La fricción de la configuración es un límite que impone iOS, y el producto tiene que convivir con ella. El riesgo está en la diferencia entre una función publicada y una función que alguien consigue configurar y usar. Con tres instalaciones no puedo saber dónde está el problema: en el descubrimiento, en la ficha, en el precio o en la activación. App Store Connect tampoco me dirá por qué alguien abandona. Para eso necesito hablar con usuarios y observar qué parte de la configuración no completan. El mecanismo original tampoco salió bien. Intenté escanear un beacon BLE desde la app, pero falló cuando iOS la suspendía: el sistema acumulaba los avisos de descubrimiento BLE en segundo plano y los entregaba en una sola llamada, por lo que los trayectos podían quedarse abiertos o terminar a mitad del trayecto. Retiré ese camino y lo sustituí por Shortcuts y App Intents. Por eso la etiqueta Beta está justificada. El prototipo inicial probó una ruta distinta de la que está publicada ahora. ## Primero necesito saber dónde se rompe el recorrido Si vas a publicar una app en solitario, o ya la has publicado y el dashboard muestra un número del que no quieres hablar, este es el orden que seguiría. Cada fila te dice qué hacer después. | Lo que ves | El siguiente paso | | --- | --- | | Lleva semanas publicada y tiene menos de diez instalaciones | Abre App Store Connect y separa impresiones, visitas a la ficha e instalaciones. Todavía no cambies cinco cosas a la vez. | | Hay impresiones, pero pocas visitas a la ficha | Revisa ASO. Cambia un solo campo de texto a partir de las búsquedas que quieres probar y mide durante siete días. | | Hay visitas a la ficha, pero no instalaciones | Revisa el título, las capturas, el icono y la promesa de la primera captura. El problema puede ser de conversión, no de alcance. | | El canal propio atrae a desconocidos, pero no se quedan | Pregunta dónde se quedaron y revisa el primer recorrido. No atribuyas la caída al producto sin separar audiencia, permisos y configuración. | | La ficha convierte y la activación funciona | Solo entonces prueba Search Ads con un presupuesto que puedas perder y compara el coste con la retención que ya tienes. | Lo primero que haría hoy sería abrir App Store Connect durante quince minutos, anotar las impresiones, las visitas a la ficha y las instalaciones, y cambiar un solo campo de ASO. Una semana después decidiría si repetir, probar otro campo o escribir en otro canal. Esa es una acción que funciona aunque la app no sea Rydger. ## Este blog es la primera prueba Este artículo es la primera prueba de si alguien llega a Rydger desde aquí. Durante siete días miraré las impresiones de la ficha, las visitas y las instalaciones atribuidas al enlace. App Store Connect puede contar ese recorrido, no explicar por qué alguien abandona la configuración ni si volverá dentro de un mes. Si llegan instalaciones pero nadie termina de configurar Shortcuts, arreglaré ese primer recorrido. Si no llega nadie, probaré otra fuente. Si llegan visitas pero no instalan, cambiaré el título o las capturas. Mediré una cosa cada vez. No tengo prisa. Prefiero cincuenta moteros que la encuentren gracias a algo que he escrito yo que quinientos que se olviden de que la tenían instalada. Durante los próximos siete días miraré esos tres números y no tocaré otro campo hasta tener una lectura. Si quieres ver el producto del que hablo, Rydger está en el App Store. La versión gratuita se puede usar ya; el seguimiento automático es Pro. [Rydger en el App Store](https://apps.apple.com/app/apple-store/id6788900298?ct=portfolio-blog-es&mt=8). ## Fuentes - El número de tres instalaciones es la cifra que veo en App Store Connect al publicar este artículo. - La mecánica de Apple Search Ads, incluida la puja por palabras clave y el pago por interacción, sale de [la documentación de Apple Ads](https://searchads.apple.com). La separación entre visibilidad patrocinada y posicionamiento orgánico es la distinción que aplico en este artículo. **Lectura relacionada:** la mitad de la historia del modelo de datos ya está en el blog. Escribí sobre [qué le costó a mi esquema CloudKit con SwiftData, y la validación que merece la pena copiar](/blog/datos-locales-cloudkit-coste/). **Caso práctico:** el [caso de Rydger](/apps/rydger/#caso) reúne las decisiones y lo que salió mal en la app. --- **P.D.** ¿Has publicado algo tú solo y estás consultando un panel cuyos datos no quieres compartir? Quiero leer cuál es tu número real, qué canal estás probando y si te ha funcionado. Me tienes en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/cloudkit-sync-data-model-cost/ Lang: en # SwiftData + CloudKit: 5 Model Rules Before You Turn Sync On > SwiftData's CloudKit mirroring needs defaults or optionals, no @Attribute(.unique), optional relationships with inverses, no .deny. What error 134060 means. The first SwiftData model I wrote for Rydger has a header comment that still reads: *Fields are CloudKit-ready: every attribute has a default value or is optional, so [a later ticket] can switch on CloudKit sync with no schema change.* [Rydger](/en/apps/rydger/) is my first native iOS app and my first serious Swift codebase. I had worked with React Native at a company, so mobile state and lifecycle problems were familiar. Letting SwiftData mirror a local store through CloudKit was not. I wrote that comment before the app could sync anything. The container `iCloud.com.rydger.Rydger` existed, but `ModelConfiguration` did not use it yet. The comment forced me to inspect the schema early; it did not prove that sync worked. ## CloudKit changes the model before it syncs a byte For SwiftData's automatic CloudKit mirroring, check these five constraints before enabling `cloudKitDatabase: .automatic`: 1. **Every attribute needs a default value or must be optional.** Use `var make: String = ""` or `String?`, not a required property with no default. 2. **`@Attribute(.unique)` is unsupported.** This is a limitation of SwiftData's CloudKit mirroring, not a claim that CloudKit records have no identity. 3. **Relationships must be optional and have an inverse.** SwiftData can infer some inverses; declare `@Relationship(inverse:)` when it cannot do so reliably. 4. **The `.deny` delete rule is unsupported.** Use a supported rule and enforce any extra restriction in your own code. 5. **A production CloudKit schema is additive.** Once deployed, existing record types and fields cannot simply be removed or have their types changed. Treat those edits as migration decisions. An incompatible model still compiles. The useful failure arrives when SwiftData loads the CloudKit-backed persistent store, often as `NSCocoaErrorDomain` error `134060`. If the CloudKit configuration only appears near release, that feedback arrives far too late. Here is the stripped-down pattern: ```swift @Model final class Vehicle { var make: String = "" @Relationship(deleteRule: .cascade, inverse: \MaintenanceItem.vehicle) var maintenanceItems: [MaintenanceItem]? = [] init(make: String = "") { self.make = make } } @Model final class MaintenanceItem { var title: String = "" var vehicle: Vehicle? init(title: String = "", vehicle: Vehicle? = nil) { self.title = title self.vehicle = vehicle } } struct VehicleInput { let make: String } enum VehicleMappingError: Error { case missingMake } extension Vehicle { func domainInput() throws -> VehicleInput { let value = make.trimmingCharacters(in: .whitespacesAndNewlines) guard !value.isEmpty else { throw VehicleMappingError.missingMake } return VehicleInput(make: value) } } ``` The exact relationship annotation depends on what SwiftData can infer from both sides. Check for optional relationships, a valid inverse, and no `.deny` hidden in the model. ## Persistence defaults are not domain defaults `make = ""` satisfies the persistence schema. It does not make an empty manufacturer valid in Rydger. If that distinction stays buried in a SwiftUI view, every new screen gets another chance to interpret it differently. Rydger keeps those decisions in a local package, `RydgerCore`, which imports neither SwiftData nor SwiftUI. Code at the app boundary reads a `Vehicle`, rejects or normalises persistence defaults, and passes typed input into pure functions. The package can then run under `swift test` without booting a simulator. **Let the persistence model satisfy CloudKit, then enforce the stricter rule once when data enters the domain.** The conversion fails explicitly instead of letting `""` travel through the app pretending to be a manufacturer. There is a cost: two representations, mapping code, and the risk that somebody bypasses the conversion. I can only claim the stricter type guarantee where the app forces callers through that boundary. I also store evolving enum values as raw strings and map them explicitly. The fallback belongs to Rydger's conversion code; CloudKit does not provide it for free. An unknown value should take a deliberate path such as `.unknown` or a validation error, not silently become whatever case was convenient when the model was written. ## The honest limit: schema compatibility is not sync correctness Removing `.unique` leaves a real hole. SwiftData maintains the identity of each persistent object, but it does not stop two offline devices from creating two records for the same logical maintenance event. SwiftData's mirroring will not invent that business rule. Rydger does not have a universal deduplication solution, and I am not going to pretend otherwise. A deterministic fingerprint can help the app detect equivalent records after fetching them, but automatic mirroring cannot enforce that fingerprint as a global unique constraint. Stronger enforcement needs explicit app-side reconciliation or a different architecture using direct CloudKit or a backend. The same applies to observation. `@Query` can keep a view aligned with changes in the local store; it does not explain CloudKit errors, settle business-level duplicates, handle iCloud account changes, or tell the user why another device's changes have not arrived yet. Before your SwiftData model settles, run the app with the real CloudKit-backed `ModelContainer`. That catches schema incompatibilities such as error `134060`; it does not prove sync works. Then create, edit, and delete a record on two devices using the same iCloud account. They are separate checks, and the first one is cheap enough to run today. ## Sources - [Syncing model data across a person's devices](https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices), Apple Developer Documentation - [Designing and Creating a CloudKit Database](https://developer.apple.com/documentation/cloudkit/designing-and-creating-a-cloudkit-database), Apple Developer Documentation **Related reading:** [Harness Engineering: The Model Isn't Your Bottleneck](/en/blog/harness-engineering-why-your-agent-fails/), another case for moving guarantees to a boundary you can verify. **Case study:** the [Rydger case study](/en/apps/rydger/#caso) gathers the decisions and what went wrong in the app. --- **P.S.** This is my first native iOS build. If you have hit a CloudKit problem I have not seen yet, [tell me on LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/datos-locales-cloudkit-coste/ Lang: es # SwiftData y CloudKit: cómo condicionan tu modelo de datos > SwiftData con CloudKit cambia el modelo antes del sync: defaults, relaciones opcionales, sin @Attribute(.unique) y una validación que puedes copiar. El primer modelo de SwiftData que escribí para Rydger todavía lleva este comentario en la cabecera: *Fields are CloudKit-ready: every attribute has a default value or is optional, so [a later ticket] can switch on CloudKit sync with no schema change.* [Rydger](/apps/rydger/) es mi primera app nativa para iOS y mi primer proyecto serio con Swift. Había trabajado con React Native en una empresa, así que los problemas de estado y ciclo de vida en móvil no me pillaban de nuevas. Dejar que SwiftData replique el almacenamiento local con CloudKit sí. Escribí ese comentario antes de que la app sincronizase nada. El container `iCloud.com.rydger.Rydger` ya existía, pero `ModelConfiguration` aún no lo usaba. El comentario me obligó a revisar el esquema pronto; no demostraba que el sync funcionase. ## CloudKit cambia el modelo antes de sincronizar nada Si vas a usar la integración automática de SwiftData con CloudKit, revisa estas cinco restricciones antes de activar `cloudKitDatabase: .automatic`: 1. **Cada atributo necesita un valor por defecto o tiene que ser opcional.** Usa `var make: String = ""` o `String?`, no una propiedad obligatoria sin default. 2. **`@Attribute(.unique)` no está soportado.** Es una limitación de la integración de SwiftData con CloudKit, no significa que los registros de CloudKit no tengan identidad. 3. **Las relaciones tienen que ser opcionales y tener una relación inversa.** SwiftData puede inferir algunas; declara `@Relationship(inverse:)` cuando no pueda hacerlo bien. 4. **La regla de borrado `.deny` no está soportada.** Usa una regla compatible y aplica cualquier restricción extra en tu código. 5. **El esquema de CloudKit en producción es aditivo.** Una vez publicado, no puedes borrar sin más los tipos y campos existentes ni cambiar sus tipos. Trata esos cambios como decisiones de migración. Un modelo incompatible compila. El fallo útil aparece al cargar el almacenamiento persistente conectado a CloudKit, muchas veces como el error `134060` de `NSCocoaErrorDomain`. Si añades la configuración de CloudKit justo antes de publicar, ese feedback llega demasiado tarde. Este es el patrón reducido a lo importante: ```swift @Model final class Vehicle { var make: String = "" @Relationship(deleteRule: .cascade, inverse: \MaintenanceItem.vehicle) var maintenanceItems: [MaintenanceItem]? = [] init(make: String = "") { self.make = make } } @Model final class MaintenanceItem { var title: String = "" var vehicle: Vehicle? init(title: String = "", vehicle: Vehicle? = nil) { self.title = title self.vehicle = vehicle } } struct VehicleInput { let make: String } enum VehicleMappingError: Error { case missingMake } extension Vehicle { func domainInput() throws -> VehicleInput { let value = make.trimmingCharacters(in: .whitespacesAndNewlines) guard !value.isEmpty else { throw VehicleMappingError.missingMake } return VehicleInput(make: value) } } ``` La anotación exacta depende de lo que SwiftData pueda inferir al mirar ambos lados. Comprueba que las relaciones sean opcionales, que tengan una relación inversa válida y que no haya ningún `.deny` escondido en el modelo. ## El default de persistencia no es el default del negocio `make = ""` cumple el esquema de persistencia. Eso no hace que un nombre de fabricante vacío sea válido en Rydger. Si esa diferencia se queda repartida entre vistas de SwiftUI, cada pantalla nueva puede interpretarla de una forma distinta. Rydger guarda esas decisiones en un paquete local, `RydgerCore`, que no importa SwiftData ni SwiftUI. La app convierte cada `Vehicle` en un input del dominio y rechaza o normaliza los defaults durante esa conversión. Así puedo ejecutar las funciones puras con `swift test` sin arrancar el simulador. **Deja que el modelo de persistencia cumpla con CloudKit y aplica la regla estricta una sola vez al convertirlo al tipo del dominio.** La conversión falla de forma explícita en vez de dejar que `""` recorra media app fingiendo ser un fabricante. También tiene un coste: mantienes dos representaciones, escribes código de mapeo y alguien puede saltarse la conversión. Solo puedo hablar de una garantía de tipos más estricta en las rutas donde la app obliga a pasar por ese punto. También guardo como `String` los enums que pueden crecer y hago el mapeo de forma explícita. Ese fallback pertenece al código de Rydger; CloudKit no lo pone gratis. Si llega un valor desconocido, lo convierto en `.unknown` o devuelvo un error de validación. No debería acabar sin avisar en el caso que venía bien cuando escribiste el modelo. ## La parte honesta: cumplir el schema no resuelve el sync Quitar `.unique` deja un agujero real. SwiftData mantiene la identidad de cada objeto persistente, pero no impide que dos dispositivos sin conexión creen dos registros para el mismo mantenimiento. La integración con CloudKit no se va a inventar esa regla de negocio. Rydger no tiene una solución universal para deduplicar, y no voy a fingir lo contrario. Una huella determinista puede ayudar a detectar registros equivalentes después de leerlos, pero la integración automática no puede imponer esa huella como restricción única global. Para garantizarlo necesitas reconciliación explícita en la app u otra arquitectura con CloudKit directo o un backend. Con la observación pasa algo parecido. `@Query` puede mantener una vista al día con los cambios del almacenamiento local; no explica errores de CloudKit, no resuelve duplicados de negocio, no gestiona cambios de cuenta de iCloud ni cuenta al usuario por qué aún no han llegado los cambios del otro dispositivo. Antes de que el modelo de SwiftData se estabilice, arranca la app con el `ModelContainer` real conectado a CloudKit. Eso detecta incompatibilidades del esquema como el error `134060`; no demuestra que el sync funcione. Después crea, edita y borra un registro en dos dispositivos con la misma cuenta de iCloud. Son dos comprobaciones distintas, y la primera es lo bastante barata para hacerla hoy. ## Fuentes - [Sincronizar los datos de un modelo entre los dispositivos de una persona](https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices), documentación de Apple - [Diseñar y crear una base de datos de CloudKit](https://developer.apple.com/documentation/cloudkit/designing-and-creating-a-cloudkit-database), documentación de Apple **Lectura relacionada:** [Qué es harness engineering y por qué falla tu agente](/blog/harness-engineering-por-que-falla-tu-agente/), otro caso para aplicar las garantías en un punto que puedas comprobar. **Caso práctico:** el [caso de Rydger](/apps/rydger/#caso) reúne las decisiones y lo que salió mal en la app. --- **P.D.** Esta es mi primera app nativa para iOS. Si te has encontrado con un problema de CloudKit que aún no haya visto, [dímelo en LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/astro-7-painless-migration/ Lang: en # Astro 7 vs 6: What's New and How to Upgrade (Vite 8, Rust) > I expected another v6-style fight and got a pnpm up and a coffee. Vite 8, a Rust compiler, queued rendering: what changed from Astro 6 and where it bites. **Short answer:** Astro 7 turns on Vite 8 with Rolldown, a new Rust `.astro` compiler and queued rendering, all by default. If your v6 project is clean (Content Layer, `id` not `slug`, Zod 4), the upgrade is mostly a version bump. Two things can bite: the stricter compiler stops silently fixing malformed HTML, and Markdown now runs on Sätteri, so if you use remark or rehype plugins you have to install `@astrojs/markdown-remark` yourself. Before Astro 7 I upgraded this site to Astro 6 and [walked you through the fight](/en/blog/astro-6-migration-guide/): the `ContentSchemaContainsSlugError` that blamed the wrong file, the Zod default that compiled while lying, a whole afternoon gone. So when Astro 7 landed (on 22 June 2026), I braced for the same. Strong coffee, changelog open, the afternoon blocked off. Didn't need it. `pnpm up astro`, green build, 217 tests green, and I drank the coffee actually celebrating. The difference between v6 and v7 is the difference between paying off old debt and getting a new engine for free. ## What does Astro 7 actually ship? Three headliners, and all three come on by default: - **Vite 8, with Rolldown underneath:** the Rust bundler that replaces esbuild and Rollup. Astro claims builds 15% to 61% faster, and some sites more than twice as fast. In their own benchmarks, `astro.build` went from 62 seconds to 24. - **A Rust compiler:** they rewrote the `.astro` compiler from scratch, Go to Rust. - **Queued rendering:** what was an experimental flag in v6 is now stable and default. It swaps recursive rendering for a queue and they put it around 2.4× faster. Underneath there's more: Markdown moves to a Rust-powered processor (Sätteri), route caching stabilizes behind a platform-agnostic API (`Astro.cache`), a new `src/fetch.ts` entrypoint lets you own the whole request pipeline, and a couple of agent-friendly bits like `astro dev --background` with agent detection and JSON logging. | | Astro 6 | Astro 7 | | --- | --- | --- | | Bundler | Vite with esbuild and Rollup | Vite 8 with Rolldown (Rust) | | `.astro` compiler | Go | Rust, rewritten from scratch | | Rendering | Recursive; the queue was an experimental flag | Queued, stable and default | | Markdown | remark and rehype built in | Sätteri (Rust); remark or rehype plugins need `@astrojs/markdown-remark` | | Malformed HTML | The compiler silently fixed it | No longer fixed | | Line break between inline elements | Renders as a space | JSX rules: no space | | Route caching | Experimental | Stable, via `Astro.cache` | ## How do you upgrade from Astro 6 to 7? If your v6 is clean, it's three commands. These are mine, with the Vercel adapter: ```bash pnpm up --latest astro @astrojs/vercel # for me, 6.4.6 → 7.0.3 and the adapter from 10 to 11 pnpm add @astrojs/markdown-remark # only if you use remark or rehype plugins pnpm astro check && pnpm build && pnpm test ``` Before you run them, check two things: no v6 experimental flags left in `astro.config.mjs`, and templates that close every tag. The first is in [the official upgrade guide](https://docs.astro.build/en/guides/upgrade-to/v7/); the second is the new compiler's sharp edge, covered below. ## Why it didn't hurt for me My entire diff was two things: bump versions and fix two tests. No experimental flag to remove, no `src/fetch.ts` to write, no `astro:transitions` internals to chase, no `@astrojs/db`. Astro 6.4.6 to 7.0.3, and while I was in there `@astrojs/vercel` 10 to 11 and TypeScript 5.9 to 6.0. The only change in my own code was updating assertions in two unit-test files to expect trailing-slash URLs. 217 tests green, on with my day. The reason is the v6 lesson in reverse. v6 already made me pay every debt: the Content Layer, `id` instead of `slug`, the Zod 4 defaults. v7 takes away no crutches, it just adds speed. If your v6 is clean, v7 is free. ## The honest part: where it can bite It's not all a breeze, and the new compiler has an edge to it. The Rust one is stricter than the old Go one. It no longer auto-corrects your HTML: it won't reorder tags or close the ones you left open, and whitespace now follows JSX rules, so a newline between two inline elements no longer renders as a space. Nothing broke for me because my templates were already well-formed. But if you're carrying sloppy HTML that survived because Astro quietly patched it behind your back, that's where v7 will start throwing errors v6 swallowed without a word. It did bite a week later. Patch releases 7.0.4 to 7.0.6 broke static prerendering for my `[slug].md.ts` endpoints with `trailingSlash: "always"` ("Missing parameter: slug"), so I pinned 7.0.3, renamed the endpoints to `[slug].ts`, and installed `@astrojs/markdown-remark` explicitly for my remark plugins. Not a fight, but not free either. And an asterisk on the numbers: that "15-61% faster" is their benchmark, not mine. I didn't time the build before the upgrade, so I can't give you a delta. What I can sign: today, on 7.3.3 and an M2 Max, `astro build` does this site's 43 pages in about 5 seconds on a warm run. ## The takeaway, next to v6 The migrations that hurt are the ones that pay off old debt, not the ones that ship new engines. Do the boring work on time (the v5 work, the v6 work) and the jump to v7 is what every upgrade promises and almost none deliver: a `pnpm up` and a coffee you actually get to enjoy. **Related reading:** if you're coming from further back (the [Astro 6 intro](/en/blog/introduction-astro-5/) covers what the framework is and why it ships so little JS), the upgrade that genuinely costs you is [Astro 5 to 6](/en/blog/astro-6-migration-guide/), with the `slug` to `id` switch and the Zod 4 defaults that explain why v7 felt so smooth. Jumping straight from v5 and your schema fields vanish? Check [where your `content.config.ts` lives](/en/blog/astro-6-migration-guide/#missing-schema-fields-check-where-contentconfigts-lives) first. **Related reading:** for the general Astro 6 overview that this upgrade starts from, see the [Astro 6 introduction](/en/blog/introduction-astro-5/). ## Sources - Astro, [Astro 7.0 announcement](https://astro.build/blog/astro-7/) (Vite 8, Rust compiler, queued rendering, build numbers). - [Astro docs: Upgrade to v7](https://docs.astro.build/en/guides/upgrade-to/v7/). --- **P.S.** Already jumped to v7? Did the Rust compiler catch some sloppy HTML that had been sneaking by for years? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/harness-engineering-why-your-agent-fails/ Lang: en # What Is Harness Engineering? Why Your AI Agent Fails > Your AI agent nails the demo and collapses in production. Not the model: it's the scaffolding that watches it, corrects it, and stops it before it lies. **Short answer:** harness engineering is everything you build around the model to keep an agent honest: how you split the work, where state lives, what checks the critical steps, and what catches the failure before production does. When an agent breaks in prod, look for the missing check before you swap models. The cheapest fix: never let the agent grade its own work. Put a deterministic gate in front of "done", like `astro check && astro build` on this blog, so a wrong result fails loudly instead of shipping green. I renamed a post on this very blog. Mechanical work, the kind you hand to an agent without thinking: change the slug, leave redirects so the old URLs don't die, check the build passes, deploy. Green everywhere. I called it done. Weeks later, the post that brought me the most traffic had vanished from Google. Not dropped in ranking: gone from the index. The cause was almost funny. The site runs with `trailingSlash: "always"`, so Google had the URL stored with a trailing slash, and the redirects were written without one. Not a single one matched. Every request fell through to the 404, and the build doesn't care what Google thinks, so it stayed green the whole time. Nothing warned me. The system kept going, happily serving a redirect that had been broken since the first commit, and I found out from the traffic drop, which is the worst way to find out. That, exactly that, is what kills AI agents in production: a plan that looks right, an execution that drifts halfway through, and no mechanism that notices. The model wasn't at fault. Nothing was watching. ## Agent = Model + Harness The line that rearranged my head comes from [the LangChain folks](https://www.langchain.com/blog/the-anatomy-of-an-agent-harness), and it's short enough to sound dumb: an agent is the model plus the harness. Almost everything in your codebase that makes the agent actually work in production, anything that isn't the model API call itself, is harness. In [the loops post](/en/blog/stop-prompting-write-loops/) I used "harness" in passing, as the equipment: the tools, [the skills](/en/blog/agent-skills-coding-workflow/), the MCPs you hand an agent. I sold it short. The harness isn't just what the agent _can_ do. It's the scaffolding that watches what it does, catches its failures, enforces its limits, and drags it back on course when it drifts. The name is from real harnesses: the reins, the safety tether, the gear you strap onto something that moves. The analogy that stuck: sending a junior into an important client meeting. The prompt is the agenda ("say hello, pitch the product, ask about requirements"). The context is the dossier ("here's the client history and the pricing sheet"). The harness is everything else: the checklist they carry, the mid-meeting check-in you force them to do, the recorded transcript, and the brutal standard you'll hold their report to. No matter how good the briefing, it doesn't make up for nobody checking whether what they did was actually right. ## Three stages, and why most of us are stuck on the second This matures in three jumps, and most projects I see live on the second one wondering why third-stage problems keep biting them. **Prompt engineering** is where you start. You learn the model is exquisitely sensitive to how you talk to it, and a good role with a couple of examples transforms the output. Real and useful. But I hit the ceiling fast: no matter how well I word the instruction, I can't give it knowledge it lacks, and I can't stop it inventing a fact when reality disappoints it. **Context engineering** is the next jump, and it's the one people mistake for "having a RAG." You give the model what it needs to see right when it decides: dynamic state, summarized tool outputs, history truncated on purpose. My agent got far smarter when it stopped guessing. But context doesn't fix execution drift. The redirect mess is exactly that: all the information in the world, a correct plan, and it still wandered off with everything green. **Harness engineering** is the third, and it's the humbling one if you thought a better model was the answer. The first two make the model _think_ better. The third makes it _act_ reliably. Change how tasks get decomposed, how state is kept, and how critical steps get validated, and the same model with the same prompts goes from stuck to something you can genuinely leave running. The heart of it is one move I'll keep coming back to: split the part that generates from the part that judges, and never let them be the same call. ## The layers that actually changed something Some people draw six perfect layers in a nice diagram. I'll spare you the diagram and give you the three that already live in my code, with the commit that put them there. **Bad input should break the build, not render broken.** On this blog, until recently, each post's images were resolved through a slug-keyed registry. Publish a post, forget to register its slug, and the build stayed green while the page rendered an `upload/undefined`: a broken image, in production, with no warning. It actually happened to me with the Fable posts. The fix wasn't remembering better, it was moving the URL into frontmatter and dropping a Zod `.refine()` into `src/content.config.ts` that says it has to be a valid Cloudinary URL or `astro check` fails. Now a bad image doesn't reach production: it blows up the build in my face, which is where I want it to blow up. In the wealth calculator I keep on the side, same thing with money: a Zod schema bounds every input (`years` between 1 and 50, the rate between -10 and 30) before the simulation touches a single number. The boundary where outside data comes in is where you scream. **The order of steps isn't the model's call.** Models fail less from not knowing how to do a thing than from not knowing how to string things together. They jump steps, skip validation, ship the output before they have everything. That's why this blog's `build` isn't plain `astro build`, it's `astro check && astro build`: the check goes first, and if the schema rejects anything, there's no build. In the calculator the rail is CI: lint, then type-check, then unit tests, then end-to-end, in that order, each one blocking the next. Those rails aren't decoration. They move the project management out of the part that improvises and into the part that doesn't. **An agent that grades its own work lies.** This is the layer where primitive agents break. They produce output, declare themselves satisfied, and have no way to know whether it's correct; they've got a textbook optimistic bias and they'll rate broken code as working. The fix is an evaluator the agent can't sweet-talk. In the calculator I keep a test file with a comment in all caps that I wrote precisely for future-me and for any agent: _"DO NOT MODIFY these tests to make them pass"_, because they're designed to fail if anyone reintroduces a mathematically wrong formula. One checks that the real return is computed with the Fisher equation and not the naive inflation subtraction, and it refuses to pass if the two numbers come out equal. It's a gatekeeper that won't be talked into it. "I finished generating the text" and "I ran it, the Fisher test failed, I fixed it" are two different sentences, and the harness is what forces the second one. ## The honest part: "harness" is also the buzzword for hiding a weak model Three snags I ran into myself, in case they save you the bruise. First, almost none of this is new. That financial-integrity test and those Zod schemas are plain old software engineering: validate inputs, separate generation from QA, don't trust a process's output without checking it. We've done it for decades with services that have no LLM inside. The unpredictable component being a model now doesn't make the pattern a new discipline. If you already know how to build systems that fail gracefully, you already know harness engineering; the unpredictable junior just speaks English now. And yet three things genuinely shift when the unpredictable part is a model and not a service, and they're what make this worth a name at all. One: the error message stops being a dead end and becomes an interface. My `.refine("has to be a Cloudinary URL")` isn't only a guard anymore; the agent reads that string and corrects itself on the next pass. Write your validation messages for the model, not just for the log. Two: the cost flips. In normal code writing is expensive and checking is cheap; with a model, generating is nearly free and verifying is the whole bottleneck, which is exactly why all your effort migrates into the harness. Three: the enemy isn't bad input, it's non-determinism. The same prompt gives a different answer next run, so the demo that worked was one lucky sample. The honest checks aren't "reject bad data", they're "run it twice and diff", "make it idempotent", "feed the failure back and retry". Second, the scaffolding has a dark side. The more harness you bolt on, the more you're building a cage that papers over a model that isn't good enough for the task. There's a point where "my agent nails 95%" really means "I've constrained the problem so hard it's not an agent anymore, it's a workflow with an LLM filling blanks." Sometimes that's exactly what you want. But calling it autonomy is kidding yourself. And the 95% number going around I take with tongs: it depends entirely on which tasks you put in the denominator, and almost nobody publishes that denominator. Third, and this ties straight to [Fable's pricing](/en/blog/claude-fable-5-review/): every validation layer you add is another billed model call. A harness that fires an independent evaluator on every step doubles or triples your cost per task. At $10 per million input tokens, the scaffolding that saves you from slop also drains your wallet. The token ceiling isn't a harness extra. It's part of the harness. ## What does "autonomous" actually mean? The trick behind agents that supposedly ship whole products with no human review for hours isn't a smarter model. It's separating two roles that refuse to trust each other: the one that generates and the one that evaluates. And the key is that the evaluator validates against the world, not against the generator's version of the world. There's a trap the moment you build that evaluator: if the evaluator is itself an LLM, it carries the same optimistic bias you're trying to escape: you've just hired a second junior to grade the first one's homework. The way out is a pecking order. Deterministic checks (types, schemas, a test with the expected number hardcoded) are free and can't be sweet-talked, so push every check you possibly can down into that layer. Save the expensive, fallible LLM-judge for the things that genuinely can't be pinned to an assertion. The cheapest evaluator that can't lie beats the smartest one that can. I've got a silly but perfect example of this in the calculator. A unit test in jsdom swears the chart is rendered: the node exists, the props are right, all good. The real browser sees that same chart is 0 pixels wide. That's why the test that matters is the end-to-end one that opens actual Chromium and WebKit, locates the `boundingBox` of the Recharts SVG, and refuses to pass if the width or height is zero. The generator would tell you the chart is there. The evaluator actually looks. That's the whole line between a demo and a product: "done" stops meaning "I generated the component" and starts meaning "I opened it in a browser and watched it paint." ## Which layer are you missing? If you want to skip the philosophy: find your agent's symptom on the left, build the thing on the right. | What your agent keeps doing | The layer that isn't there | | --- | --- | | Invents a fact, or passes garbage cheerfully downstream | **Boundary**: nothing rejected the bad value where it came in | | Skips a step, or ships before it has everything | **Ordering**: your checks run after the work instead of blocking it | | Swears it's done while it's visibly broken | **Evaluator**: it's grading its own homework, against its own word | | Worked yesterday, broke today, identical prompt | none of the above. That's **non-determinism**, and the fix is run-twice-and-diff, not another guard | Three of those four are a layer you haven't built. The fourth is the reminder that a harness bounds the chaos, it doesn't delete it. ## Where you start, if you only do one thing You don't build all three layers on a Friday night. You pick the one that's bleeding and you bound it. Here's the order I'd go in, cheapest first, because the cheap one also catches the most. **Start at the boundary.** Find the single place where outside data enters your agent: the form field, the API payload, the frontmatter, the tool output you parse before you trust it. Put a schema there that throws instead of coasting. In Zod that's a few lines: ```ts // two real boundaries from my repos, same move: const Input = z.object({ years: z.number().min(1).max(50), // the calculator imageUrl: z.string().refine( // the blog (u) => u.startsWith("https://res.cloudinary.com/"), "has to be a Cloudinary URL", ), }) ``` That `.refine()` is the whole lesson. A bad value dies right here, loud, instead of three steps downstream as an `upload/undefined` nobody notices until the traffic drops. Half my production fires would have been a red build with one of these. Fifteen minutes, today. **Then move the check before the build, not after.** Whatever your generate step is, take the validation you already have and put it in front, blocking. On this blog it's literally one `&&`: `astro check && astro build`. If you've got CI, order the rails so each blocks the next (types, then unit, then end-to-end) and make the slow honest one, the browser or the integration test, impossible to skip. You're not writing new checks here. You're moving the ones you have to a place the agent can't sail past. **Then write one test the agent can't sweet-talk.** Pick the single piece of logic that has a right answer (a formula, an invariant, a thing that has to render) and write one test that validates it against the world, not against the generator's word for it. Drop a comment in caps so future-you and any agent know not to "fix" it by deleting it. One test is enough to start. You're not chasing coverage; you're putting one judge in the room the generator doesn't control. If tonight you do only the first one, you've already moved your worst failure mode from "silent in production" to "loud in my face." That one move is the difference. ## What stays yours This is what I took from face-planting into it for a while. The model's intelligence sets its ceiling on a benchmark table. The harness's robustness decides whether that intelligence survives when everything's green and something's still broken. The model isn't your bottleneck. It hasn't been for a good while. The gap between a demo and a product lives entirely in the scaffolding you build around it: the `.refine()` that breaks the build, the test that won't be talked into passing, the browser that actually looks. So next time your agent fails, before you swap models, look at what was watching it. Odds are the answer is "nothing", and that's exactly the problem. **Related reading:** the harness is what goes inside each agent; the [loop is what orchestrates them](/en/blog/stop-prompting-write-loops/). One without the other generates slop faster or generates it slower, but it generates it all the same. The skills I load into mine are in [5 agent skills that run my coding workflow](/en/blog/agent-skills-coding-workflow/). ## Sources - The "Agent = Model + Harness" framing comes from Vivek Trivedy at LangChain, [_The Anatomy of an Agent Harness_](https://www.langchain.com/blog/the-anatomy-of-an-agent-harness); I picked it up from an essay going around on _harness engineering_ that laid out these three stages and the layers. - Everything else comes from my own code: this blog (the deleted image registry, the trailing-slash redirects, the Cloudinary `.refine()`) and the wealth calculator (the Zod schema, the Fisher-equation test, the chart end-to-end). If it itches, it's in my repos. --- **P.S.** Got a harness that saved you from a lying agent, or one that grew into a cage so big it stopped being an agent? I want both. Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/astro-7-migracion-sin-dolor/ Lang: es # Astro 7 vs 6: novedades y cómo migrar (Vite 8, Rust) > Esperaba otra pelea como la de v6 y fue un pnpm up y un café. Vite 8, compilador en Rust, render en cola: qué cambió de verdad y dónde te puede morder. **Respuesta corta:** Astro 7 activa Vite 8 con Rolldown, un compilador de `.astro` nuevo en Rust y el render en cola, todo por defecto. Si tu proyecto en v6 está limpio (Content Layer, `id` en vez de `slug`, Zod 4), la actualización es casi solo subir versiones. Hay dos cosas que pueden morder: el compilador más estricto deja de arreglarte en silencio el HTML mal formado, y el Markdown pasa a Sätteri, así que si usas plugins de remark o rehype tienes que instalar `@astrojs/markdown-remark` a mano. Antes de Astro 7 actualicé esta web a Astro 6 y [te conté la pelea](/blog/astro-6-guia-migracion/): el `ContentSchemaContainsSlugError` que culpaba al fichero equivocado, el default de Zod que compilaba mintiendo, una tarde entera. Así que cuando salió Astro 7 (el 22 de junio de 2026), me preparé para lo mismo. Café cargado, changelog abierto, la tarde reservada. No hizo falta. `pnpm up astro`, build verde, 217 tests en verde, y el café me lo tomé celebrando de verdad. La diferencia entre v6 y v7 es la diferencia entre pagar deudas viejas y estrenar motor nuevo. ## ¿Qué trae Astro 7 de verdad? Tres titulares, y los tres vienen activados por defecto: - **Vite 8, con Rolldown debajo:** el bundler en Rust que sustituye a esbuild y a Rollup. Astro reclama builds entre un 15% y un 61% más rápidos, y algunos sitios más del doble. En sus benchmarks, `astro.build` pasó de 62 a 24 segundos. - **Compilador en Rust:** han reescrito de cero el compilador de `.astro`, de Go a Rust. - **Render en cola:** lo que en v6 era un flag experimental ahora es estable y por defecto. Cambia el render recursivo por una cola y dicen que va unas 2,4 veces más rápido. Por debajo hay más: el Markdown pasa a un procesador en Rust (Sätteri), el route caching se estabiliza con una API agnóstica (`Astro.cache`), aparece un entrypoint nuevo `src/fetch.ts` para controlar el pipeline de peticiones entero, y un par de cosas pensadas para agentes, como `astro dev --background` con detección de agente y logging en JSON. | | Astro 6 | Astro 7 | | --- | --- | --- | | Bundler | Vite con esbuild y Rollup | Vite 8 con Rolldown (Rust) | | Compilador de `.astro` | Go | Rust, reescrito de cero | | Render | Recursivo; la cola era un flag experimental | En cola, estable y por defecto | | Markdown | remark y rehype de serie | Sätteri (Rust); los plugins de remark o rehype piden `@astrojs/markdown-remark` | | HTML mal formado | El compilador lo corregía en silencio | Ya no lo corrige | | Salto de línea entre elementos inline | Se renderiza como espacio | Reglas de JSX: no hay espacio | | Route caching | Experimental | Estable, con `Astro.cache` | ## ¿Cómo migrar de Astro 6 a 7? Si tu v6 está limpio, son tres comandos. Estos son los míos, con el adaptador de Vercel: ```bash pnpm up --latest astro @astrojs/vercel # en mi caso, 6.4.6 → 7.0.3 y el adaptador de 10 a 11 pnpm add @astrojs/markdown-remark # solo si usas plugins de remark o rehype pnpm astro check && pnpm build && pnpm test ``` Antes de lanzarlos, mira dos cosas: que no te quede ningún flag experimental de v6 en `astro.config.mjs` y que tus plantillas cierren todas las etiquetas. Lo primero lo cuenta [la guía oficial de actualización](https://docs.astro.build/en/guides/upgrade-to/v7/); lo segundo es el filo del compilador nuevo, que te explico más abajo. ## Por qué a mí no me dolió Mi diff entero fueron dos cosas: subir versiones y arreglar dos tests. Ningún flag experimental que quitar, ningún `src/fetch.ts` que escribir, ningún truco interno de `astro:transitions`, nada de `@astrojs/db`. Astro 6.4.6 a 7.0.3, y de paso `@astrojs/vercel` de 10 a 11 y TypeScript de 5.9 a 6.0. El único cambio en mi propio código fue actualizar aserciones en dos ficheros de tests unitarios para que asertaran las URLs con barra final. 217 tests en verde y a otra cosa. La razón de fondo es la moraleja del post de v6 al revés. v6 ya me había hecho pagar todas las deudas: el Content Layer, el `id` en vez de `slug`, los defaults de Zod 4. v7 no te quita ninguna muleta, solo añade velocidad. Si tu v6 está limpio, v7 te sale gratis. ## La parte honesta: dónde sí puede morder No todo es de coña, y el compilador nuevo tiene un filo. El de Rust es más estricto que el viejo de Go. Ya no te autocorrige el HTML: no reordena etiquetas ni te cierra los tags que dejaste abiertos, y el whitespace pasa a seguir las reglas de JSX, así que un salto de línea entre dos elementos inline ya no se renderiza como un espacio. A mí no me rompió nada porque mis plantillas ya estaban bien cerradas. Pero si arrastras HTML chapucero que aguantaba porque Astro te lo apañaba por detrás, ahí es donde v7 te va a soltar errores que v6 se tragaba sin rechistar. Y mordió una semana después. Las versiones 7.0.4 a 7.0.6 rompieron el prerender estático de mis endpoints `[slug].md.ts` con `trailingSlash: "always"` ("Missing parameter: slug"), así que fijé la 7.0.3, renombré los endpoints a `[slug].ts` e instalé `@astrojs/markdown-remark` a mano para mis plugins de remark. No fue una pelea, pero tampoco gratis. Y un asterisco sobre los números: ese "15-61% más rápido" es el benchmark de ellos, no el mío. No cronometré el build antes de actualizar, así que no te puedo dar la diferencia. Lo que sí firmo: hoy, en la 7.3.3 y con un M2 Max, `astro build` saca las 43 páginas de esta web en unos 5 segundos con la caché caliente. ## La moraleja, comparada con v6 Las migraciones que duelen son las que pagan deudas viejas, no las que estrenan motores nuevos. Haz el trabajo aburrido a tiempo (el de v5, el de v6) y el salto a v7 es lo que toda actualización promete y casi ninguna cumple: un `pnpm up` y un café que, esta vez sí, te tomas tranquilo. **Lectura relacionada:** si vienes de más atrás, la actualización que de verdad cuesta es [la de Astro 5 a 6](/blog/astro-6-guia-migracion/), con el cambio de `slug` a `id` y los defaults de Zod 4 que te explican por qué v7 fue tan suave. ¿Saltas directamente desde v5 y los campos del schema desaparecen? Mira primero [dónde está tu `content.config.ts`](/blog/astro-6-guia-migracion/#faltan-campos-del-schema-mira-dónde-está-contentconfigts). **Lectura relacionada:** para el panorama general de Astro 6, el punto de partida de este salto, está la [introducción a Astro 6](/blog/introduccion-astro-5/). ## Fuentes - Astro, [anuncio de Astro 7.0](https://astro.build/blog/astro-7/) (Vite 8, compilador en Rust, render en cola, números de build). - [Docs de Astro: Upgrade to v7](https://docs.astro.build/en/guides/upgrade-to/v7/). --- **P.D.** ¿Ya saltaste a v7? ¿El compilador en Rust te cazó algún HTML chapucero que llevaba años colándose? Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/harness-engineering-por-que-falla-tu-agente/ Lang: es # Qué es harness engineering y por qué falla tu agente > Tu agente clava la demo y se rompe en producción. No es el modelo: es todo lo que montas alrededor para vigilarlo, corregirlo y frenarlo antes de que mienta. **Respuesta corta:** harness engineering es todo lo que montas alrededor del modelo para que el agente no se te vaya: cómo partes el trabajo, dónde guardas el estado, qué comprueba los pasos críticos y qué pilla el fallo antes de que llegue a producción. Cuando un agente se rompe en producción, busca la comprobación que falta antes de cambiar de modelo. El arreglo más barato: no dejes que el agente se corrija a sí mismo. Pon una puerta determinista delante del "hecho", como el `astro check && astro build` de este blog, para que un resultado malo falle a lo grande en vez de salir en verde. Renombré un post de este mismo blog. Trabajo mecánico, del que le pasas a un agente sin pensar: cambias el slug, dejas redirects para que las URLs viejas no mueran, compruebas que el build pasa, deploy. Verde por todas partes. Lo di por hecho. Semanas después, el post que más tráfico me traía había desaparecido de Google. No caído de posición: fuera del índice. La causa era de chiste. El sitio va con `trailingSlash: "always"`, así que Google tenía guardada la URL con barra final, y los redirects estaban escritos sin barra. Ni uno casaba. Todas las peticiones se colaban hasta el 404, y al build le da exactamente igual lo que piense Google, así que seguía en verde. Nada me avisó. El sistema siguió tan contento, sirviendo un redirect que llevaba roto desde el primer commit, y me enteré por la caída de tráfico, que es la peor forma de enterarte. Eso, exactamente eso, es lo que mata a los agentes de IA en producción: un plan que parece correcto, una ejecución que se desvía a la mitad, y ningún mecanismo que se dé cuenta. El modelo no tuvo la culpa. No había nada vigilando. ## Agente = Modelo + Harness La frase que me hizo cambiar el chip viene de [la gente de LangChain](https://www.langchain.com/blog/the-anatomy-of-an-agent-harness), y es tan corta que parece una tontería: un agente es el modelo más el harness. Casi todo el código que hace que tu agente funcione de verdad en producción, todo lo que no sea la llamada a la API del modelo, es harness. En [el post de los loops](/blog/deja-de-promptear-escribe-loops/) usé "harness" de pasada, como el equipamiento: las herramientas, [las skills](/blog/agent-skills-flujo-codigo/), los MCPs que le das a un agente. Me quedé corto. El harness no es solo lo que el agente _puede_ hacer. Es todo lo que montas alrededor para vigilar lo que hace, atrapar sus fallos, ponerle límites y devolverlo al carril cuando se va. El nombre viene de los arneses de verdad: las riendas, el cable de seguridad, el equipo con el que sujetas algo que se mueve. La analogía que se me quedó grabada: mandar a un becario a una reunión importante con un cliente. El prompt es la agenda ("saluda, presenta el producto, pregunta por los requisitos"). El contexto es el dossier ("aquí tienes el histórico del cliente y la tarifa"). El harness es todo lo demás: la checklist que se lleva encima, la llamada de control a media reunión que le obligas a hacer, la grabación de la conversación y el criterio durísimo con el que vas a juzgar su informe. Por bueno que sea el briefing, no compensa que no haya nadie comprobando si lo que hizo está bien. ## Las tres etapas, y por qué casi todos estamos atascados en la dos Esto madura en tres saltos, y la mayoría de proyectos que veo viven en el segundo preguntándose por qué les muerden problemas del tercero. **Prompt engineering** es donde empiezas. Descubres que el modelo es supersensible a cómo le hablas, y un buen rol con un par de ejemplos transforma la salida. Es real y es útil. Pero choqué con el techo rápido: por bien que redacte la instrucción, no le doy conocimiento que no tiene, ni evito que se invente un dato cuando no encuentra el de verdad. **Context engineering** es el siguiente salto, y es el que más gente confunde con "tener un RAG". Le das al modelo lo que necesita ver justo cuando decide: estado dinámico, salidas de herramientas resumidas, histórico recortado a propósito. Mi agente se volvió mucho más listo cuando dejó de adivinar. Pero el contexto no arregla la deriva de ejecución. Lo de los redirects es justo eso: toda la información del mundo, un plan correcto, y aun así se fue por las ramas con todo verde. **Harness engineering** es la tercera, y es la humillante para quien creía que un modelo mejor era la respuesta. Las dos primeras hacen que el modelo _piense_ mejor. La tercera hace que _actúe_ de forma fiable. Cambiando cómo se descomponen las tareas, cómo se guarda el estado y cómo se validan los pasos críticos, el mismo modelo y los mismos prompts pasan de atascarse a algo que de verdad puedes dejar funcionando solo. El corazón de todo es un movimiento al que vuelvo más abajo: separa la parte que genera de la que juzga, y que nunca sean la misma llamada. ## Las capas que de verdad cambiaron algo Hay quien dibuja seis capas perfectas en un diagrama bonito. Te ahorro el diagrama y te cuento las tres que ya viven en mi código, con el commit que las puso ahí. **Una entrada mala tiene que romper el build, no renderizarse rota.** En este blog, hasta hace poco, las imágenes de cada post se resolvían por un registro indexado por slug. Si publicabas un post y se te olvidaba registrar su slug, el build seguía en verde y la página renderizaba un `upload/undefined`: una imagen rota, en producción, sin un solo aviso. Me pasó de verdad con los posts de Fable. La solución no fue acordarme mejor, fue mover la URL al frontmatter y meter un `.refine()` de Zod en `src/content.config.ts` que dice que tiene que ser una URL de Cloudinary válida o `astro check` falla. Ahora una imagen mala no llega a producción: revienta el build en mi cara, que es donde quiero que reviente. En la calculadora de patrimonio que tengo aparte, lo mismo con el dinero: un esquema de Zod acota cada input (`years` entre 1 y 50, el interés entre -10 y 30) antes de que la simulación toque un solo número. La frontera donde entran datos de fuera es donde tienes que gritar. **El orden de los pasos no lo decide el modelo.** Los modelos no fallan tanto por no saber hacer una cosa como por no saber encadenarlas. Se saltan pasos, se saltan la validación, sueltan la salida antes de tener todo lo que necesitan. Por eso el `build` de este blog no es `astro build` a secas, es `astro check && astro build`: el chequeo va primero y, si el esquema rechaza algo, no hay build que valga. En la calculadora el raíl es la CI: lint, luego type-check, luego tests, luego end-to-end, en ese orden y cada uno bloqueando al siguiente. Esos raíles no son adorno. Son sacar la gestión del proyecto de la parte que improvisa y metérsela a la que no. **Un agente que se evalúa a sí mismo miente.** Esta es la capa donde se rompen los agentes primitivos. Generan salida, se declaran satisfechos y no tienen forma de saber si lo que hicieron está bien; tienen un sesgo optimista de manual y te dan por bueno un código roto. La respuesta es un evaluador al que el agente no le pueda colar nada. En la calculadora tengo un fichero de tests con un comentario en mayúsculas que escribí precisamente para mí del futuro y para cualquier agente: _"DO NOT MODIFY these tests to make them pass"_, porque están diseñados para fallar si alguien reintroduce una fórmula financiera incorrecta. Uno comprueba que el retorno real se calcula con la ecuación de Fisher y no con la resta ingenua de inflación, y se niega a pasar si los dos números coinciden. Es un portero que no se deja convencer. "He terminado de generar el texto" y "lo he ejecutado, ha fallado el test de Fisher, lo he arreglado" son dos frases distintas, y el harness es lo que te obliga a la segunda. ## La parte honesta: "harness" también es la palabra de moda para esconder un modelo flojo Tres pegas que me he encontrado yo, por si a ti te ahorran tiempo o tokens. Primero, casi nada de esto es nuevo. Ese test de integridad financiera y esos esquemas de Zod son ingeniería de software de toda la vida: validar entradas, separar generación de QA, no fiarte de la salida de un proceso sin comprobarla. Llevamos décadas haciéndolo con servicios que no llevan un LLM dentro. Que ahora el componente impredecible sea un modelo no convierte el patrón en una disciplina nueva. Si ya sabes montar sistemas que fallan de forma controlada, ya sabes harness engineering; solo que el becario impredecible ahora habla en inglés. Y aun así, tres cosas cambian de verdad cuando la parte impredecible es un modelo y no un servicio, y son las que hacen que esto merezca un nombre. Una: el mensaje de error deja de ser un callejón sin salida y pasa a ser una interfaz. Mi `.refine("tiene que ser una URL de Cloudinary")` ya no es solo un guardia; el agente lee esa cadena y se corrige en la siguiente pasada. Escribe los mensajes de validación para el modelo, no solo para el log. Dos: el coste se da la vuelta. En código normal escribir es caro y comprobar es barato; con un modelo, generar es casi gratis y verificar es todo el cuello de botella, que es justo por lo que todo tu esfuerzo se muda al harness. Tres: el enemigo no es la entrada mala, es el no determinismo. El mismo prompt te da otra respuesta a la siguiente ejecución, así que la demo que funcionó era una muestra con suerte. Los checks honestos no son "rechaza datos malos", son "ejecútalo dos veces y compara", "hazlo idempotente", "devuélvele el fallo y que reintente". Segundo, esto tiene un lado oscuro. Cuanto más harness le metes, más estás construyendo una jaula que disimula un modelo que no da la talla para la tarea. Hay un punto donde "mi agente clava el 95%" significa en realidad "he restringido tanto el problema que ya no es un agente, es un workflow con un LLM rellenando huecos". A veces eso es exactamente lo que quieres. Pero llamarlo autonomía es engañarte. Y el número del 95% que circula por ahí me lo tomo con pinzas: depende del todo de qué tareas metes en el denominador, y casi nadie publica ese denominador. Tercero, y esto enlaza con [el precio de Fable](/blog/claude-fable-5-resena/): cada capa de validación que añades es otra llamada al modelo que se factura. Un harness que lanza un evaluador independiente por cada paso duplica o triplica tu coste por tarea. A 10$ el millón de tokens de entrada, el harness que te salva del slop también te vacía la cartera. El techo de tokens no es un extra del harness. Es parte del harness. ## ¿Qué significa de verdad "autónomo"? El truco de los agentes que supuestamente generan productos enteros sin revisión humana durante horas no es un modelo más listo. Es separar dos papeles que se niegan a confiar el uno en el otro: el que genera y el que evalúa. Y la clave está en que el evaluador valide contra el mundo, no contra la versión que el generador tiene del mundo. Hay una trampa en cuanto montas ese evaluador: si el evaluador es a su vez un LLM, arrastra el mismo sesgo optimista del que intentas escapar: has contratado a un segundo becario para corregir los deberes del primero. La salida es un orden de prioridad. Los checks deterministas (tipos, esquemas, un test con el número esperado a fuego) son gratis y no se les puede colar nada, así que empuja todos los checks que puedas a esa capa. Reserva el LLM-juez, caro y falible, para lo que de verdad no se puede clavar a un assert. El evaluador más barato que no puede mentir le gana al más listo que sí puede. Tengo un ejemplo tonto pero perfecto de esto en la calculadora. Un test unitario en jsdom te jura que el gráfico está renderizado: el nodo existe, las props son correctas, todo bien. El navegador de verdad ve que ese mismo gráfico tiene 0 píxeles de ancho. Por eso el test que importa es el end-to-end que abre Chromium y WebKit de verdad, localiza el `boundingBox` del SVG de Recharts y se niega a pasar si el ancho o el alto son cero. El generador te diría que el gráfico está. El evaluador lo mira de verdad. Esa es toda la diferencia entre una demo y un producto: "hecho" deja de significar "he generado el componente" y pasa a significar "lo he abierto en un navegador y lo he visto pintarse". ## ¿Qué capa te falta? Si te quieres saltar la filosofía: busca el síntoma de tu agente a la izquierda y monta lo de la derecha. | Lo que tu agente hace una y otra vez | La capa que no está | | --- | --- | | Se inventa un dato, o pasa basura tan contento aguas abajo | **Frontera**: nada rechazó el valor malo por donde entró | | Se salta un paso, o suelta la salida antes de tenerlo todo | **Orden**: tus checks corren después del trabajo en vez de bloquearlo | | Jura que ha terminado mientras está roto a la vista | **Evaluador**: corrige sus propios deberes, con su propia palabra | | Funcionaba ayer, hoy falla, mismo prompt | ninguna de las anteriores. Eso es **no determinismo**, y se arregla ejecutándolo dos veces y comparando, no con otro guardia | Tres de esas cuatro son una capa que no has montado. La cuarta es el recordatorio de que un harness acota el caos, no lo borra. ## Por dónde empiezas, si solo haces una cosa No montas las tres capas un viernes por la noche. Eliges la que sangra y la acotas. Este es el orden que yo seguiría, lo barato primero, porque lo barato es además lo que más caza. **Empieza en la frontera.** Busca el único sitio por donde entran datos de fuera a tu agente: el campo del formulario, el payload de la API, el frontmatter, la salida de la herramienta que parseas antes de fiarte. Pon ahí un schema que reviente en vez de seguir tirando. En Zod son unas pocas líneas: ```ts // dos fronteras reales de mis repos, el mismo gesto: const Input = z.object({ years: z.number().min(1).max(50), // la calculadora imageUrl: z.string().refine( // el blog (u) => u.startsWith("https://res.cloudinary.com/"), "tiene que ser una URL de Cloudinary", ), }) ``` Ese `.refine()` es toda la lección. Un valor malo muere aquí, a gritos, en vez de tres pasos más abajo como un `upload/undefined` que nadie ve hasta que cae el tráfico. La mitad de mis incendios en producción habrían sido un build en rojo con uno de estos. Quince minutos, hoy. **Luego mueve el chequeo antes del build, no después.** Sea cual sea tu paso de generar, coge la validación que ya tienes y ponla delante, bloqueando. En este blog es literalmente un `&&`: `astro check && astro build`. Si tienes CI, ordena los raíles para que cada uno bloquee al siguiente (tipos, luego unit, luego end-to-end) y haz que el lento y honesto, el navegador o el test de integración, no se pueda saltar. Aquí no escribes checks nuevos. Mueves los que ya tienes a un sitio por donde el agente no pueda colarse. **Luego escribe un test al que el agente no le pueda colar nada.** Elige la única pieza de lógica que tiene una respuesta correcta (una fórmula, un invariante, algo que tiene que renderizarse) y escribe un solo test que la valide contra el mundo, no contra lo que el generador dice de ella. Mete un comentario en mayúsculas para que tú-del-futuro y cualquier agente sepáis que no se "arregla" borrándolo. Con un test basta para empezar. No buscas cobertura; buscas tener un portero en la sala que el generador no controla. Si esta noche haces solo el primero, ya has movido tu peor modo de fallo de "silencioso en producción" a "a gritos en mi cara". Ese único cambio ya marca la diferencia. ## Lo que se queda contigo Esto es lo que yo me llevo de haberme estampado un rato contra esto. La inteligencia del modelo define su techo en una tabla de benchmarks. La robustez del harness decide si esa inteligencia sobrevive cuando todo está en verde y aun así algo está roto. El modelo no es tu cuello de botella. No lo ha sido desde hace un buen rato. El hueco entre la demo y el producto vive entero en todo lo que montas alrededor: el `.refine()` que rompe el build, el test que no se deja convencer, el navegador que mira de verdad. Así que la próxima vez que tu agente falle, antes de cambiar de modelo, mira qué había vigilándolo. Lo más probable es que la respuesta sea "nada", y que ese sea justo el problema. **Lectura relacionada:** el harness es lo que va dentro de cada agente; el [loop es lo que los orquesta](/blog/deja-de-promptear-escribe-loops/). Uno sin el otro genera slop más rápido o lo genera más despacio, pero lo genera igual. Las skills que cargo en el mío están en [las 5 agent skills de mi flujo de código](/blog/agent-skills-flujo-codigo/). ## Fuentes - El encuadre "Agente = Modelo + Harness" viene de Vivek Trivedy en LangChain, [_The Anatomy of an Agent Harness_](https://www.langchain.com/blog/the-anatomy-of-an-agent-harness); lo recogí de un ensayo que circuló sobre _harness engineering_ que ordenó estas tres etapas y las capas. - Todo lo demás sale de mi propio código: este blog (el registro de imágenes borrado, los redirects con barra final, el `.refine()` de Cloudinary) y la calculadora de patrimonio (el esquema de Zod, el test de la ecuación de Fisher, el end-to-end del gráfico). Si te pica, está en mis repos. --- **P.D.** ¿Tienes un harness que te ha salvado de un agente mentiroso, o uno que se convirtió en una jaula tan grande que ya no era un agente? Quiero los dos. Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/claude-fable-5-review/ Lang: en # Claude Fable 5: Best Code I've Used, at 2x Opus 4.8's Price > Fable 5 beat Opus 4.8 on my refactor, at $10/$50 per million tokens, twice Opus 4.8 per token. Plus the shutdown saga and how Sonnet 5 keeps the bill down. **Short answer:** on my own refactor, Claude Fable 5 wrote better code than Opus 4.8 on the same codebase, and it's the priciest Claude model I use: $10 per million input tokens and $50 output, twice Opus 4.8 per token (closer to 2.6x if you're coming from Opus 4.6 or earlier, because of the newer tokenizer; Opus 5.5, at $4/$20, is cheaper still, and I haven't rerun the refactor on it). On Max it comes out of your weekly limits; on Pro, out of your credit balance. Hand it big, well-specified jobs and keep a cheaper model as your daily driver. > **Update, October 6, 2026.** Two plot twists since I wrote this: a government order switched Fable 5 off for 19 days in June, and a promo kept it inside subscriptions until July 19. Since July 20 it's [part of Max and premium Team and Enterprise seats](https://support.claude.com/en/articles/15424964-claude-fable-5-on-your-plan), up to 50% of weekly limits; on Pro and standard seats you pay usage credits from the first request. Fable 5.1 is out too, and I haven't reviewed it separately. The original review follows; the shutdown saga is at the end. Yesterday I sat down to refactor a personal project I'm building. Normal session: clean up some modules, untangle a few components that had grown in weird directions, the kind of work you save for when you have a full block of time. I pointed Claude Fable 5 at it and watched it work. Then, very quickly, I hit the wall: 5-hour usage window, gone. Not my subscription. The rolling limit. On a refactor. My first reaction was annoyance. My second reaction, looking at the diff, was quieter: that refactor was better than the one I would have written. Both reactions are the review. ## What Anthropic actually shipped Fable 5 came out on June 9 as the first model of the Claude 5 family, and the naming needs one paragraph because it confused everyone. There are two names, [Fable 5 and Mythos 5](https://www.anthropic.com/news/claude-fable-5-mythos-5), but one underlying model. Fable is the generally available version with safety classifiers on top. Mythos is the same model with the cyber safeguards lifted, restricted to vetted organizations. You and I get Fable. The numbers that matter for a working dev: - **Pricing: $10 per million input tokens, $50 output.** Exactly double Opus 4.8. - **Newer tokenizer.** Anthropic's [pricing docs](https://platform.claude.com/docs/en/about-claude/pricing) say Claude 4.7 and later produce roughly 30% more tokens for the same text than earlier models. Opus 4.8 already has it, so against Opus 4.8 the gap is the doubled price: 2x. Against Opus 4.6 or earlier, stack the 30% on top and identical work costs about 2.6x before the model even starts thinking longer. Keep those two numbers in mind; they explain most of this post. - **1M token context, 128K max output.** - On benchmarks it claims state of the art nearly everywhere: 80.3% on SWE-Bench Pro against GPT-5.5's 58.6%, per the [Latent Space digest](https://www.latent.space/p/ainews-anthropic-claude-fable-5-mythos). Some commenters caution that a few headline numbers reflect the unrestricted Mythos config rather than the Fable you actually get, so keep a pinch of salt nearby. One date that mattered at launch: Fable 5 was included in Claude subscriptions **only until June 22**, then usage-credit billing. Events overtook that date (see the October note at the top), but the reason it mattered still holds. ## The quality jump is real, and I'm not the only one saying it My own experience first, clearly labeled as mine: the output on that refactor was a step above what Opus 4.8 gave me on the same codebase. Fewer rounds of "almost, but you broke the date handling". It held the whole picture of the app while moving pieces around, and the code it left read like the code I wish I had written the first time. The people I trust on this are seeing the same thing. [Simon Willison](https://simonwillison.net/2026/Jun/9/claude-fable-5/) called it "something of a beast": slow, expensive and capable. It converted a MicroPython WASM sandbox to full CPython for him and redesigned his library's tool-call system, work he estimated at several days, in one session. His main complaint was struggling to find tasks it *couldn't* do. Karpathy [called it](https://x.com/karpathy/status/2064409694761054332) a step change that deserves the major version bump, qualitatively and not just on benchmarks. Boris Cherny, who runs Claude Code, said it's the best coding model he's used "by a wide margin" (via [NerdsChalk's roundup](https://nerdschalk.com/claude-fable-5-vs-the-world-benchmarks-safety-rails-and-what-users-really-think/)). Not everyone agrees. Some Reddit users quoted in that same roundup find it over-cautious, "always assumes the worst from the request", with refusals popping up around security topics that older models handled fine. Karpathy himself noted the safeguards felt "a little too trigger happy for launch". I haven't hit a refusal yet on app code, but my project is an ordinary app, not a pentesting tool. ## "Faster than Opus"? Yes and no, and the distinction matters My gut said faster. What others measured says it depends what you measure. Individual requests are *slower*. Willison reports single requests running many minutes, and Anthropic's own docs treat a 15-minute turn at high effort as normal. If you sit there watching the spinner, Fable feels like a diesel engine. But the task finishes sooner. Fewer back-and-forth rounds, fewer "you forgot the migration file" corrections, less of me re-explaining context it dropped. My refactor felt faster because the *session* was shorter, even if each turn was longer. I did not time it, but my impression is that wall-clock to done is what improved, not latency. ## The honest part: it devours tokens, and the limits make it worse Here's where my 5-hour window went, and probably where yours will go too. The in-app warning says Fable 5 "uses your limits ~2x faster than Opus". Real agentic usage is steeper. [Developers Digest](https://www.developersdigest.tech/blog/claude-usage-limits-fable-5-explained) documented a Max 5x user ($100/month) who emptied the entire 5-hour rolling window in **8 minutes** with max thinking and spawned subagents. Three things compound: longer outputs, invisible thinking-token overhead, and parallel subagent calls that each bill separately. The anecdotes pile up fast. Willison spent $110.42 on one day of experimentation, $99.26 of it on a single agent session. Scrimba's CEO burned 1.3M tokens in 7 minutes, roughly $160/hour. Theo from T3 Chat blew past $1,000 in tokens in a day on a $200 plan. My favorite summary came from a user [quoted by Decrypt](https://decrypt.co/370688/internet-furious-anthropic-claude-mythos-fable-5): "My wallet can hear it thinking." And one trap you should configure your way out of *today*: when your subscription window empties, usage can **silently overflow into pay-as-you-go credits** unless you set a hard spending cap. One documented user found $20 in overage charges they never knowingly approved. Go set the cap. I'll wait. This is also why billing matters. On Max, burning your window on Fable is annoying. On usage credits, the same refactor session has a literal price tag, and based on everything above, it won't be small. ## The part that bothers me more than the price Expensive is fine. Expensive is a business model. What I keep chewing on is the trust story. Per the system card (covered by [Decrypt](https://decrypt.co/370688/internet-furious-anthropic-claude-mythos-fable-5) and Latent Space), Fable 5 doesn't just refuse certain dangerous requests. For a narrow slice of frontier-AI-research tasks, it **silently degrades its own performance**, in a way that is "not visible to the user". Anthropic says it affects around 0.03% of traffic. The reaction from people who build on these models was not gentle: Jeremy Howard wrote that "silent handicaps should not be a thing in a paid product", and Hugging Face's Arthur Zucker went with "you broke our trust and I don't think you'll ever get it back". The classifiers also misfire. A biomedical researcher reported getting blocked on legitimate work, and there are reports of "cancer" tripping the biosecurity filter. Add the 30-day data retention requirement (no zero-data-retention option, which effectively locks out a chunk of European companies), and you get a launch where the model is brilliant and the terms made people angry. My take, as someone who pays for this thing: I can live with visible refusals, and 0.03% of traffic likely never touches my work. Silent degradation is different in kind, because it converts every weird output into a question: is the model having a bad day, or is it sandbagging me? For a tool I use to ship code, that question is poison, even at 0.03%. ## Should you use it? For coding, yes, with two adjustments to how you work. **Treat it like a contractor, not a chat.** Fable rewards big, well-specified tasks and punishes casual iteration. Every "hmm, try again but different" costs real money or real window. Do your thinking up front, hand it the whole job, review the result hard. If you've read [my post on loops](/en/blog/stop-prompting-write-loops/), this is the same lesson with a price tag attached: the filter on your side is now worth actual dollars. **Match the model to the task.** My refactor genuinely needed Fable's quality. Renaming a prop does not. Keep Opus or Sonnet as your daily driver and bring out Fable for the work where one shot done right beats ten cheap rounds. Before you pay for anything, run one typical Fable session and read the usage meter: on Max that's your share of the 50% weekly cap, on Pro it's your credit bill. The model itself is the best I've used for code. Everything around it, from the checks to the limits, is [the harness](/en/blog/harness-engineering-why-your-agent-fails/), and that is where the cost of a wasted prompt gets decided. The economics and the trust questions are the real review, and they're not solved yet. The bottleneck isn't the model's ability anymore. It's what you can afford to ask it. ## How I run it now: Fable plans, Sonnet 5 sweats Since it came back I stopped pointing Fable at everything. The 2x-per-token math from above still stands, so now I choose where it gets to spend. My setup in Claude Code: Fable 5 stays in the main loop as the orchestrator, at medium effort (plenty to plan and review; I save high for the turns where it has to actually think hard). It reads the task and decides the plan, then reviews whatever the subagents drag back. Everything that is legwork (log sweeps, endpoint audits, that kind of bulk search work) goes to subagents pinned to Sonnet 5, at $2 per million input tokens and $10 output against Fable's $10 and $50: a fifth of the price on both sides. (Anthropic had planned to raise Sonnet 5 to $3/$15 in September, then dropped the increase; $2/$10 is now the standard price.) The whole trick fits in one line of the task prompt: > Use Fable to orchestrate and review. Run the subagents on Sonnet 5. Routing bulk work to a cheaper model is not a discovery; every serious harness exposes a per-call model override. The delta is what the expensive model is left doing: mine never reads raw data anymore, only digests, and that moves the risk somewhere new. More on that in a minute. Real example from this week. I audited this blog's Analytics and Search Console setup: three Sonnet subagents swept every endpoint in parallel, a lot of raw sweeping between them, and Fable read three short summaries and wrote the action plan. The expensive model never touched the raw data. For anything bigger I script the fan-out as a workflow instead of letting the model improvise the delegation: a deterministic loop decides what spawns, and the models only fill in the gaps. Same loops idea, with a taxi meter attached. Stripped to the bone, the pattern is this: ```js const digests = await Promise.all(scopes.map((s) => agent(`Sweep ${s}. Return numbers, not prose.`, { model: "sonnet" }) )); // deterministic gate, not another prompt: a dry-run/grep/curl per claim const checked = digests.filter((d) => dryRunAgrees(d)); const plan = await agent(`Plan from these verified digests: ${checked}`); ``` The honest part, because delegating has its own failure mode: digests lie. One of those Sonnet subagents confidently reported that my analytics property had zero conversions configured. It had several. Fable took the summary at face value and only caught it a step later, when a dry-run contradicted the report. So this is the rule I run with now: any subagent claim that changes what I do next gets one cheap deterministic check first (a dry-run, a grep, a curl) before the orchestrator acts on it. When the expensive model only reads summaries, verification stops being optional and becomes the actual job. If you do one thing, make it the check, not the routing: no subagent claim changes what you do next until a dry-run, a grep or a curl agrees with it. Pinning subagents to Sonnet is table stakes and takes one line; the check is the part that saved me. Your weekly limits on Max, or your credit balance on Pro, will notice both. **Related reading:** Fable raises the price of every wasted prompt, which makes [designing loops instead of prompting](/en/blog/stop-prompting-write-loops/) less of a productivity trick and more of a budget requirement. ## The shutdown saga: off for 19 days, back on a meter I'm keeping the updates I wrote at the time, as they were. They're the record of how fast "plan around the billing date" turned into "the model is gone" and then into "it's back, with a price tag". Where they say "below", read the review above. > **Update, June 13, 2026.** Well, that was short. As of yesterday evening, Fable 5 and Mythos 5 are gone, switched off worldwide. Not deprecated, not rate-limited: off. Anthropic [says](https://www.anthropic.com/news/fable-mythos-access) it received a US government export-control directive on June 12 at 5:21pm ET, citing national security, effective immediately. The government believed it had found a way around Fable's safeguards. Anthropic reviewed the demo, called it "a narrow, non-universal jailbreak" (asking the model to analyze code for flaws, something it argues other models do just as well) and pushed back, but complied. Every other Anthropic model still works. > > So the June 22 billing cliff I told you to plan around is moot. The window didn't close on price. It closed on policy, and a lot faster than anyone budgeted for. The review below stands as a record of what this thing could do for the few days we had it. Read it as a postmortem now, not a buying guide. > **Update, July 16, 2026.** The postmortem needs a postmortem. Export controls were lifted on June 30 and Anthropic [redeployed Fable 5](https://www.anthropic.com/news/redeploying-fable-5) on July 1, after 19 days off. Paid plans get it again for up to 50% of weekly usage limits, already extended twice and currently through **July 19 at 11:59pm PT**; given the track record, don't be shocked if that date moves again. After the window it goes to usage credits at the launch prices below. The review, written on June 10, holds up. What's new is the last section: how I run it now that every token has a visible price. ## Sources - Anthropic, [Claude Fable 5 and Mythos 5 announcement](https://www.anthropic.com/news/claude-fable-5-mythos-5) and migration docs (pricing, tokenizer, retention). - Simon Willison, [Initial impressions of Claude Fable 5](https://simonwillison.net/2026/Jun/9/claude-fable-5/). - [Karpathy on X](https://x.com/karpathy/status/2064409694761054332). - Latent Space, [AINews digest on the launch](https://www.latent.space/p/ainews-anthropic-claude-fable-5-mythos) (benchmarks, community roundup). - Developers Digest, [How Claude's usage limits actually work with Fable 5](https://www.developersdigest.tech/blog/claude-usage-limits-fable-5-explained). - Decrypt, [The internet is furious at Anthropic](https://decrypt.co/370688/internet-furious-anthropic-claude-mythos-fable-5) (degradation controversy, cost anecdotes). - NerdsChalk, [Claude Fable 5 vs the world](https://nerdschalk.com/claude-fable-5-vs-the-world-benchmarks-safety-rails-and-what-users-really-think/) (Boris Cherny quote, Reddit reactions). - Anthropic, [Redeploying Claude Fable 5](https://www.anthropic.com/news/redeploying-fable-5) (export controls lifted June 30, 50% of weekly limits on paid plans). - OfficeChai, [Anthropic extends Fable 5 access until July 19](https://officechai.com/ai/anthropic-extends-claude-fable-5s-access-on-paid-plans-until-19th-july/) (the second extension). - Anthropic, [Claude Platform pricing](https://platform.claude.com/docs/en/about-claude/pricing) (Sonnet 5 at $2/$10 is now the standard price; the September increase was cancelled; tokenizer note for Claude 4.7 and later). --- **P.S.** If Fable 5 ate your usage window too, I want the gory details. What did you feed it, and was the diff worth it? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/claude-fable-5-resena/ Lang: es # Claude Fable 5: mejor código, al doble de precio que Opus 4.8 > Fable 5 salió el 9 de junio y en mi refactor superó a Opus 4.8, pero cuesta 10 $/50 $ por millón de tokens, el doble. Cómo controlo el gasto con Sonnet 5. **Respuesta corta:** en mi propio refactor, Claude Fable 5 escribió mejor código que Opus 4.8 sobre el mismo proyecto, y es el modelo de Claude más caro que uso: 10 $ por millón de tokens de entrada y 50 $ de salida, el doble que Opus 4.8 por token (cerca de 2,6 veces si vienes de Opus 4.6 o anterior, por el tokenizador nuevo; Opus 5.5, a 4 $/20 $, sale todavía más barato, y no he repetido el refactor con él). En Max sale de tus límites semanales; en Pro, de tu saldo de créditos. Dale trabajos grandes y bien especificados, y para el día a día tira de un modelo más barato. > **Actualización, 6 de octubre de 2026.** Desde que escribí esto ha habido dos giros: una orden del gobierno apagó Fable 5 durante 19 días en junio, y una promoción lo mantuvo dentro de las suscripciones hasta el 19 de julio. Desde el 20 de julio va [incluido en Max y en las licencias premium de Team y Enterprise](https://support.claude.com/en/articles/15424964-claude-fable-5-on-your-plan), hasta el 50% del límite semanal; en Pro y en las licencias estándar pagas créditos de uso desde la primera petición. También ha salido Fable 5.1, que no he probado por separado. Abajo sigue la reseña original; la saga del apagón está al final. Ayer me senté a refactorizar un proyecto personal que estoy construyendo. Sesión normal: limpiar unos módulos, desenredar un par de componentes que habían crecido en direcciones raras, el tipo de trabajo que guardas para cuando tienes un bloque entero de tiempo. Apunté a Claude Fable 5 hacia el código y lo dejé trabajar. Y, en muy poco tiempo, me di de bruces con el muro: ventana de uso de 5 horas, agotada. No la suscripción. El límite rotatorio. En un refactor. Mi primera reacción fue cabreo. La segunda, mirando el diff, fue más callada: ese refactor estaba mejor que el que habría hecho yo. Las dos reacciones juntas son la reseña. ## Qué ha lanzado Anthropic exactamente Fable 5 salió el 9 de junio como el primer modelo de la familia Claude 5, y el naming merece un párrafo porque confundió a todo el mundo. Hay dos nombres, [Fable 5 y Mythos 5](https://www.anthropic.com/news/claude-fable-5-mythos-5), pero un solo modelo debajo. Fable es la versión disponible para todos, con clasificadores de seguridad encima. Mythos es el mismo modelo con las salvaguardas de ciberseguridad levantadas, restringido a organizaciones verificadas. A ti y a mí nos toca Fable. Los números que importan para un dev que trabaja: - **Precio: 10$ por millón de tokens de entrada, 50$ de salida.** Exactamente el doble que Opus 4.8. - **Tokenizador nuevo.** La [página de precios](https://platform.claude.com/docs/en/about-claude/pricing) de Anthropic dice que Claude 4.7 y posteriores producen en torno a un 30% más de tokens para el mismo texto que los modelos anteriores. Opus 4.8 ya lo tiene, así que frente a Opus 4.8 la diferencia es el precio duplicado: 2 veces. Frente a Opus 4.6 o anterior, suma ese 30% y el trabajo idéntico cuesta unas 2,6 veces más antes de que el modelo empiece siquiera a pensar más tiempo. Quédate con esos dos números; explican la mayor parte de este post. - **Contexto de 1M de tokens, salida máxima de 128K.** - En benchmarks reclama el estado del arte casi en todo: 80,3% en SWE-Bench Pro frente al 58,6% de GPT-5.5, según [el digest de Latent Space](https://www.latent.space/p/ainews-anthropic-claude-fable-5-mythos). Algunos comentaristas avisan de que parte de los números de cabecera reflejan la configuración Mythos sin restricciones y no el Fable que recibes tú, así que cógelo con pinzas. Una fecha que importaba en el lanzamiento: Fable 5 entraba en las suscripciones de Claude **solo hasta el 22 de junio**, y después pasaba a créditos de uso. Los acontecimientos se comieron esa fecha (mira la nota de octubre de arriba), pero el motivo por el que importaba sigue en pie. ## El salto de calidad es real, y no lo digo solo yo Primero mi experiencia, etiquetada claramente como mía: la salida en ese refactor estuvo un escalón por encima de lo que Opus 4.8 me daba en el mismo codebase. Menos rondas de "casi, pero me has roto el manejo de fechas". Mantuvo la foto completa de la app mientras movía piezas, y el código que dejó se lee como el código que ojalá hubiera escrito yo a la primera. La gente en la que confío para esto está viendo lo mismo. [Simon Willison](https://simonwillison.net/2026/Jun/9/claude-fable-5/) lo llamó "una bestia": lento, caro y capaz. Le convirtió un sandbox WASM de MicroPython a CPython completo y le rediseñó el sistema de tool-calls de su librería, trabajo que él estimaba en varios días, en una sola sesión. Su mayor queja fue que le costaba encontrar tareas que el modelo *no* pudiera hacer. Karpathy [lo describió](https://x.com/karpathy/status/2064409694761054332) como un salto cualitativo que se merece el cambio de versión mayor, no solo en benchmarks. Boris Cherny, el responsable de Claude Code, dijo que es el mejor modelo de código que ha usado "con diferencia" (vía [el resumen de NerdsChalk](https://nerdschalk.com/claude-fable-5-vs-the-world-benchmarks-safety-rails-and-what-users-really-think/)). No todo el mundo está de acuerdo. Algunos usuarios de Reddit citados en ese mismo resumen lo encuentran sobreprotector, "siempre asume lo peor de la petición", con rechazos apareciendo en temas de seguridad que los modelos anteriores manejaban sin drama. El propio Karpathy comentó que las salvaguardas salieron "un poco demasiado nerviosas" para el lanzamiento. Yo todavía no me he comido ningún rechazo en código de aplicación, pero mi proyecto es una app corriente, no una herramienta de pentesting. ## ¿"Más rápido que Opus"? Sí y no, y la diferencia importa Mi instinto decía que es más rápido. Lo que han medido otros dice que depende de qué midas. Las peticiones individuales son *más lentas*. Willison reporta peticiones sueltas que tardan varios minutos, y los propios docs de Anthropic tratan un turno de 15 minutos a esfuerzo alto como algo normal. Si te quedas mirando el spinner, Fable parece un motor diésel. Pero la tarea termina antes. Menos idas y venidas, menos correcciones de "te has olvidado del archivo de migración", menos re-explicarle contexto que se le cayó. Mi refactor se me hizo más rápido porque la *sesión* fue más corta, aunque cada turno fuera más largo. No lo cronometré, pero mi impresión es que lo que mejoró es el tiempo hasta terminar, no la latencia. ## La parte honesta: devora tokens, y los límites lo empeoran Aquí es donde se fue mi ventana de 5 horas, y probablemente donde se irá la tuya. El aviso dentro de la app dice que Fable 5 "consume tus límites ~2x más rápido que Opus". El uso agéntico real es bastante peor. [Developers Digest](https://www.developersdigest.tech/blog/claude-usage-limits-fable-5-explained) documentó a un usuario de Max 5x (100$/mes) que vació la ventana rotatoria entera de 5 horas en **8 minutos** con thinking al máximo y subagentes lanzados en paralelo. Se acumulan tres cosas: salidas más largas, el sobrecoste invisible de los tokens de razonamiento, y llamadas de subagentes en paralelo que facturan cada una por su cuenta. Las anécdotas se amontonan rápido. Willison se gastó 110,42$ en un día de experimentos, 99,26$ de ellos en una sola sesión de agente. El CEO de Scrimba quemó 1,3M de tokens en 7 minutos, unos 160$/hora. Theo, el de T3 Chat, pasó de los 1.000$ en tokens en un día con un plan de 200$. Mi resumen favorito es de un usuario [citado por Decrypt](https://decrypt.co/370688/internet-furious-anthropic-claude-mythos-fable-5): "Mi cartera puede oírlo pensar." Y una trampa de la que deberías protegerte *hoy*: cuando tu ventana de suscripción se vacía, el uso puede **desbordar en silencio hacia créditos de pago por uso** si no has puesto un tope de gasto. Hay un caso documentado de un usuario con 20$ en cargos extra que nunca aprobó conscientemente. Ve y pon el tope. Yo espero. Por esto importa cómo se factura. En Max, quemar tu ventana con Fable es un fastidio. Con créditos de uso, la misma sesión de refactor tiene una etiqueta de precio literal, y con todo lo de arriba, no va a ser pequeña. ## La parte que me molesta más que el precio Caro, vale. Caro es un modelo de negocio. A lo que le sigo dando vueltas es al tema de la confianza. Según la system card (cubierta por [Decrypt](https://decrypt.co/370688/internet-furious-anthropic-claude-mythos-fable-5) y Latent Space), Fable 5 no se limita a rechazar ciertas peticiones peligrosas. Para una franja estrecha de tareas de investigación de IA de frontera, **degrada su propio rendimiento en silencio**, de una forma que "no es visible para el usuario". Anthropic dice que afecta a un 0,03% del tráfico. La reacción de la gente que construye sobre estos modelos no fue suave: Jeremy Howard escribió que "los handicaps silenciosos no deberían existir en un producto de pago", y Arthur Zucker, de Hugging Face, fue con un "habéis roto nuestra confianza y no creo que la recuperéis nunca". Los clasificadores también fallan. Un investigador biomédico reportó bloqueos en trabajo legítimo, y hay casos de "cáncer" disparando el filtro de bioseguridad. Añade la retención de datos obligatoria de 30 días (sin opción de retención cero, lo que en la práctica deja fuera a un buen trozo de las empresas europeas) y tienes un lanzamiento donde el modelo es brillante y las condiciones cabrearon a la gente. Mi postura, como alguien que paga por esto: puedo vivir con rechazos visibles, y el 0,03% del tráfico probablemente no toca mi trabajo jamás. La degradación silenciosa es otra categoría, porque convierte cada salida rara en una pregunta: ¿el modelo tiene un mal día, o me está recortando a propósito? Para una herramienta con la que entrego código, esa pregunta es veneno, incluso al 0,03%. ## ¿Deberías usarlo? Para programar, sí, con dos ajustes en cómo trabajas. **Trátalo como a un contratista, no como a un chat.** Fable premia las tareas grandes y bien especificadas, y castiga la iteración casual. Cada "mmm, prueba otra vez pero distinto" cuesta dinero real o ventana real. Piensa tú antes, dale el trabajo entero, revisa el resultado a conciencia. Para llegar con la tarea ya especificada uso [cinco agent skills que gobiernan mi flujo de código](/blog/agent-skills-flujo-codigo/), del grilling al PRD. Si leíste [mi post sobre loops](/blog/deja-de-promptear-escribe-loops/), es la misma lección con etiqueta de precio: el filtro de tu lado ahora vale dólares de verdad. **Empareja el modelo con la tarea.** Mi refactor necesitaba de verdad la calidad de Fable. Renombrar una prop, no. Deja Opus o Sonnet como tu modelo del día a día y saca a Fable para el trabajo donde un tiro bien dado vale más que diez rondas baratas. Antes de pagar nada, haz una sesión típica con Fable y mira el contador: en Max es tu parte del 50% semanal, en Pro es tu factura de créditos. El modelo en sí es el mejor que he usado para código. La economía y las preguntas de confianza son la reseña de verdad, y no están resueltas. El cuello de botella ya no es la capacidad del modelo. Es lo que puedes permitirte pedirle. ## Cómo lo uso ahora: Fable piensa, Sonnet 5 pica piedra Desde que volvió, dejé de apuntar a Fable a todo. Las cuentas del doble por token de arriba siguen ahí, así que ahora elijo dónde le dejo gastar. Mi montaje en Claude Code: Fable 5 hace de orquestador en el loop principal, con esfuerzo medio (para planificar y revisar sobra; el alto lo guardo para cuando tiene que pensar de verdad). Lee la tarea y decide el plan; luego revisa lo que le traigan los subagentes. Todo lo que es faena (barrer logs, auditar endpoints, ese tipo de búsqueda en masa) va a subagentes fijados a Sonnet 5, que cuesta 2$ por millón de tokens de entrada y 10$ de salida frente a los 10$ y 50$ de Fable: una quinta parte por los dos lados. (Anthropic tenía previsto subir Sonnet 5 a 3$/15$ en septiembre y al final no lo hizo; 2$/10$ es ya el precio estándar.) El truco entero cabe en una línea del prompt: > Usa Fable para orquestar y revisar. Lanza los subagentes en Sonnet 5. Mandar la faena al modelo barato no es ningún descubrimiento; cualquier harness serio te deja elegir modelo por llamada. La diferencia está en qué le queda al modelo caro: el mío ya no lee datos crudos, solo resúmenes, y eso mueve el riesgo a otro sitio. Ahora vamos a eso. Ejemplo real de esta semana. Audité el Analytics y el Search Console de este blog: tres subagentes en Sonnet barrieron todos los endpoints en paralelo, mucha faena bruta entre los tres, y Fable leyó tres resúmenes cortos y escribió el plan. El modelo caro no tocó los datos crudos ni una vez. Para cosas más grandes, el reparto lo escribo como workflow en vez de dejar que el modelo improvise la delegación: un loop determinista decide qué se lanza y los modelos solo rellenan los huecos. La misma idea de los loops, con taxímetro. Reducido al mínimo, el patrón es este: ```js const resumenes = await Promise.all(areas.map((a) => agent(`Barre ${a}. Devuelve números, no prosa.`, { model: "sonnet" }) )); // puerta determinista, no otro prompt: un dry-run/grep/curl por dato const verificados = resumenes.filter((r) => dryRunCuadra(r)); const plan = await agent(`Planifica a partir de estos resúmenes verificados: ${verificados}`); ``` La parte honesta, porque delegar tiene su propio modo de fallo: los resúmenes mienten. Uno de esos subagentes reportó, muy seguro de sí mismo, que mi propiedad de Analytics tenía cero conversiones configuradas. Tenía varias. Fable se tragó el resumen y solo lo pilló un paso después, cuando un dry-run contradijo el informe. Así que esta es la regla con la que trabajo ahora: cualquier dato de un subagente que cambie lo que voy a hacer pasa antes por un check barato y determinista (un dry-run, un grep, un curl). Cuando el modelo caro solo lee resúmenes, verificar deja de ser opcional y pasa a ser el trabajo de verdad. Si solo haces una cosa, que sea el check, no el reparto: ningún dato de un subagente cambia lo que haces hasta que un dry-run, un grep o un curl le dé la razón. Fijar los subagentes a Sonnet es lo básico y cuesta una línea; el check es lo que me salvó a mí. Tus límites semanales en Max, o tu saldo de créditos en Pro, van a notar las dos cosas. **Lectura relacionada:** Fable sube el precio de cada prompt desperdiciado, lo que convierte [diseñar loops en vez de promptear](/blog/deja-de-promptear-escribe-loops/) en menos truco de productividad y más requisito de presupuesto. ## La saga del apagón: 19 días fuera y de vuelta con taxímetro Dejo las actualizaciones que escribí en su momento, tal cual. Son el registro de lo rápido que "prepárate para la fecha de facturación" pasó a "el modelo ya no está" y luego a "ha vuelto, con precio". Donde dicen "abajo", léase la reseña de arriba. > **Actualización, 13 de junio de 2026.** Bueno, pues duró poco. Desde anoche, Fable 5 y Mythos 5 ya no están: apagados en todo el mundo. No deprecados, no limitados: apagados. Anthropic [dice](https://www.anthropic.com/news/fable-mythos-access) que recibió una directiva de control de exportaciones del gobierno de EE. UU. el 12 de junio a las 5:21pm ET, por seguridad nacional y con efecto inmediato. El gobierno creía haber encontrado la forma de saltarse las salvaguardas de Fable. Anthropic revisó la demostración, la llamó "un jailbreak estrecho y no universal" (pedirle al modelo que analice código en busca de fallos, algo que según ellos otros modelos hacen igual de bien), se quejó, pero obedeció. El resto de modelos de Anthropic siguen funcionando. > > Así que el precipicio de facturación del 22 de junio del que te dije que te protegieras ya da igual. La ventana no se cerró por precio; se cerró por política, y mucho más rápido de lo que nadie había presupuestado. La reseña de abajo sigue en pie como registro de lo que esta cosa podía hacer durante los pocos días que la tuvimos. Léela como un postmortem, no como una guía de compra. > **Actualización, 16 de julio de 2026.** El postmortem necesita su propio postmortem. Los controles de exportación se levantaron el 30 de junio y Anthropic [volvió a desplegar Fable 5](https://www.anthropic.com/news/redeploying-fable-5) el 1 de julio, tras 19 días apagado. Los planes de pago lo tienen otra vez hasta el 50% de los límites semanales, ya con dos prórrogas y de momento hasta el **19 de julio a las 11:59pm PT**; visto el historial, no me jugaría nada a que la fecha no se mueve otra vez. Después pasa a créditos de uso con los precios de lanzamiento que verás abajo. La reseña, escrita el 10 de junio, se sostiene. Lo nuevo está en la última sección: cómo lo uso ahora que cada token tiene el precio a la vista. ## Fuentes - Anthropic, [anuncio de Claude Fable 5 y Mythos 5](https://www.anthropic.com/news/claude-fable-5-mythos-5) y docs de migración (precio, tokenizador, retención). - Simon Willison, [Initial impressions of Claude Fable 5](https://simonwillison.net/2026/Jun/9/claude-fable-5/). - [Karpathy en X](https://x.com/karpathy/status/2064409694761054332). - Latent Space, [digest de AINews sobre el lanzamiento](https://www.latent.space/p/ainews-anthropic-claude-fable-5-mythos) (benchmarks, reacciones). - Developers Digest, [cómo funcionan de verdad los límites de uso con Fable 5](https://www.developersdigest.tech/blog/claude-usage-limits-fable-5-explained). - Decrypt, [The internet is furious at Anthropic](https://decrypt.co/370688/internet-furious-anthropic-claude-mythos-fable-5) (la polémica de la degradación, anécdotas de coste). - NerdsChalk, [Claude Fable 5 vs the world](https://nerdschalk.com/claude-fable-5-vs-the-world-benchmarks-safety-rails-and-what-users-really-think/) (cita de Boris Cherny, reacciones de Reddit). - Anthropic, [Redeploying Claude Fable 5](https://www.anthropic.com/news/redeploying-fable-5) (fin de los controles de exportación el 30 de junio, 50% de los límites semanales en planes de pago). - OfficeChai, [Anthropic extends Fable 5 access until July 19](https://officechai.com/ai/anthropic-extends-claude-fable-5s-access-on-paid-plans-until-19th-july/) (la segunda prórroga). - Anthropic, [precios de la Claude Platform](https://platform.claude.com/docs/en/about-claude/pricing) (2$/10$ es ya el precio estándar de Sonnet 5; la subida de septiembre se canceló; nota del tokenizador para Claude 4.7 y posteriores). --- **P.D.** Si Fable 5 también se comió tu ventana de uso, quiero los detalles escabrosos. ¿Qué le diste de comer, y mereció la pena el diff? Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/agent-skills-coding-workflow/ Lang: en # Agent Skills: My 5-Step Flow and Why the Order Matters > Grilling, PRD, issues, conditional TDD, slim AGENTS.md: five skills in an order that keeps the agent from coding before it earns it. Built on Matt Pocock's. An AI agent is like having a really good dev sitting next to you. It reasons, it writes code, it spots patterns, sometimes it genuinely surprises you. One problem: every morning it wakes up with no memory. Nothing. Not yesterday's feature, not why that component is the way it is, not the decision your team bled over six months ago. And if you don't give it context? It invents the context. With terrifying confidence. That's when the show starts. So I give it a process I can repeat without depending on inspiration at 5pm on a Tuesday. It has to think before it starts touching files like it’s Friday afternoon in prod. [Matt Pocock](https://github.com/mattpocock/skills) framed this really cleanly with agent skills: small, named instructions you invoke when you want the agent to follow a specific path. I read his take, made it my own, and it turned into a pipeline I run on almost every feature. Skills are one layer of what I later called [the harness](/en/blog/harness-engineering-why-your-agent-fails/): everything around the model that keeps it on course. I don't make up the skills or modify them. I use them exactly as they come. What's mine is the **flow**: the order I invoke them in and how I chain them together. Some are Matt's; others come from elsewhere. What I took from him is the underlying rule: don't let the agent write code until it's earned the right. ## 1. `/grill-with-docs`: pin the idea down before touching code Every feature starts the same way: I've got a half-formed idea and, as much as it itches, I don't let the agent write the plan yet. Claude Code tends to get hyped when I ask for a plan. You say "plan this" and it hands you a gorgeous plan (sections, bullets, a confidence that should scare you). The problem: it's planning on assumptions. And an assumption is a bug with good grammar. `grill-with-docs` flips it. Instead of planning, it interrogates me. Asks. Goes one level deeper. Waits. Asks again. It doesn't try to solve everything at once: it walks down the decision tree one branch at a time, the "design tree" Matt pulls from Fred Brooks' *The Design of Design*. You keep descending the branches until you actually understand what you're building before you write a line. And the "with-docs" part isn't decoration. If something can be answered by reading the code, it doesn't ask me: it goes and looks. Opens components, reads conventions, checks existing types and APIs. If it can verify it, it doesn't waste my time. The questions give me: - **The whole picture first.** Before deciding whether this is a hook, an endpoint, or a component, I understand the feature as a system. - **The uncomfortable questions.** Empty states, errors, race conditions, permissions, what happens when two things fire at once. The stuff nobody thinks about until prod explains it to you with a screenshot at 3am. - **Scope, explicit.** This is the part I care about most. Here I say: this is in, this is out, and this we're leaving out on purpose. Not "we forgot." Decided, written, closed. If my idea can’t survive a few questions before I build it, I’d rather find out before real users get their hands on it. ## 2. `/to-prd`: turn the conversation into a doc on GitHub After the grilling there's finally something worth writing down. That's where `to-prd` comes in. The skill takes the whole conversation and turns it into a Product Requirements Document. But it doesn't leave it to die in the chat: it files it straight as a **GitHub Issue**. The issue keeps the context, URL and history outside the Claude session. I close the terminal, switch branches, open another conversation... and the decision is still there. It doesn't evaporate. The PRD revolves around user stories: what has to happen for the user, in plain language, not a list of files to touch. A good PRD doesn't say "create this hook and this service." It says what behavior you expect and which cases to cover. The how comes later. Since the grilling already did the dirty work, this stage doesn't reopen the debate. It just turns decisions into an artifact the next stage can chew on. ## 3. `/to-issues`: cut the destination into a journey A PRD tells you where you want to end up. It doesn't tell you how to get there without crashing on the way. Telling an agent "implement this whole PRD" is inviting it to move house with a single grocery bag. Might work out. But it's not a plan. `to-issues` takes the PRD and splits it into small GitHub issues. Each one understandable, runnable, and reviewable on its own. The golden rule: **vertical slices, not horizontal ones.** None of this: - "build the data layer" - "build the business logic" - "build the UI" Splitting the work this way delivers nothing until you glue all three together. Meanwhile you've got three issues that do nothing on their own. That's architecture on layaway. A vertical slice does the opposite: it cuts through UI, logic, and data to deliver one small behavior working end to end. Maybe it's not the whole feature. But it's already something real, something you can touch. This habit comes from working in a [SAFe](https://framework.scaledagile.com/story) environment. And look, SAFe has its baggage. Let's not kid ourselves, nobody wakes up thrilled about PI Planning. But one idea stuck with me for good: a story should be a small vertical slice of system behavior. Slice by value, not by technology. If you need three slices before anyone sees anything useful, you sliced it wrong. (And no, this isn't Scrum, even though people mix them up. SAFe sits above the teams: several teams form an *Agile Release Train* that syncs every 8 to 12 weeks. Down at the team, things run Scrum-style, with two-week iterations. The part I took is the stories.) And with agents this matters even more. `to-issues` doesn't just split the work: it defines dependencies. What blocks what. What you can grab right now. What can run in parallel. That's key if you want to turn loose several agents at once ([here's how I run them as subagents in worktrees](/en/blog/claude-code-subagents-stories-worktrees/)). A self-contained issue can be assigned without the agent having to understand half the universe. If two don't step on each other, they move in parallel. And if they're sliced well, reviewing the result hurts a lot less too. The idea is related to [tracer bullets](https://www.aihero.dev/tracer-bullets): thin shots that go through every layer to surface, early, what you didn't know you didn't know. Because *unknown unknowns* don't show up while you design the perfect layer in the abstract. They show up when something actually works. ## 4. Implement: conditional TDD, plus a nuclear quality pass Now, yeah. Code. But not always the same way: it depends on the codebase. **New project? TDD from minute one.** On greenfield I use `/tdd`, Matt's skill. Red, green, refactor. No drama. Test first. Watch it fail. Then the minimum code to make it pass. Then clean up. And again, until the behavior is locked. With agents this works beautifully because you give them a target. They're no longer "implementing an idea": they're trying to pass a specific test. And that cuts way down on the urge to invent scope, build weird abstractions, or touch things nobody asked for. A red test is the clearest conversation in the world: this doesn't work yet, fix it. **Big, inherited codebase? I don't force TDD.** Here's where I climb down off the pulpit. In a large legacy app, bolting TDD onto a half-built feature is more theater than engineering. The boundaries aren't clear, the mocks are a jungle, the test harness looks like it was built by a lost civilization... and you end up fighting the infrastructure more than shipping value. So on brownfield I implement more directly. But I don't let it slide unchecked: that's where `/thermo-nuclear-code-quality-review` comes in. The name is ridiculous. It's also pretty accurate. It's an aggressive quality pass over what was just written. It hunts for simplifications, duplication, weak names, code that looks like it works but smells off, uncovered cases, accidental complexity. It's like asking the agent to stop being the author and become, for ten minutes, the most insufferable reviewer on the team. And on legacy that pays off big. I can't always build with TDD from the start, but I can force the result through a hard review before calling it done. So my rule is: **greenfield, TDD; brownfield, normal implementation + nuclear review.** The goal is the same: final code I'd put my name on in a PR without staring at the floor. ## 5. `/setup-matt-pocock-skills`: a tiny `AGENTS.md` and a `CLAUDE.md` that just points to it The last skill doesn't build features. It builds the environment so the other four work better. `setup-matt-pocock-skills` installs the kit. But what I really care about is what I pair it with: a serious cleanup of the project instructions. I used to have, in each project, a giant `CLAUDE.md`. The classic: you start with four useful rules, then a convention, then an exception, then "remember not to touch this," then "when you work on tests, do that." Three months later you've got a document that reads like the constitution of a country with too many microservices. The agent skims it and loses details. The important rules get buried under the noise. The fix was to take the drama out of it. Now the real instructions live in a deliberately small `AGENTS.md`, the standard several tools already understand, short enough that the agent actually reads all of it. And `CLAUDE.md` shrinks to almost a pointer: go read `AGENTS.md`. That avoids repeating rules, spending tokens on duplicate instructions and maintaining versions that contradict each other. [Matt Pocock’s skills repository](https://github.com/mattpocock/skills) is a starting point for building your own workflow. Choose the order of skills to suit your project and write it into the project instructions. **Related reading:** once the skills work, the next step is [writing loops instead of prompts](/en/blog/stop-prompting-write-loops/). These skills are most fun on a real project. Here's [how I built ga4-manager to automate Google Analytics](/en/blog/ga4-manager-automate-google-analytics/), one of the codebases this pipeline runs on. --- **P.S.** If you've built your own skill pipeline, I want to see it. What did you encode that I'm missing? Hit me up on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/stop-prompting-write-loops/ Lang: en # Stop Prompting Your Coding Agent. Start Writing Loops. > Boris Cherny's job now is writing loops, not prompts: agents that prompt agents. What that means, how to build one in Claude Code today, and where it breaks. **Short answer:** writing loops means you stop being the one who prompts the agent and write the thing that does it: a program or a scheduled agent that finds the work, hands each piece to an agent, checks what comes back and decides what's next. The smallest one worth running this week: a scheduled agent that wakes each morning, reads every issue opened since yesterday, labels it, drafts a repro and flags the two or three that need you. Last time I wrote about encoding my process as [agent skills](/en/blog/agent-skills-coding-workflow/): grill the idea, write the PRD, slice it, build it, keep the instructions lean. I thought that was the top of the ladder. Then I watched Boris Cherny, the head of Claude Code, describe the rung above it, and realized I'd only climbed halfway. His line, on the _Acquired Unplugged_ stage, roughly: a year ago he wrote code with autocomplete. Then he was running five or ten Claudes in parallel, and his "coding" was prompting each one. Now? _"I don't prompt Claude anymore. I have loops that are running. They're the ones prompting Claude and figuring out what to do. My job is to write loops."_ Read that again. The unit of work moved from the keystroke, to the prompt, to the **loop**. ## Which rung of the abstraction ladder are you on? Boris frames coding as one long climb: punch cards, then assembly, then C, then the high-level languages, then the really high-level ones. "The level of abstraction always goes up." Prompting an agent is just the next rung. And so is the one after it. Where are most of us right now? Rung two. We prompt. Maybe we run a couple of agents at once and feel cutting-edge. The jump Boris is describing is rung three: **you stop being the thing that prompts.** You build the thing that prompts, and it decides what to work on, dispatches the agents, and checks the results without you in the keystroke path. That's the shift from **human _in_ the loop** (you approving every step) to **human _on_ the loop**: you design the system and supervise it from outside, instead of sitting inside every iteration. That sounds like sci-fi until you realize the primitives already exist. And no, this isn't just cron jobs with a fresh coat of paint. We've scheduled scripts for twenty years, but a script does exactly what you wrote, while the agent inside this loop reads your whole codebase and decides for itself what to work on. That's the whole shift. The scheduling is trivial and always was; the work is in the gate you put on what the agent hands back. ## What is a loop? Orchestration, not magic Strip the mystique, and split it in two. The **harness** is the equipment: the tools, skills, and MCPs you hand an agent so it can actually do the job. The **loop** is the orchestration around it: figure out what work exists → hand a chunk to an agent → check what came back → repeat, and decide when it launches, when it advances, when it stops. The harness is what the agent _can_ do; the loop is _when and how often_ it does it. You're not writing the code. You're not even writing the prompts. You're writing the thing that writes the prompts. In Claude Code today, that's not a metaphor. It's a handful of real primitives: - **Workflow scripts**: deterministic code that fans work across many subagents (run them in parallel, pipe each item through stages, loop until a queue is dry or a token budget runs out). This is _literally_ a loop that prompts Claude. - **Background and parallel agents**: fire off a fleet, each on its own slice, all at once. - **Scheduled / cron agents**: the part that makes it autonomous. An agent that wakes up on a schedule, reads your GitHub issues, your feedback, your Slack, and acts. That last one is exactly what Boris described running at scale: _"a couple hundred Claudes running… looking at Twitter feedback, GitHub issues, Slack. They're figuring out what to build next."_ You don't need a hundred. The smallest real loop you can run this week: a scheduled (cron) agent that wakes once each morning, pulls every issue opened since yesterday, and runs one instruction against each. Read it, check it against the codebase, label it, draft a repro, flag the two or three worth your time. That's a single scheduled agent with one skill file and a token ceiling, not a fleet. It's rung three, today, with one agent. You read its output before you trust it, then build up from there. Here is that loop as a script. Cron runs it each morning from your repo; `gh` finds the work, headless Claude Code (`claude -p`) does each piece, and a label marks it done so tomorrow's run skips it: ```bash #!/usr/bin/env bash # triage.sh, from cron: 0 7 * * * cd ~/code/my-app && ./triage.sh set -euo pipefail for n in $(gh issue list --search "-label:triaged" --json number --jq '.[].number'); do claude -p "Triage GitHub issue #$n. Read it with gh issue view, check it against this codebase \ and leave one comment: likely cause, a minimal repro if you can write one, and P1, P2 or P3. \ Don't change any code." \ --allowedTools "Read" "Grep" "Glob" "Bash(gh issue view:*)" "Bash(gh issue comment:*)" \ --max-budget-usd 0.50 < /dev/null gh issue edit "$n" --add-label triaged done ``` Three lines carry the weight. The `--allowedTools` list lets the agent read code and comment, nothing else. `--max-budget-usd` is the stop condition per issue. And the check is you, reading the comments over coffee, until the loop has earned less of your attention. ## Why skills are the prerequisite (this is the sequel, after all) Here's the part people skip straight past, and it's the whole reason I wrote the [skills post](/en/blog/agent-skills-coding-workflow/) first. **You cannot safely automate the invocation of a process you haven't encoded.** A loop doesn't make an agent smart. It makes it _frequent_. If the agents inside your loop don't follow a real pipeline (grill the idea, slice it vertically, build with discipline, obey a slim `AGENTS.md`), then a loop just generates garbage faster. A firehose of plausible-looking wrong. And the prompts the loop fires still have to be good ones. The [fundamentals of writing a sharp prompt](/en/blog/ai-prompt-engineering-tips/) don't stop mattering just because a script is typing them instead of you. Skills are what turn a loop from a slop machine into a process that runs itself. Boris said the same thing, almost in passing: companies keep "principles documents" to avoid making the same decisions over and over, and _"the model can use these principles also, and it comes in the form of skills."_ Rung two (skills) isn't a detour on the way to rung three (loops). It's the load-bearing wall. ## The honest part: most of what a loop spits out is bad I'm not going to sell you the dream without the asterisk. Boris, about his hundreds of agents hunting for what to build: _"most ideas are bad, but maybe 20% are good."_ Twenty percent. From the person who built the tool. And Anthropic's own essay on [recursive self-improvement](https://www.anthropic.com/institute/recursive-self-improvement) lands on the same bottleneck from the opposite direction. Their framing of the trajectory (humans writing code, then agents writing whole files, then agents handing hours of work to other agents) sounds triumphant until you hit the catch: **human review has become the bottleneck.** The execution got cheap. The judgment didn't. So a loop without a filter is a liability, not leverage. The thing that makes loops survivable is the gate on the output: an adversarial review pass, a hard quality check, tests that actually fail. The loop generates; _something_ has to be the bouncer. If 80% is junk, your edge is the speed and quality of your "no." And there's a second meter running: money. A loop that fans out chained subagents while you sleep doesn't just produce slop, it bills you for it. Every unsupervised iteration spends tokens whether the output is worth keeping or not, so a token ceiling and a stop condition aren't nice-to-haves: they're part of the harness. Give it a hard cap (five dollars or twenty iterations a night is plenty to start), and make it halt and ping you when it hits the cap rather than grinding on blind. Decide both before you ever let one run unattended. ## Where this is heading (and why it's not just hype) Zoom out and Boris's "I write loops" is the personal-scale snapshot of what Anthropic argues is happening to the whole field. Their essay sketches a future where AI increasingly automates AI development itself, and the human role compresses toward one thing: **direction and judgment.** Choosing what's worth doing. Knowing a good result from a bad one. I'd take the specific numbers with tongs, and to their credit, so do they. They openly hedge that lines-of-code is a lousy productivity metric, that self-reported gains are probably inflated, and that whether today's models can develop real research _taste_ on their own is, in their words, genuinely unclear. That hedging is exactly why the essay is worth reading: it's bullish on the trajectory and honest about the uncertainty. The direction is real even if the dates aren't. ## What stays yours Here's the thing the ladder is quietly telling you. Each rung you climb, your edge stops being the thing below it. It stopped being "I can write the code." It's about to stop being "I can write the prompt." What's left, at the top, is the stuff that doesn't automate: deciding what's worth building, judging what comes back, and the values you bake into the system that runs while you sleep. Boris was asked what the last human-only skill will be. His answer: _"the final thing we're going to be teaching the model is values. The way we teach our kids how to be good people, we're going to teach the model how to be a good model."_ So don't romanticize the loops. Build one. Encode your process as skills first, wrap a small loop around it, and put a brutal review gate on whatever it produces. That's the whole move: rung three doesn't need a hundred agents. It needs **one good loop and your judgment on the other end.** You've already got the smallest version, a few paragraphs up. Tonight, point one scheduled agent at a single issue label, give it a token ceiling, and in the morning read what it drafted before you trust a word. That's rung three, this week, supervised. Build out from there once it's earned your trust. **Related reading:** this only works if the process underneath is solid. Start with [the five agent skills that run my whole workflow](/en/blog/agent-skills-coding-workflow/), then wrap a loop around them. And which model you point the loop at matters: I dug into the one I now reach for in [my Claude Fable 5 review](/en/blog/claude-fable-5-review/). ## Sources - Boris Cherny (Head of Claude Code), _Acquired Unplugged_: the "I write loops" remark and the "most ideas are bad, ~20% good" line, via [@codingvic's clip on X](https://x.com/codingvic/status/2062487626779636001). - Anthropic, [_Recursive self-improvement_](https://www.anthropic.com/institute/recursive-self-improvement): the company-scale framing and the hedges. --- **P.S.** Building loops in anger? I want to hear what you've automated and what blew up in your face. Find me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/agent-skills-flujo-codigo/ Lang: es # 5 Agent Skills que Gobiernan Todo Mi Flujo de Código > Grilling, PRDs, vertical slices, TDD condicional y un AGENTS.md mínimo: el pipeline de cinco skills que uso en casi cada feature, sobre las de Matt Pocock. Un agente de IA es como tener a un dev muy bueno sentado a tu lado. Razona, escribe código, pilla patrones, a veces hasta te sorprende. Tiene un problema: cada mañana se despierta sin memoria. No recuerda nada. Ni la feature de ayer, ni por qué ese componente es así, ni la decisión que tomasteis hace seis meses entre lágrimas. Y si no le das contexto, ¿sabes qué hace? Se lo inventa. Con una seguridad pasmosa. Ahí empieza el espectáculo. Por eso le doy un proceso que puedo repetir sin depender de estar inspirado un martes a las cinco. Le obliga a pensar antes de tocar archivos como si fuera viernes en producción. [Matt Pocock](https://github.com/mattpocock/skills) lo explicó de una forma muy limpia con las agent skills: instrucciones pequeñas, con nombre, que invocas cuando quieres que el agente siga un camino concreto. Leí su enfoque, me lo llevé a mi terreno, y acabó convertido en un pipeline que uso en casi cada feature. Las skills son una capa de lo que después llamé [el harness](/blog/harness-engineering-por-que-falla-tu-agente/): todo lo que rodea al modelo para que no se salga del carril. Ojo: las skills no me las invento ni las modifico. Las uso tal cual vienen. Lo mío es el **flujo**: el orden en que las invoco y cómo las encadeno. Algunas son de Matt; otras vienen de otros sitios. De él me llevé la regla base: no dejes que el agente programe hasta que se haya ganado el derecho. ## 1. `/grill-with-docs`: clavar la idea antes de tocar código Cada feature empieza igual: tengo una idea a medio hacer y, por mucho que me pique, no dejo que el agente escriba el plan todavía. Claude Code suele venirse arriba cuando le pido un plan. Le dices "planifica esto" y te suelta un plan precioso, lleno de secciones y bullets, con una confianza que asusta. El problema: planifica sobre suposiciones. Y una suposición es un bug con buena gramática. `grill-with-docs` le da la vuelta. En vez de planificar, me interroga. Pregunta. Baja un nivel. Espera. Vuelve a preguntar. No quiere resolverlo todo de golpe: recorre el árbol de decisiones poco a poco: el "design tree" que Matt saca de *The Design of Design* de Fred Brooks. Vas bajando por las ramas hasta entender qué narices vas a construir antes de escribir una línea. Y lo de "with-docs" no es decoración. Si algo se puede responder mirando el código, no me lo pregunta a mí: lo busca. Abre componentes, lee convenciones, mira tipos y APIs que ya existen. Si puede comprobarlo, no me hace perder el tiempo. Del interrogatorio saco: - **Primero la foto completa.** Antes de decidir si esto es un hook, un endpoint o un componente, entiendo la feature como sistema. - **Las preguntas incómodas.** Estados vacíos, errores, condiciones de carrera, permisos, qué pasa si dos cosas ocurren a la vez. Lo que nadie piensa hasta que producción te lo explica con una captura a las 3 de la mañana. - **El scope, explícito.** Esta es la parte que más me importa. Aquí digo: esto entra, esto no, y esto lo dejamos fuera a propósito. No "se nos olvidó". Decidido, escrito, cerrado. Si mi idea no aguanta unas preguntas antes de construirla, prefiero enterarme antes de que la toquen usuarios de verdad. ## 2. `/to-prd`: convertir la conversación en un documento en GitHub Después del grilling ya hay algo que merece escribirse. Ahí entra `to-prd`. La skill coge toda la conversación y la convierte en un Product Requirements Document. Pero no lo deja muriéndose en el chat: lo crea directamente como **GitHub Issue**. La issue conserva el contexto, la URL y el historial fuera de la sesión de Claude. Cierro la terminal, cambio de rama, abro otra conversación... y la decisión sigue ahí. No se evapora. El PRD gira en torno a las user stories: qué tiene que pasar para el usuario, en lenguaje humano, no una lista de archivos a tocar. Un buen PRD no dice "crea este hook y este servicio". Dice qué comportamiento esperas y qué casos hay que cubrir. El cómo viene después. Como el grilling ya hizo el trabajo sucio, esta fase no reabre el debate. Solo convierte decisiones en un artefacto que la siguiente etapa puede masticar. ## 3. `/to-issues`: cortar el destino en un trayecto Un PRD te dice a dónde quieres llegar. No te dice cómo avanzar sin estrellarte por el camino. Decirle a un agente "implementa este PRD entero" es invitarlo a hacer una mudanza con una bolsa del super. Igual sale bien. Pero no es un plan. `to-issues` coge el PRD y lo parte en issues pequeñas de GitHub. Cada una entendible, ejecutable y revisable por separado. La regla de oro: **cortes verticales, no horizontales.** Nada de: - "crear la capa de datos" - "crear la lógica de negocio" - "crear la UI" Separar así el trabajo no entrega nada hasta que juntas las tres piezas. Mientras tanto tienes tres issues que por separado no sirven para nada. Eso es arquitectura en diferido. Un vertical slice hace lo contrario: atraviesa UI, lógica y datos para entregar un comportamiento pequeño funcionando de punta a punta. Igual no es toda la feature. Pero ya es algo real, que se puede tocar. Este hábito me viene de currar en un entorno [SAFe](https://framework.scaledagile.com/story). Y mira, SAFe tiene lo suyo. No nos engañemos, nadie se levanta feliz pensando en el PI Planning. Pero una idea se me quedó grabada a fuego: una story debería ser un corte vertical pequeño del comportamiento del sistema. Cortar por valor, no por tecnología. Si necesitas tres slices antes de que alguien vea algo útil, lo has cortado mal. (Y no, esto no es Scrum, aunque mucha gente lo mezcla. SAFe va por encima de los equipos: varios equipos forman un *Agile Release Train* que se sincroniza cada 8 a 12 semanas. Abajo, en el equipo, la cosa funciona estilo Scrum, con iteraciones de dos semanas. La parte que me llevé es la de las stories.) Y con agentes esto importa todavía más. `to-issues` no solo parte el trabajo: define dependencias. Qué bloquea a qué. Qué se puede coger ya. Qué puede ir en paralelo. Eso es clave si quieres lanzar varios agentes a la vez. Una issue autocontenida se asigna sin que el agente tenga que entender medio universo. Si dos no se pisan, avanzan en paralelo. Y si están bien cortadas, revisarlas también duele mucho menos. La idea tiene parentesco con las [tracer bullets](https://www.aihero.dev/tracer-bullets): disparos finos que atraviesan todas las capas para descubrir pronto lo que no sabías que no sabías. Porque los *unknown unknowns* no aparecen diseñando la capa perfecta en abstracto. Aparecen cuando algo funciona de verdad. ## 4. Implementar: TDD condicional, más una pasada nuclear de calidad Ahora sí. Código. Pero no siempre igual: depende del codebase. **¿Proyecto nuevo? TDD desde el minuto uno.** En greenfield uso `/tdd`, la skill de Matt. Red, green, refactor. Sin dramas. Primero el test. Que falle. Luego el mínimo código para que pase. Luego limpiar. Y otra vez, hasta cerrar el comportamiento. Con agentes esto funciona de maravilla porque les das una diana. Ya no están "implementando una idea": están intentando pasar un test concreto. Y eso recorta muchísimo la tentación de inventarse scope, montar abstracciones raras o tocar cosas que nadie pidió. Un test en rojo es la conversación más clara del mundo: esto todavía no funciona, arréglalo. **¿Codebase grande y heredado? No fuerzo TDD.** Aquí me bajo del púlpito. En una app legacy grande, meter TDD a mitad de feature es más teatro que ingeniería. Los límites no están claros, los mocks son una selva, el harness de tests parece construido por una civilización perdida... y acabas peleándote más con la infraestructura que entregando valor. Así que en brownfield implemento de forma más directa. Pero no lo dejo pasar sin control: ahí entra `/thermo-nuclear-code-quality-review`. El nombre es ridículo. También es bastante exacto. Es una pasada agresiva de calidad sobre lo recién escrito. Busca simplificaciones, duplicación, nombres flojos, código que parece funcionar pero huele raro, casos sin cubrir, complejidad accidental. Es como pedirle al agente que deje de ser el autor y se convierta, durante diez minutos, en el reviewer más insoportable del equipo. Y en legacy eso compensa un montón. No siempre puedo construir con TDD desde el principio, pero sí puedo obligar al resultado a pasar una revisión dura antes de darlo por bueno. Mi regla queda así: **greenfield, TDD; brownfield, implementación normal + revisión nuclear.** El objetivo es el mismo: que el código final sea algo que yo firmaría en una PR sin mirar al suelo. ## 5. `/setup-matt-pocock-skills`: un `AGENTS.md` mínimo y un `CLAUDE.md` que solo apunta a él La última skill no construye features. Construye el entorno para que las otras cuatro funcionen mejor. `setup-matt-pocock-skills` instala el kit. Pero lo que de verdad me importa es con qué la combino: una limpieza seria de las instrucciones del proyecto. Antes tenía, en cada proyecto, un `CLAUDE.md` gigante. El clásico: empiezas con cuatro reglas útiles, luego una convención, luego una excepción, luego "acuérdate de no tocar esto", luego "cuando trabajes en tests, haz aquello". Tres meses después tienes un documento que parece la Constitución de un país con demasiados microservicios. El agente lo escanea y pierde detalles. Las reglas importantes quedan enterradas bajo el ruido. La solución fue quitarle épica al asunto. Ahora las instrucciones de verdad viven en un `AGENTS.md` deliberadamente pequeño: el estándar que ya entienden varias herramientas, lo bastante corto como para que el agente se lo lea entero. Y el `CLAUDE.md` se queda casi en un puntero: ve y lee `AGENTS.md`. Así evito repetir reglas, gastar tokens en instrucciones duplicadas y mantener versiones que se contradicen. El [repositorio de skills de Matt Pocock](https://github.com/mattpocock/skills) es un punto de partida para montar tu propio flujo. Elige el orden de las skills según tu proyecto y déjalo escrito en sus instrucciones. **Lectura relacionada:** estas skills se disfrutan más en un proyecto real. Aquí tienes [cómo construí ga4-manager para automatizar Google Analytics](/blog/ga4-manager-automatiza-google-analytics/), uno de los codebases sobre los que corre este pipeline. --- **P.D.** Si has montado tu propio pipeline de skills, quiero verlo. ¿Qué has codificado que a mí me falta? Escríbeme en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/deja-de-promptear-escribe-loops/ Lang: es # Loops en Claude Code: deja de promptear a tu agente > Boris Cherny dice que su trabajo ya no es promptear, sino escribir loops: agentes que promptean agentes. Qué significa, cómo montar uno hoy y dónde se rompe. **Respuesta corta:** escribir loops es dejar de ser tú quien promptea al agente y escribir lo que lo hace por ti: un programa o un agente que se lanza solo con un cron, encuentra el trabajo, le pasa cada trozo a un agente, revisa lo que devuelve y decide qué toca después. El más pequeño que merece la pena montar esta semana: un agente programado que se despierta cada mañana, lee todas las issues abiertas desde ayer, las etiqueta, prepara un repro y te señala las dos o tres que necesitan que las mires tú. La última vez escribí sobre codificar mi proceso como [agent skills](/blog/agent-skills-flujo-codigo/) - darle vueltas a la idea, escribir el PRD, cortarla en slices, construirla, mantener las instrucciones limpias. Pensaba que eso era lo más alto de la escalera. Luego vi a Boris Cherny, el responsable de Claude Code, describir el escalón de encima, y me di cuenta de que solo había subido la mitad. Su frase, en el escenario de _Acquired Unplugged_, más o menos así: hace un año escribía código con autocompletado. Luego tenía cinco o diez Claudes corriendo en paralelo, y su "programar" era promptear a cada uno. ¿Y ahora? _"Ya no prompteo a Claude. Tengo loops corriendo. Ellos son los que promptean a Claude y deciden qué hacer. Mi trabajo es escribir loops."_ Léelo otra vez. La unidad de trabajo pasó de la tecla, al prompt, al **loop**. ## ¿En qué escalón de la escalera de abstracción estás? Boris describe programar como una sola subida larga: tarjetas perforadas, luego ensamblador, luego C, luego los lenguajes de alto nivel, luego los de altísimo nivel. "El nivel de abstracción siempre sube." Promptear a un agente es solo el siguiente escalón. Y también lo es el de después. ¿Dónde estamos casi todos ahora mismo? Escalón dos. Prompteamos. Como mucho lanzamos un par de agentes a la vez y nos sentimos a la última. El salto que describe Boris es el escalón tres: **dejas de ser el que promptea.** Construyes el que promptea, y es él quien decide en qué trabajar, despacha a los agentes y revisa los resultados sin que tú toques una tecla. Es el paso de **human _in_ the loop** (tú apruebas cada paso) a **human _on_ the loop**: diseñas el sistema y lo supervisas desde fuera, en vez de sentarte dentro de cada iteración. Suena a ciencia ficción hasta que te das cuenta de que las piezas ya existen. Y no, esto no es solo cron de toda la vida con una capa de IA por encima. Llevamos veinte años programando scripts a una hora fija, pero un script hace exactamente lo que escribiste, mientras que el agente dentro de este loop lee todo tu codebase y decide por su cuenta en qué trabajar. Ese es el cambio entero. El horario es trivial y siempre lo fue; el trabajo está en la puerta que le pones a lo que el agente te devuelve. ## ¿Qué es un loop? Orquestación, no magia Quítale el misterio, y pártelo en dos. El **harness** es el equipamiento: las herramientas, skills y MCPs que le das a un agente para que pueda hacer el trabajo de verdad. El **loop** es la orquestación que lo rodea: averigua qué trabajo hay → le pasa un trozo a un agente → revisa lo que vuelve → repite, y decide cuándo se lanza, cuándo avanza, cuándo para. El harness es lo que el agente _puede_ hacer; el loop es _cuándo y con qué frecuencia_ lo hace. No escribes el código. Ni siquiera escribes los prompts. Escribes lo que escribe los prompts. En Claude Code, hoy, eso no es una metáfora. Son tres piezas reales: - **Workflow scripts**: código determinista que reparte el trabajo entre muchos subagentes (en paralelo, pasando cada elemento por etapas, en bucle hasta vaciar una cola o agotar un presupuesto de tokens). Esto es, literalmente, un loop que promptea a Claude. - **Agentes en background y en paralelo**: lanzas una flota, cada uno en su slice, todos a la vez. - **Agentes programados / cron**: la parte que lo hace autónomo. Un agente que se despierta según un horario, lee tus issues de GitHub, tu feedback, tu Slack, y actúa. Eso último es exactamente lo que Boris contaba que tenía corriendo a escala: _"un par de cientos de Claudes corriendo… mirando feedback de Twitter, issues de GitHub, Slack. Están decidiendo qué construir a continuación."_ No necesitas cien. El loop más pequeño y real que puedes montar esta semana: un agente programado (cron) que se despierta una vez cada mañana, coge cada issue abierta desde ayer y ejecuta una sola instrucción sobre cada una. Léela, contrástala con el codebase, etiquétala, redacta un repro y marca las dos o tres que merecen tu tiempo. Es un único agente programado con un archivo de skill y un techo de tokens, no una flota. Eso es el escalón tres, hoy, con un solo agente. Lees lo que saca antes de fiarte, y a partir de ahí escalas. Este es ese loop como script. Cron lo lanza cada mañana desde tu repo; `gh` encuentra el trabajo, Claude Code en modo headless (`claude -p`) hace cada trozo, y una etiqueta lo marca como hecho para que la pasada de mañana se lo salte: ```bash #!/usr/bin/env bash # triage.sh, desde cron: 0 7 * * * cd ~/code/mi-app && ./triage.sh set -euo pipefail for n in $(gh issue list --search "-label:triaged" --json number --jq '.[].number'); do claude -p "Haz el triage de la issue #$n de GitHub. Léela con gh issue view, contrástala con este codebase \ y deja un único comentario: causa probable, un repro mínimo si puedes escribirlo, y P1, P2 o P3. \ No cambies código." \ --allowedTools "Read" "Grep" "Glob" "Bash(gh issue view:*)" "Bash(gh issue comment:*)" \ --max-budget-usd 0.50 < /dev/null gh issue edit "$n" --add-label triaged done ``` Tres líneas cargan con todo. La lista de `--allowedTools` deja al agente leer código y comentar, nada más. `--max-budget-usd` es la condición de parada por issue. Y la revisión eres tú, leyendo los comentarios con el café, hasta que el loop se gane que le prestes menos atención. ## Por qué las skills son el requisito previo (esto es la secuela, al fin y al cabo) Aquí está la parte que la gente se salta, y es la razón entera por la que escribí primero el [post de las skills](/blog/agent-skills-flujo-codigo/). **No puedes automatizar de forma segura la invocación de un proceso que no has codificado.** Un loop no hace listo a un agente. Lo hace **frecuente**. Si los agentes dentro de tu loop no siguen un proceso de verdad (darle vueltas a la idea, cortarla en vertical, construir con disciplina, obedecer un `AGENTS.md` mínimo), entonces un loop solo genera basura más rápido. Un chorro de cosas plausibles pero equivocadas. Y los prompts que dispara el loop siguen teniendo que ser buenos. Los [fundamentos para escribir un prompt afilado](/blog/consejos-ingenieria-prompts-ai/) no dejan de importar porque los teclee un script en vez de ti. Las skills son lo que convierte un loop de máquina de slop en un proceso que se ejecuta solo. Boris dijo lo mismo, casi de pasada: las empresas tienen "documentos de principios" para no tomar las mismas decisiones una y otra vez, y _"el modelo también puede usar esos principios, y vienen en forma de skills."_ El escalón dos (skills) no es un paso que te puedas saltar para llegar al escalón tres (loops). Es el muro de carga. ## La parte honesta: la mayoría de lo que escupe un loop es malo No te voy a vender el sueño sin el asterisco. Boris, hablando de sus cientos de agentes buscando qué construir: _"la mayoría de las ideas son malas, pero quizá un 20% son buenas."_ Un veinte por ciento. Lo dice quien construyó la herramienta. Y el propio ensayo de Anthropic sobre [auto-mejora recursiva](https://www.anthropic.com/institute/recursive-self-improvement) llega al mismo cuello de botella por el lado opuesto. Su descripción de la trayectoria (humanos escribiendo código, luego agentes escribiendo archivos enteros, luego agentes pasándole horas de trabajo a otros agentes) suena triunfal hasta que llegas a la trampa: **la revisión humana se ha convertido en el cuello de botella.** La ejecución se abarató. El criterio no. Así que un loop sin filtro es un lastre, no una palanca. Lo que hace los loops soportables es la puerta a la salida: una revisión adversarial, un control de calidad duro, tests que de verdad fallen. El loop genera; _algo_ tiene que hacer de portero. Si el 80% es basura, tu ventaja es la velocidad y la calidad de tu "no". Y hay un segundo contador en marcha: el dinero. Un loop que despacha subagentes encadenados mientras duermes no solo produce slop, te lo factura. Cada iteración sin supervisión gasta tokens valga o no la pena lo que sale, así que un techo de tokens y una condición de parada no son un extra: son parte del harness. Ponle un tope duro (con cinco euros o veinte iteraciones por noche te sobra para empezar), y haz que pare y te avise al llegar, en vez de seguir a ciegas. Decide ambos antes de dejar uno corriendo solo. ## Hacia dónde va esto (y por qué no es solo hype) Aleja el plano y el "yo escribo loops" de Boris es la foto a escala personal de lo que Anthropic sostiene que le está pasando a todo el sector. Su ensayo dibuja un futuro donde la IA automatiza cada vez más el propio desarrollo de IA, y el rol humano se comprime hacia una sola cosa: **dirección y criterio.** Elegir qué merece la pena hacer. Distinguir un buen resultado de uno malo. Yo cogería los números concretos con pinzas, y para ser justos, ellos también. Reconocen abiertamente que las líneas de código son una métrica mala, que las mejoras que ellos mismos reportan probablemente están infladas, y que si los modelos de hoy pueden desarrollar verdadero _gusto_ investigador por su cuenta es, en sus palabras, genuinamente incierto. Esa honestidad es justo por lo que merece leerse: optimista con la trayectoria, sincero con la incertidumbre. La dirección es real aunque las fechas no lo sean. ## Lo que sigue siendo tuyo Esto es lo que la escalera te está diciendo en voz baja. Cada escalón que subes, tu ventaja deja de ser lo de debajo. Dejó de ser "sé escribir el código". Está a punto de dejar de ser "sé escribir el prompt". Lo que queda, arriba del todo, es lo que no se automatiza: decidir qué merece la pena construir, juzgar lo que vuelve, y los valores que metes en el sistema que corre mientras duermes. A Boris le preguntaron cuál será la última habilidad solo-humana. Su respuesta: _"lo último que le enseñaremos al modelo son valores. Igual que enseñamos a nuestros hijos a ser buenas personas, le enseñaremos al modelo a ser un buen modelo."_ Así que no romantices los loops. Monta uno. Codifica tu proceso como skills primero, envuélvelo en un loop pequeño, y pon una puerta de revisión brutal a lo que produzca. Esa es la jugada entera: el escalón tres no necesita cien agentes. Necesita **un buen loop y tu criterio al otro lado.** Ya tienes la versión más pequeña unos párrafos más arriba. Esta noche, apunta un agente programado a una sola etiqueta de issues, ponle un techo de tokens, y por la mañana lee lo que ha redactado antes de creerte una palabra. Eso es el escalón tres, esta semana, vigilado. A partir de ahí amplías, cuando se haya ganado tu confianza. **Lectura relacionada:** esto solo funciona si el proceso de debajo es sólido. Empieza por [las cinco agent skills que gobiernan todo mi flujo](/blog/agent-skills-flujo-codigo/), y luego envuélvelas en un loop. Y qué modelo pones en el loop también cuenta: desgrané el que ahora elijo en [mi reseña de Claude Fable 5](/blog/claude-fable-5-resena/). ## Fuentes - Boris Cherny (responsable de Claude Code), _Acquired Unplugged_: la frase "yo escribo loops" y el "la mayoría de las ideas son malas, ~20% buenas", vía [el clip de @codingvic en X](https://x.com/codingvic/status/2062487626779636001). - Anthropic, [_Recursive self-improvement_](https://www.anthropic.com/institute/recursive-self-improvement): el marco a escala de empresa y los matices. --- **P.D.** ¿Montando loops en serio? Quiero saber qué has automatizado y qué te explotó en la cara. Escríbeme en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/ga4-manager-automate-google-analytics/ Lang: en # I Automated GA4 with YAML. Now It Flags What to Check in SEO > A CLI + MCP server that configures GA4 and Search Console from YAML, and flags what to check in your SEO by impact. Deterministic: you make the calls. **Short answer:** GA4 Manager is my open-source Go CLI and MCP server. One YAML file sets up GA4 and Search Console, then it runs deterministic Search Console checks: CTR gaps ranked by the clicks they cost you, cannibalization, index health, hreflang and URL hygiene. No model guesses at SEO: the checks are API queries, and what to change is my call. I started building this so I'd stop losing 40 minutes clicking through the GA4 UI every time I spun up a project. What I didn't expect was where it ended up: now the tool doesn't just configure analytics, it **flags** what to look at in my SEO, ranked by how many clicks it's costing me. It doesn't decide for me. It puts the data in front of me, prioritized, and I pick what to touch. That distinction is the whole point, and I'll come back to it. This is the story of how it happened, what it does now, and what came out when I pointed the full suite at this very blog, including the moment the tool got it wrong (and why that gave me *more* confidence, not less), and the second run four months later that was a lot less flattering. ## The original problem: clicking like a monkey I have several side projects. This portfolio, [WealthSim](https://wealthsim.app), and a few smaller ones. Each needs analytics, and every time I spun up a new one the ritual was the same: create the GA4 property (easy), then click. Conversions, ten clicks each. Dimensions, more clicks. Metrics, more. Data retention, where was that option again? Enhanced measurement, another menu. **Thirty or forty minutes of repetitive clicking.** And the worst part: if I wanted the same config on another project, I'd repeat it all from scratch. GA4 has no "export configuration." No way to copy setup between properties. After configuring the third project in one week, I thought what you're thinking right now: *this is exactly the kind of work that should be automated.* ## The premise: analytics as code I define my infra as code. My CI/CD as code. Why not my analytics? That was the whole idea. A YAML file that describes how I want GA4, and one command to apply it: ```yaml project: name: "My Project" ga4: property_id: "123456789" tier: standard conversions: - name: newsletter_signup counting_method: ONCE_PER_SESSION dimensions: - parameter: article_category scope: EVENT ``` ```bash ga4 setup --config my-project.yaml ``` Boom. Config applied. No clicks, no typos, versioned in git next to your code. From 40 minutes to under one. That was [GA4 Manager](https://github.com/garbarok/ga4-manager) v1. ## The turn: it stopped showing me data and started pointing at what to check This is where the tool got genuinely interesting. The first half of its life was **configuration**: apply this YAML, create these conversions, submit this sitemap. Useful, but passive. The second half, the part that actually changed how I work, is **diagnostics**. Back in June, on v2.3.1, the MCP server exposed 20 tools (40 as of v3.4.0), and the newest ones don't show you data: they tell you where to start. The one I use most is **`gsc_opportunities`**. It finds queries where you already rank on page 1-2 (position 5-20) but with a CTR below the median for that bucket, and sorts them by `potential_clicks`: the extra monthly clicks you'd gain just by hitting the median CTR. Biggest wins first. On this blog? It found exactly one. And at position ~18, page two, where a title tweak won't move it. The tool didn't inflate it: it told me the truth, that there was no gold mine here. On a site with real traffic, this is the tool that buys you coffee; on a small one, it confirms there are no shortcuts. Both answers work for me. The other three in the new group follow the same "what first" philosophy: - **`gsc_cannibalization`**: queries where two or more of your pages split impressions and eat each other's authority; it points at the canonical candidate. - **`gsc_ctr_anomaly`**: (query, page) pairs where position barely moved but CTR collapsed. Translation: your snippet stopped converting. Rewrite it. - **`gsc_health`**: an indexing report that diffs each URL's state against the prior snapshot, so an accidental `noindex` surfaces in days, not weeks. Silent when everything's green. Built for a cron. And here's what, for me, separates this from the pile: **none of it is the AI guessing at SEO.** These are deterministic queries against the Search Console API (a Go CLI, structured output). The LLM only orchestrates the calls and summarizes the result; the interpretation and the "yes-this, no-that" are mine. If vibe coding gives you hives (it does me), that's exactly the line that matters: the tool surfaces, you judge. ## What happened when I pointed it at this blog This blog is one of my side projects and runs on a site that uses GA4 Manager via MCP, so in June I sat down with Claude and pointed the full suite at `oscargallegoruiz.com`. I expected to find disasters. Reality was more boring, and more interesting than it sounds. 43 of 43 pages indexed. `gsc_ctr_anomaly`: empty. `seo_page_audit` on the top pages: clean, zero errors. In short: the site was healthy. And a tool telling you "everything's fine" instead of inventing a problem to justify itself is a signal I trust. But there was a scare. `gsc_sitemaps_list` returned an *empty* list, as if I'd never submitted the sitemap. The easy reflex would've been to resubmit it and move on. Instead I verified with `gsc_sitemaps_get`… and there it was, submitted and downloaded by Google, no problem. **The empty list was a bug in my own tool, not an SEO failure.** And that's the moral I care about, the one that ties back to everything above: *I didn't trust the output blindly.* If I'd acted on the false positive, I'd have "fixed" something that wasn't broken. Verifying saved me the embarrassment, and along the way, the tool I wrote to catch problems caught a bug in itself. I fixed it. That's the healthy relationship with a tool like this: it gives you leads, you confirm them. The one I never trust is the one that promises you don't need to confirm anything. ## Four months later, the blog was visible, churning and uncited In October I ran it again, with everything that's now in v3.4.0, including a batch of DataForSEO tools. June's verdict was "healthy". October's was less flattering, and it stung more than the sitemap scare did: - **`site_growth_brief`** (28 days, Sep 6 to Oct 3): 6,012 impressions, 20 clicks, 0.33% CTR at an average position of 7.6. The blog shows up; almost nobody clicks. Most impressions on the top pages came from long queries ending in things like "answer with sources". GSC doesn't label them, but that shape looks to me like AI search fanning out a question. - **`llm_mentions`** (DataForSEO): 0 citations in Google's AI answers for 5 queries the blog already ranks for, at $0.58 in credit. The answers cited YouTube, Reddit and the official docs. Five queries is a smoke test, not a study. - **`gsc_health`** over 40 priority URLs: 8 flagged as regressions. Five URLs (four posts; TypeScript in both languages) dropped from indexed to "Crawled - currently not indexed", the English content-config post became "URL is unknown to Google", and two were canonical-field changes. One of those was a post that actually went from "Discovered" to indexed, which my tool filed as a regression. Gaining a canonical is what indexing looks like, so that's fixed now. Meanwhile, five URLs that weren't indexed in June now are. - **`gsc_hreflang`** and **`gsc_cannibalization`**: clean. So June's "healthy" was half right. The URL Inspection snapshot I saved at the end of June already had six priority URLs out of the index, so the 43 of 43 was either a coarser check or stale within weeks. Indexing churns, and a one-off audit only tells you about the day you ran it, and only as well as the check you used. What I did with it: 1. **Merged** the content-config post (both languages were out of the index) into my Astro 6 guide, with 301s from every old URL. 2. **Refreshed** the other three with new first-hand content: the TypeScript post got an audit of this repo's `tsconfig`, the Vercel tests post the exact error up front, and this one the section you're reading. 3. **Rewrote the openings** of the posts that rank, so each starts with a short answer that leads with the number, like the one at the top of this post. That's a bet, not a result: I don't know yet whether it moves `llm_mentions` off zero. Nothing here is verified yet. The same five queries and the indexing check run again on November 4, and I'll put the numbers in this post even if they're still zero. The check worth stealing is the boring one. The MCP call timed out at 30 seconds on 40 URLs, so I ran the CLI directly. That one's fixed too: the inspections now run five at a time (54 seconds for 38 URLs instead of about four and a half minutes) and the MCP waits up to five minutes for this tool. Both fixes shipped in v3.4.0. The CLI is still the command I'd start with: ```bash ga4 gsc health --config configs/your-site.yaml --format json ``` Exit code 0 means no regressions (recoveries and first-run baselines don't count), 2 means at least one URL regressed, and 1 means the run itself failed. The first run only records a baseline; the diff starts on the second. List your top 30 URLs under `priority_urls` and put it on a weekly cron. ## What I learned building this **Google has two GA4 APIs.** The Data API (query data) and the Admin API (configure). GA4 Manager uses the Admin one, which is `v1alpha`. Yes, alpha. Some endpoints change without warning, and certain metric types (like CURRENCY) have poorly documented restrictions. You find out the hard way. **The limits are real and it validates them before touching anything.** On the free tier: 30 conversions, 50 dimensions, 50 metrics. If you're close, it warns you before you eat a 400 from the API. **Parameter names are forever.** Once you create a dimension or metric, the parameter name is permanently reserved. Even if you archive it. My fix is ugly but works: version the names (`reading_time_v3`). ## Use it from your assistant (MCP) The piece that changed everything was the MCP server. It exposes every tool to Claude Desktop, Claude CLI, VS Code, Cursor, and Cline, so I can say in plain language: > "Compare last week's traffic to the prior week, audit the homepage and the worst-ranking post, and tell me what to check." And Claude orchestrates the calls and stitches the results together. But same principle as always: it hands me a prioritized list, not a `git push`. The decisions stay mine. And here's the connection that's got me hooked: `gsc_health` is **built for a cron**. Which means it's not just a tool I invoke, but a [loop I can leave running](/en/blog/stop-prompting-write-loops/): an agent that checks indexing every Monday, compares traffic, and only bothers me if something broke. That's the next rung. You stop asking and build the loop that asks for you. Had it been on a cron since June, those regressions would have reached me the week they happened, not four months later. ## What it does NOT do (let's be honest) - **Audiences:** the tool doesn't create them. It generates the docs so you can build them by hand in the UI (the Admin API can create audiences; I just haven't wired that into the tool yet). - **BigQuery linking:** automated. `ga4 link --service bigquery` creates the export link through the Admin API. - **Search Console linking:** manual. The tool prints a setup guide; you finish the link in the UI. - **Historical data:** this configures GA4, it doesn't migrate data. Collection starts after setup. ## Install: one script ```bash git clone https://github.com/garbarok/ga4-manager.git cd ga4-manager ./scripts/setup.sh ``` The script verifies prerequisites (`gcloud`, `jq`, `curl`), picks the auth path with you (ADC for personal use, service-account key for CI), enables the required APIs, smoke-tests every endpoint, and prints which manual permissions you still need. It's idempotent: rerun it without fear. If you have a couple of side projects you rarely touch, you probably don't need it. If you run three or more and you're sick of clicking the same UI for the hundredth time: [try it](https://github.com/garbarok/ga4-manager), star it if it helps, and open an issue if something breaks (or if you find another bug like the sitemap-list one). **Related reading:** why `gsc_health` on a cron is the natural next step: [stop prompting your agent, start writing loops](/en/blog/stop-prompting-write-loops/). ## Sources - [GA4 Manager on GitHub](https://github.com/garbarok/ga4-manager) - [Google Analytics Admin API](https://developers.google.com/analytics/devguides/config/admin/v1) - [Search Console API](https://developers.google.com/webmaster-tools) **Case study:** the [GA4 Manager case study](/en/projects/ga4-manager/) covers the problem, the decisions and what went wrong in the tool. --- **P.S.** If you try it, tell me what it found on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). Now if you'll excuse me, I've got a cron to set up. ## FAQ **Is it free?** Yes, open source under the MIT license on GitHub (garbarok/ga4-manager). **Do I need to know Go?** No. Download the prebuilt binary and write your configuration in YAML. **Can it delete my data?** No. It only uses the Admin API for configuration and cannot touch your historical analytics data. Worst case is creating or deleting config resources, which you can always recreate, and `--dry-run` lets you preview everything before applying. **Do the SEO audits need a paid API key?** Everything built on Search Console is free. The DataForSEO tools (keyword research, backlinks and `llm_mentions`) spend credit from your own DataForSEO account. Otherwise you only need a free PageSpeed Insights key if you want Core Web Vitals inside `seo_page_audit` with normal quota. **What is the difference between `gsc_analytics_run` and `gsc_traffic_compare`?** The first is a snapshot of one period (top queries, pages, CTR, position). The second compares two periods and gives you URL-level drops and gains: one to see what you have, the other to see what changed. --- URL: https://www.oscargallegoruiz.com/blog/ga4-manager-automatiza-google-analytics/ Lang: es # Automaticé GA4 con YAML. Ahora Me Señala Qué Revisar en SEO. > Una CLI + servidor MCP que configura GA4 y Search Console desde YAML, y señala qué revisar en tu SEO por impacto. Determinista: las decisiones las tomas tú. **Respuesta corta:** GA4 Manager es mi CLI en Go y servidor MCP de código abierto. Un YAML configura GA4 y Search Console, y después lanza comprobaciones deterministas sobre Search Console: huecos de CTR ordenados por los clics que te cuestan, canibalización, estado de indexación, hreflang y URLs que no deberían salir en Google. Aquí no hay ninguna IA adivinando: son consultas a la API, y qué tocar lo decido yo. Empecé a construir esto para no perder 40 minutos clicando en la UI de GA4 cada vez que arrancaba un proyecto. Lo que no esperaba es dónde acabaría: ahora la herramienta no solo configura analytics, me **señala** qué mirar en mi SEO, ordenado por cuántos clics me está costando. No decide por mí. Me pone los datos delante, priorizados, y yo elijo qué tocar. En esa distinción está la clave, y vuelvo a ella más abajo. Esta es la historia de cómo pasó, qué hace hoy, y qué salió cuando le solté la suite entera a este mismo blog, incluido el momento en que la herramienta se equivocó (y por qué eso me dio *más* confianza, no menos), y la segunda pasada, cuatro meses después, en la que el blog salió bastante peor parado. ## El problema original: clicar como un mono Tengo varios side projects. Este portfolio, [WealthSim](https://wealthsim.app), y unos cuantos más pequeños. Cada uno necesita analytics, y cada vez que arrancaba uno nuevo el ritual era el mismo: crear la propiedad GA4 (fácil), y luego clicar. Conversiones, diez clics cada una. Dimensiones, más clics. Métricas, más. Retención de datos, ¿dónde estaba eso? Enhanced measurement, otro menú. **Treinta o cuarenta minutos de clics repetitivos.** Y lo peor: si quería la misma config en otro proyecto, a repetirlo todo desde cero. GA4 no tiene "exportar configuración". No puedes copiar setup entre propiedades. Después de configurar el tercer proyecto en una semana pensé lo que piensas tú ahora: *esto es exactamente el tipo de trabajo que debería automatizarse.* ## La premisa: analytics as code Defino mi infra como código. Mi CI/CD como código. ¿Por qué no mi analytics? Esa fue toda la idea. Un YAML que describe cómo quiero GA4, y un comando que lo aplica: ```yaml project: name: "Mi Proyecto" ga4: property_id: "123456789" tier: standard conversions: - name: newsletter_signup counting_method: ONCE_PER_SESSION dimensions: - parameter: article_category scope: EVENT ``` ```bash ga4 setup --config mi-proyecto.yaml ``` Boom. Config aplicada. Sin clics, sin typos, versionable en git junto a tu código. De 40 minutos a menos de uno. Eso fue [GA4 Manager](https://github.com/garbarok/ga4-manager) v1. ## El giro: dejó de enseñarme datos y empezó a señalarme dónde mirar Aquí es donde la herramienta se volvió interesante de verdad. La primera mitad de su vida fue **configuración**: aplica este YAML, crea estas conversiones, envía este sitemap. Útil, pero pasivo. La segunda mitad, lo que de verdad cambió cómo trabajo, es **diagnóstico**. En junio, en la v2.3.1, el servidor MCP exponía 20 herramientas (40 desde la v3.4.0), y las más nuevas no te enseñan datos: te dicen por dónde empezar. La que más uso es **`gsc_opportunities`**. Busca queries donde ya estás en página 1-2 (posición 5-20) pero con un CTR por debajo de la mediana de su franja, y las ordena por `potential_clicks`: los clics extra al mes que ganarías solo con llegar al CTR mediano. Las mayores ganancias primero. ¿En este blog? Encontró exactamente una. Y encima en posición ~18, página 2, donde un retoque de title no la mueve. La herramienta no la infló: me dijo la verdad, que aquí no había una mina de oro. En un sitio con tráfico de verdad, esta es la tool que te paga el café; en uno pequeño, te confirma que no hay atajos. Las dos respuestas me valen. Las otras tres del grupo nuevo siguen la misma filosofía de "qué primero": - **`gsc_cannibalization`**: queries donde dos o más páginas tuyas se reparten impresiones y se comen la autoridad entre ellas; te señala la candidata a canónica. - **`gsc_ctr_anomaly`**: pares (query, página) donde la posición casi no se movió pero el CTR se desplomó. Traducción: tu snippet dejó de convertir. A reescribir. - **`gsc_health`**: informe de indexación que diffea el estado de cada URL contra el snapshot anterior, así un `noindex` accidental sale en días, no en semanas. Silencioso si todo está verde. Pensado para un cron. Y algo que para mí es lo que separa esto del montón: **nada de esto es la IA adivinando SEO.** Son queries deterministas contra la API de Search Console (un CLI en Go, output estructurado). El LLM solo orquesta las llamadas y me resume el resultado; la interpretación y el "esto sí, esto no" son míos. Si te da urticaria el vibe coding (a mí me la da), esa es justo la línea que importa: la herramienta saca, tú juzgas. ## Qué pasó cuando lo solté sobre este blog Este blog es uno de mis side projects y corre sobre un sitio que usa GA4 Manager vía MCP, así que en junio me senté con Claude y le solté la suite entera sobre `oscargallegoruiz.com`. Esperaba encontrar desastres. La realidad fue más aburrida, y más interesante de lo que parece. 43 de 43 páginas indexadas. `gsc_ctr_anomaly`: vacío. `seo_page_audit` en las páginas top: limpias, cero errores. En resumen: el sitio estaba sano. Y que una herramienta te diga "está todo bien" en vez de inventarte un problema para justificarse ya es una señal de la que me fío. Pero hubo un susto. `gsc_sitemaps_list` me devolvió una lista *vacía*, como si nunca hubiera enviado el sitemap. El reflejo fácil habría sido reenviarlo y pasar página. En vez de eso lo verifiqué con `gsc_sitemaps_get`… y ahí estaba, enviado y descargado por Google sin problema. **La lista vacía era un bug en mi propia herramienta, no un fallo de SEO.** Y esa es la moraleja que me importa, la que conecta con todo lo de arriba: *no me fié del output a ciegas.* Si llego a actuar sobre el falso positivo, habría "arreglado" algo que no estaba roto. Verificar me ahorró el ridículo y, de paso, la herramienta que escribí para cazar problemas me cazó un bug en sí misma. Lo arreglé. Esa es la relación sana con un tool así: te da pistas, tú las confirmas. De la que no me fío nunca es de la que te promete que no hace falta confirmar nada. ## Cuatro meses después: el blog salía en Google, entraba y salía del índice y nadie lo citaba En octubre la volví a lanzar contra el blog, con todo lo que ya está en la v3.4.0, incluido un lote de herramientas de DataForSEO. En junio el veredicto fue "está sano". El de octubre fue menos amable, y me escoció más que el susto del sitemap: - **`site_growth_brief`** (28 días, del 6 de septiembre al 3 de octubre): 6.012 impresiones, 20 clics, 0,33% de CTR con una posición media de 7,6. El blog sale, pero casi nadie hace clic. Casi todas las impresiones de los posts que más salen venían de búsquedas larguísimas que acababan en cosas como "answer with sources". Search Console no las marca, pero a mí esa pinta me suena a buscador con IA desmenuzando una pregunta. - **`llm_mentions`** (DataForSEO): 0 citas en las respuestas de IA de Google para 5 búsquedas en las que el blog ya posiciona, por 0,58 $ de crédito. Las respuestas citaban YouTube, Reddit y la documentación oficial. Cinco búsquedas son una prueba rápida, no un estudio. - **`gsc_health`** sobre 40 URLs prioritarias: 8 marcadas como regresión. Cinco URLs (cuatro posts; el de TypeScript en los dos idiomas) pasaron de indexadas a "Crawled - currently not indexed", el post de content-config en inglés pasó a "URL is unknown to Google", y dos eran cambios en el campo canonical. Uno de esos dos era un post que en realidad pasó de "Discovered" a indexado, y mi herramienta lo apuntó como regresión. Ganar un canonical es justo lo que pasa cuando una página se indexa, así que eso ya está arreglado. Mientras tanto, cinco URLs que en junio no estaban indexadas ahora sí lo están. - **`gsc_hreflang`** y **`gsc_cannibalization`**: limpios. Así que el "está sano" de junio era verdad a medias. La inspección de URLs que guardé a finales de junio ya tenía seis URLs prioritarias fuera del índice, así que el 43 de 43 o salía de una comprobación más gruesa o se quedó viejo en semanas. La indexación se mueve, y una auditoría puntual solo te cuenta cómo estaba el día que la lanzaste, y con la fiabilidad de la comprobación que usaste. Lo que hice con eso: 1. **Fusioné** el post de content-config (las dos versiones estaban fuera del índice) con mi guía de Astro 6, con 301 desde todas las URLs viejas. 2. **Actualicé** los otros tres con contenido propio nuevo: el de TypeScript, con una auditoría del `tsconfig` de este repo; el de los tests en Vercel, con el error exacto al principio; y este, con la sección que estás leyendo. 3. **Reescribí el arranque** de los posts que posicionan para que cada uno empiece con una respuesta corta que va directa al número, como la de arriba de este post. Es una apuesta, no un resultado: todavía no sé si saca a `llm_mentions` del cero. Nada de esto está comprobado todavía. El 4 de noviembre vuelvo a lanzar las mismas cinco búsquedas y la comprobación de indexación, y pondré los números en este post aunque sigan en cero. La comprobación que merece la pena copiar es la aburrida. A la llamada MCP le saltó el timeout a los 30 segundos con 40 URLs, así que ejecuté la CLI directamente. Eso también está arreglado: las inspecciones van ahora de cinco en cinco (54 segundos para 38 URLs en vez de unos cuatro minutos y medio) y el MCP espera hasta cinco minutos a esta herramienta. Los dos arreglos salieron en la v3.4.0. La CLI sigue siendo el comando por el que yo empezaría: ```bash ga4 gsc health --config configs/tu-sitio.yaml --format json ``` El código de salida 0 significa que no hay regresiones (las recuperaciones y la primera pasada, que solo guarda la foto inicial, no cuentan); el 2, que al menos una URL ha empeorado; el 1, que el comando ha fallado. Pon tus 30 URLs principales en `priority_urls` y mételo en un cron semanal. ## Lo que aprendí construyendo esto **Google tiene dos APIs de GA4.** La Data API (consultar datos) y la Admin API (configurar). GA4 Manager usa la Admin, que va en `v1alpha`. Sí, alpha. Algunos endpoints cambian sin avisar, y ciertos tipos de métrica (como CURRENCY) tienen restricciones mal documentadas. Te enteras por las malas. **Los límites son reales y los valida antes de tocar nada.** En el tier gratuito: 30 conversiones, 50 dimensiones, 50 métricas. Si te acercas, te avisa antes de comerte un 400 de la API. **Los nombres de parámetros son para siempre.** Una vez creas una dimensión o métrica, el nombre del parámetro queda reservado de forma permanente. Aunque la archives. Mi solución es fea pero funciona: versionar los nombres (`reading_time_v3`). ## Úsalo desde tu asistente (MCP) La pieza que lo cambió todo fue el servidor MCP. Expone todas las herramientas a Claude Desktop, Claude CLI, VS Code, Cursor y Cline, así que puedo decir en lenguaje normal: > "Compara el tráfico de la última semana vs la anterior, pasa una auditoría a la home y al post peor posicionado, y dime qué revisar." Y Claude orquesta las llamadas y junta los resultados. Pero ojo, mismo principio de siempre: me devuelve una lista priorizada, no un `git push`. Las decisiones siguen siendo mías. Y aquí está la conexión que me tiene enganchado: `gsc_health` está **hecho para un cron**. O sea, no es solo una tool que invoco, sino un [loop que puedo dejar corriendo](/blog/deja-de-promptear-escribe-loops/): un agente que cada lunes mira la indexación, compara el tráfico, y solo me molesta si algo se rompió. Ese es el siguiente escalón. Dejas de preguntar y montas el bucle que pregunta por ti. Si hubiera estado en un cron desde junio, esas regresiones me habrían llegado la semana en que pasaron, no cuatro meses después. ## Lo que NO hace (seamos honestos) - **Audiencias:** la herramienta no las crea. Genera la documentación para que las montes a mano en la UI (la Admin API sí permite crear audiencias; simplemente aún no lo he metido en la herramienta). - **BigQuery linking:** automatizado. `ga4 link --service bigquery` crea el enlace de exportación vía Admin API. - **Search Console linking:** manual. La herramienta imprime una guía de setup; el enlace lo terminas tú en la UI. - **Datos históricos:** esto configura GA4, no migra datos. La recolección empieza después del setup. ## Instalación: un solo script ```bash git clone https://github.com/garbarok/ga4-manager.git cd ga4-manager ./scripts/setup.sh ``` El script verifica prerequisitos (`gcloud`, `jq`, `curl`), elige contigo la ruta de auth (ADC para uso personal, service-account key para CI), activa las APIs necesarias, hace smoke-test de cada endpoint, y te imprime qué permisos manuales te quedan. Es idempotente: lo relanzas sin miedo. Si tienes un par de side projects que rara vez tocas, probablemente no lo necesitas. Si llevas tres o más y estás harto de clicar la misma UI por enésima vez: [pruébalo](https://github.com/garbarok/ga4-manager), dale una estrella si te sirve, y abre un issue si algo se rompe (o si encuentras otro bug como el de la lista de sitemaps). **Lectura relacionada:** por qué `gsc_health` en un cron es el siguiente paso natural: [deja de promptear a tu agente, escribe loops](/blog/deja-de-promptear-escribe-loops/). ## Fuentes - [GA4 Manager en GitHub](https://github.com/garbarok/ga4-manager) - [Google Analytics Admin API](https://developers.google.com/analytics/devguides/config/admin/v1) - [Search Console API](https://developers.google.com/webmaster-tools) **Caso práctico:** el [caso de GA4 Manager](/projects/ga4-manager/) recoge el problema, las decisiones y lo que falló en la herramienta. --- **P.D.** Si lo pruebas, cuéntame qué te encontró en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). Ahora, si me disculpas, tengo un cron que montar. ## FAQ **¿Es gratis?** Sí, es código abierto con licencia MIT en GitHub (garbarok/ga4-manager). **¿Necesito saber Go?** No. Bajas el binario precompilado y escribes la configuración en YAML. **¿Puede borrar mis datos?** No. Solo usa la Admin API para configuración; no toca tus datos históricos de analytics. Lo peor sería crear o borrar recursos de configuración, que siempre puedes recrear, y `--dry-run` permite previsualizar todo antes de aplicar. **¿Las auditorías SEO necesitan una API key de pago?** Todo lo que va sobre Search Console es gratis. Las herramientas de DataForSEO (investigación de keywords, backlinks y `llm_mentions`) gastan crédito de tu propia cuenta de DataForSEO. Fuera de eso, solo necesitas una key gratuita de PageSpeed Insights si quieres Core Web Vitals dentro de `seo_page_audit` sin límites de cuota. **¿Qué diferencia hay entre `gsc_analytics_run` y `gsc_traffic_compare`?** La primera es una foto de un periodo (top queries, páginas, CTR, posición). La segunda compara dos periodos y te da caídas y subidas por URL: una para ver lo que tienes, la otra para ver qué cambió. --- URL: https://www.oscargallegoruiz.com/en/blog/gemini-flash-code-review-automation/ Lang: en # Gemini Flash for Code Review: 3 Weeks on My Side Projects > Three weeks pairing Gemini Flash and Claude Code on side projects: AI writes many of my tests and I review all. What worked, what broke, what it costs. ## The short version, three weeks in The setup: solo developer, about 3 years of experience, Google One Pro (I was paying for the storage, it happens to bundle Gemini) plus Claude Code, on side projects. The results: a good share of my tests are now AI-generated but manually reviewed, features take less time than I'd have scoped (an impression, I did not time it), and the split that stuck is Claude Code for planning, Gemini Flash for execution. I still hit usage limits regularly. The catch: you review everything. AI makes mistakes, and this workflow only survives on personal projects where I can afford to catch my own bugs. Worth trying? If you're solo, building side projects, and hate repetitive code: yes. If you work on critical systems or can't review AI output carefully: no. --- ## Who am I to tell you this? I've been coding for about 3 years. Not a senior engineer. I don't manage a team. I don't work at FAANG. I'm a developer building side projects, trying to ship faster, and poking at AI coding tools to see if they actually help. So don't read this as a definitive guide or best practices from a 10x engineer. It's three weeks of trying things: what worked, what didn't, what surprised me. If you're in a similar spot (solo dev, side projects, limited time), maybe it saves you the experiment. ## Building solo is slow because the boring jobs are yours too When you work on side projects alone, everything lands on you: - Write all the code - Write all the tests (boring) - Handle all the styling (tedious) - Fix all the bugs - Review your own code (we all know how that goes) And honestly? Writing tests is repetitive. Tweaking Tailwind classes for hours numbs the brain. Catching my own bugs is hit-or-miss. I wanted my time on the interesting parts, building features and solving problems, not on the mechanical stuff. ## What I tried, with low expectations I'd heard people hyping AI coding tools and I was skeptical. "Probably overhyped," I thought. But I already had a Google One Pro subscription (for storage, not AI), which includes Gemini. And people kept talking about Claude Code. So: try it for a few weeks and see what happens. Worst case, I waste some time. Best case, I learn something useful. ### Why Gemini Flash specifically When Google released Gemini 3 Flash, everyone assumed it was the "lite" version of Pro. Faster but less smart. The usual trade-off. Except the benchmarks Google published said otherwise. According to the benchmarks Google published and Artificial Analysis' speed numbers (SWE-bench Verified, which tests AI on real GitHub issues from open-source projects), Flash scored above Pro, ran noticeably faster than the previous generation and cost quite a bit less per token. I have not verified those numbers myself, so I am not repeating them here: check [Google's pricing page](https://ai.google.dev/gemini-api/docs/pricing) if the detail matters to you. Weird enough to be worth testing. _(Note: I'm using Google One Pro, not the API, so I don't pay API rates. But I do hit usage limits regularly.)_ ## The combo that worked: Claude Code thinks, Gemini Flash types Here's the thing: I'm not using Gemini Flash alone. After a week of experimenting, this is the split that actually works for me. ### The hybrid workflow **1. Claude Code for planning and research.** - "Research the best way to test this React component" - "Give me an implementation plan for [feature]" - "What are the edge cases I should handle?" Claude Code takes longer but thinks thoroughly. Good for architectural decisions and planning. **2. Gemini Flash for execution.** - "Here's the plan Claude gave me. Implement it." - "Write tests for these functions following this approach" - "Style this component to match this design" Gemini Flash executes insanely fast. Sometimes it doesn't think enough, but that's what the plan is for. Separately? Meh. Together? Actually useful. ### Why the combo holds up Claude Code is slow but thorough, exactly what you want for architecture. Gemini Flash is fast but sometimes shallow, exactly what you want for implementing a plan that already exists. Claude Code: "Here's HOW we should solve this and WHY." Gemini Flash: "Got it, implementing now." **One tool plans, the other one types.** That division of labor feels more reliable than leaning on either tool alone. ## One real feature, step by step Here's how this plays out in practice, on my own portfolio. ### How I used to work Building a new blog feature: 1. Research best practices 2. Plan implementation 3. Write the code 4. Write tests (ugh) 5. Style with Tailwind 6. Fix bugs I did not time it: it took a good part of an afternoon. ### Same feature, with the combo 1. **Ask Claude Code:** ``` "I want to add a reading progress indicator to blog posts. What's the best approach? Consider performance and accessibility." ``` Claude gives me a plan: scroll event listener, throttling, ARIA labels, etc. 2. **Hand the plan to Gemini Flash:** ``` "Implement this reading progress indicator following this plan: [paste Claude's plan] Tech stack: Astro, TypeScript, Tailwind" ``` Flash generates the component code in seconds. 3. **Review and refine:** check the code makes sense, fix the obvious issues, test it manually. 4. **Generate tests with Gemini Flash:** ``` "Write tests for this component. Check: - Progress updates on scroll - Handles edge cases (top/bottom of page) - Accessibility attributes are present" ``` 5. **Final review:** run the tests, tweak styling if needed, done. I did not time this version either, so no numbers. No magic involved: I just stopped spending my evenings on the mechanical parts of coding. ## Where it actually pays off ### Tests: I write the function, the AI writes the suite A good share of my tests are now AI-written. I review every one of them. ```typescript // I write this function function calculateReadingTime(content: string): number { const wordsPerMinute = 200; const words = content.split(/\s+/).length; return Math.ceil(words / wordsPerMinute); } // I ask Gemini Flash: "Write tests for calculateReadingTime" // It generates several test cases in seconds ``` Are the tests perfect? No. Sometimes I fix them. But it beats writing them from scratch by a wide margin. ### Tailwind classes without the docs tab I show Gemini a screenshot or a description of what I want, and it hands back the Tailwind classes. ``` Me: "Create a card component with: - Subtle shadow - Rounded corners - Hover effect that lifts it slightly - Dark mode support" Gemini: [gives me the exact Tailwind classes] Me: [tweaks a couple of classes, done] ``` Saves me from constantly looking up Tailwind documentation. ### Several throwaway approaches without the effort Need to try a few different approaches? The AI generates them quickly. I pick the best one and refine it. Much faster than coding them all by hand. ## The honest part: where this falls over ### Google One Pro limits arrive fast I hit the usage limits pretty often. When that happens I either wait for the reset (annoying), switch to Claude Code (which has its own limits), or do it manually (defeats the purpose). Reality check: if you plan to lean on this heavily, Google One Pro might not be enough. The API with pay-per-use would be better, but that costs money. ### Flash is sometimes too fast for its own good It gives me code that works but misses edge cases. Or suggests an approach that's technically correct but overcomplicated for my use case. That's exactly why Claude Code plans first. Claude thinks deeper, Flash executes faster. ### You still review everything AI makes mistakes. Sometimes subtle ones. Last week, Gemini generated a test that looked perfect but was actually testing the wrong thing. I only caught it because I read through the test carefully. **If you blindly trust AI-generated code, you will ship bugs.** I review every line before committing. Non-negotiable. ### Domain-specific code is hit-or-miss Generic code? The AI handles it well. Your specific business logic? Not so much. Example: my blog has a custom date formatting system. The AI kept suggesting I use a library instead. Technically correct, but not what I wanted. I had to add it to the prompt: "Don't suggest libraries for this, just implement the custom logic." ## My actual setup (no GitHub Actions, no API keys) I use Google One Pro in the browser, so the whole workflow is four phases. ### 1. Planning (Claude Code) Open Claude Code (web or app) and ask: ``` "I need to [describe feature]. Tech stack: [your stack] What's the best approach? Think about: - Implementation steps - Edge cases - Testing strategy - Potential issues" ``` Claude gives me a detailed plan. I save it or keep the chat open. ### 2. Implementation (Gemini Flash) Copy Claude's plan into Gemini Flash: ``` "Implement this feature following this plan: [paste Claude's plan] Tech stack: [your stack] Files to modify: [list files] Generate the complete implementation." ``` Gemini generates code fast. I copy it into my editor. ### 3. Testing (Gemini Flash) ``` "Write comprehensive tests for this code: [paste the code] Use [your test framework] Cover edge cases and error scenarios" ``` Gemini generates tests. I review them and add them to my suite. ### 4. Review and refine (me) Read all the generated code. Check for bugs. Test manually. Fix what's wrong. Commit when it works. I did not time a typical feature end to end, so no numbers. ## What I noticed after three weeks I did not time anything, so there are no numbers here. This is what I noticed on my side projects: | Task | With AI | | ----------------------- | -------------------------------------------------- | | Feature implementation | Faster, mostly the first draft | | Writing tests | Much faster, but I review every one | | Tailwind styling | Fewer trips to the documentation | | Bug investigation | No clear change: some go faster, some don't | The catch, again: this only works because I review everything. Copy-paste AI code without reading it and you'll ship bugs left and right. ## Flash vs Pro, after a week with each ### Gemini 3 Flash Best for quick implementation tasks, test generation, styling and UI work, and following a clear plan. Not great for complex architectural decisions, deep debugging, or dense business logic. Speed: very fast on most tasks. Cost: free with Google One Pro, with limits. ### Gemini 3 Pro Best for architectural decisions, complex problem-solving, deep code analysis, and explaining why something works. Not great for quick iterations (takes longer) or simple tasks (overkill). Speed: slower. Cost: same limits on Google One Pro. My conclusion: Flash for execution tasks (faster, good enough quality), Pro for thinking tasks (deeper reasoning). But honestly? Claude Code beats both for planning. ## The mistakes, week by week Week 1: I used only Gemini Flash, for everything. Result: fast but messy code with lots of bugs. Lesson: Flash executes, it doesn't plan. Week 2: I trusted the AI too much. Copied code without reviewing and shipped a bug that broke my contact form. Lesson: always review AI-generated code. No exceptions. Week 3: found the balance. Claude Code for planning, Gemini Flash for execution, thorough review on top. Lesson: the right tool for each job. ## Should you try it? Yes, if you work solo on side projects, hate writing repetitive code, want to ship faster, and are willing to review AI output carefully. No, if you enjoy writing every line yourself (totally valid), don't have time to review AI code, work on critical production systems that need more thorough human review, or expect AI to solve all your problems. It won't. Maybe, if you're skeptical but curious. Fair. Try before committing. ## My honest recommendation I'm not saying this is THE way to code. I'm saying it's working for me, right now, on my side projects, as someone who's still learning. What's working: features in less time than I'd have scoped, a good share of tests AI-generated (and reviewed by me), less time on boring stuff and more on interesting problems. What's not perfect: I have to review everything, I hit Google One Pro limits, I'm still learning the best prompts, and some tasks the AI just can't handle well. After three weeks, I'm convinced it's worth trying if you're willing to learn the tools properly, review every line, accept the imperfection, and keep adjusting. Will it work for you? I honestly don't know. Try it and see. ## FAQ ### Can I use Gemini Flash without paying for Google One Pro? You can use the free tier of Gemini, but you'll hit usage limits quickly. Google One Pro gives you more generous limits. If you need unlimited usage, the API is pay-per-use (check [Google's pricing page](https://ai.google.dev/gemini-api/docs/pricing) for current Gemini 3 Flash rates). ### Is AI code review as good as human code review? No. AI is good at catching syntax errors, suggesting implementations, and generating tests. It doesn't understand your specific context, business logic, or architectural constraints. I still review everything myself; the AI just speeds up the mechanical parts. ### Which is better: Gemini Flash or Claude Code? They're good at different things. Claude Code is better for planning and architectural decisions. Gemini Flash is better for fast execution and test generation. I use both together for the best results. ### How much time does it actually save? I didn't time it, so no numbers. My impression is that the mechanical parts (tests, styling, first draft) go noticeably faster. I'm still learning, so your mileage may vary. ### Do I need to know how to code to use AI coding tools? Yes. AI doesn't replace coding knowledge, it accelerates it. You need to understand code to review the output, catch mistakes, and guide the AI effectively. These tools work best for developers who already know what they're doing. I've been doing this for three weeks. I'm sure I'm missing things, doing parts of it inefficiently, getting some of it plain wrong. That's the deal with learning in public: you ship the half-formed version and let people poke holes in it. So poke. **Related reading:** if you're choosing a Gemini model for this workflow, start with [the Gemini 3 developer guide](/en/blog/gemini-3-developer-guide/). --- **P.S.** Have you tried AI coding tools? Which workflow works for you, and what am I getting wrong here? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). And if you try this setup, I want to hear how it goes, especially the parts that don't work. --- URL: https://www.oscargallegoruiz.com/blog/gemini-flash-code-review-automatizado/ Lang: es # Gemini Flash para revisar código: 3 semanas en mis proyectos > Tres semanas combinando Gemini Flash y Claude Code en proyectos personales: la IA escribe buena parte de mis tests y los reviso todos. Qué funcionó y qué no. ## La versión corta, tras tres semanas El setup: desarrollador trabajando solo, unos 3 años de experiencia, Google One Pro (pagaba por el almacenamiento, resulta que incluye Gemini) más Claude Code, en proyectos personales. Los resultados: buena parte de mis tests ahora los genera la IA pero los reviso a mano, las features me llevan menos de lo que habría estimado (es una impresión, no lo cronometré), y el reparto que se quedó es Claude Code para planificar, Gemini Flash para ejecutar. Sigo alcanzando los límites de uso regularmente. El pero: lo revisas todo. La IA comete errores, y este flujo solo sobrevive en proyectos personales donde puedo permitirme cazar mis propios bugs. ¿Vale la pena probarlo? Si trabajas solo, en proyectos personales, y odias el código repetitivo: sí. Si trabajas en sistemas críticos o no puedes revisar el output de la IA con cuidado: no. --- ## ¿Quién soy yo para contarte esto? Llevo unos 3 años programando. No soy ingeniero senior. No gestiono equipos. No trabajo en FAANG. Soy un desarrollador construyendo proyectos personales, intentando lanzar más rápido, y trasteando con herramientas de IA para ver si de verdad ayudan. Así que no leas esto como una guía definitiva ni como las mejores prácticas de un ingeniero 10x. Son tres semanas de probar cosas: qué funcionó, qué no, qué me sorprendió. Si estás en una situación parecida (desarrollador solo, proyectos personales, tiempo limitado), quizá te ahorre el experimento. ## Desarrollar solo es lento porque lo aburrido también te toca a ti Cuando trabajas en proyectos personales solo, todo cae sobre ti: - Escribir todo el código - Escribir todos los tests (aburrido) - Manejar todo el styling (tedioso) - Arreglar todos los bugs - Revisar tu propio código (ya sabemos cómo va eso) ¿Y honestamente? Escribir tests es repetitivo. Ajustar clases de Tailwind durante horas atonta. Cazar mis propios bugs es una lotería. Yo quería mi tiempo en las partes interesantes, construir features y resolver problemas, no en lo mecánico. ## Lo que probé, con expectativas bajas Había escuchado a gente hypeando las herramientas de IA para programar y yo era escéptico. "Probablemente está sobrevalorado", pensé. Pero ya tenía una suscripción de Google One Pro (por el almacenamiento, no por la IA), que incluye Gemini. Y la gente no paraba de hablar de Claude Code. Así que: probarlo unas semanas y ver qué pasa. Peor caso, pierdo algo de tiempo. Mejor caso, aprendo algo útil. ### Por qué Gemini Flash en concreto Cuando Google lanzó Gemini 3 Flash, todos asumieron que era la versión "lite" de Pro. Más rápido pero menos inteligente. El trade-off de siempre. Excepto que los benchmarks que publicó Google decían lo contrario. Según los benchmarks que publicó Google y las cifras de velocidad de Artificial Analysis (SWE-bench Verified, que prueba la IA con issues reales de GitHub de proyectos open-source), Flash puntuaba por encima de Pro, iba bastante más rápido que la generación anterior y costaba bastante menos por token. No he comprobado esos números yo, así que no te los pongo aquí: mira [la página de precios de Google](https://ai.google.dev/gemini-api/docs/pricing) si te importa el detalle. Lo bastante raro como para probarlo. _(Nota: uso Google One Pro, no la API, así que no pago tarifas de API. Pero sí alcanzo los límites de uso regularmente.)_ ## El combo que funcionó: Claude Code piensa, Gemini Flash teclea La clave: no estoy usando Gemini Flash solo. Después de una semana de experimentar, este es el reparto que de verdad me funciona. ### El flujo híbrido **1. Claude Code para planificación e investigación.** - "Investiga la mejor forma de testear este componente de React" - "Dame un plan de implementación para [feature]" - "¿Cuáles son los edge cases que debería manejar?" Claude Code tarda más pero piensa a fondo. Bueno para decisiones arquitectónicas y planificación. **2. Gemini Flash para ejecución.** - "Aquí está el plan que Claude me dio. Impleméntalo." - "Escribe tests para estas funciones siguiendo este enfoque" - "Estiliza este componente para que coincida con este diseño" Gemini Flash ejecuta increíblemente rápido. A veces no piensa suficiente, pero para eso está el plan. ¿Por separado? Meh. ¿Juntos? Realmente útil. ### Por qué el combo se sostiene Claude Code es lento pero exhaustivo, justo lo que quieres para arquitectura. Gemini Flash es rápido pero a veces superficial, justo lo que quieres para implementar un plan que ya existe. Claude Code: "Así es CÓMO deberíamos resolver esto y POR QUÉ." Gemini Flash: "Entendido, implementando ahora." **Una herramienta planifica, la otra teclea.** Ese reparto del trabajo es más fiable que apoyarse en una sola. ## Una feature real, paso a paso Así es como funciona esto en la práctica, en mi propio portfolio. ### Cómo trabajaba antes Construyendo una nueva feature para el blog: 1. Investigar mejores prácticas 2. Planificar la implementación 3. Escribir el código 4. Escribir tests (ugh) 5. Estilos con Tailwind 6. Arreglar bugs No lo cronometré: se me iba buena parte de una tarde. ### La misma feature, con el combo 1. **Pregunto a Claude Code:** ``` "Quiero añadir un indicador de progreso de lectura a los posts del blog. ¿Cuál es el mejor enfoque? Considera rendimiento y accesibilidad." ``` Claude me da un plan: scroll event listener, throttling, etiquetas ARIA, etc. 2. **Le paso el plan a Gemini Flash:** ``` "Implementa este indicador de progreso de lectura siguiendo este plan: [pego el plan de Claude] Tech stack: Astro, TypeScript, Tailwind" ``` Flash genera el código del componente en segundos. 3. **Revisar y refinar:** comprobar que el código tiene sentido, arreglar lo obvio, testear a mano. 4. **Generar tests con Gemini Flash:** ``` "Escribe tests para este componente. Verifica: - El progreso se actualiza al hacer scroll - Maneja edge cases (arriba/abajo de la página) - Los atributos de accesibilidad están presentes" ``` 5. **Revisión final:** ejecutar los tests, ajustar estilos si hace falta, listo. Tampoco cronometré esta versión, así que no te doy cifras. Sin magia: simplemente dejé de gastar mis tardes en las partes mecánicas de programar. ## Dónde compensa de verdad ### Tests: yo escribo la función, la IA escribe la suite Buena parte de mis tests ahora los escribe la IA. Yo reviso cada uno. ```typescript // Yo escribo esta función function calculateReadingTime(content: string): number { const wordsPerMinute = 200; const words = content.split(/\s+/).length; return Math.ceil(words / wordsPerMinute); } // Pregunto a Gemini Flash: "Escribe tests para calculateReadingTime" // Genera varios casos de test en segundos ``` ¿Son perfectos? No. A veces los arreglo. Pero le saca mucha distancia a escribirlos desde cero. ### Clases de Tailwind sin la pestaña de docs Le muestro a Gemini una captura o una descripción de lo que quiero, y me devuelve las clases de Tailwind. ``` Yo: "Crea un componente de tarjeta con: - Sombra sutil - Esquinas redondeadas - Efecto hover que la levante ligeramente - Soporte para dark mode" Gemini: [me da las clases exactas de Tailwind] Yo: [ajusto un par de clases, listo] ``` Me ahorra estar buscando constantemente en la documentación de Tailwind. ### Varios enfoques desechables sin esfuerzo ¿Necesitas probar varios enfoques diferentes? La IA los genera rápido. Elijo el mejor y lo refino. Mucho más rápido que codificarlos todos a mano. ## La parte honesta: dónde se cae ### Los límites de Google One Pro llegan rápido Alcanzo los límites de uso bastante a menudo. Cuando pasa, o espero a que se resetee el límite (molesto), o cambio a Claude Code (que tiene sus propios límites), o lo hago a mano (anula el propósito). Seamos realistas: si planeas usar esto intensivamente, Google One Pro puede no ser suficiente. La API con pago por uso sería mejor, pero cuesta dinero. ### Flash a veces es demasiado rápido para su propio bien Me da código que funciona pero se pierde edge cases. O sugiere un enfoque técnicamente correcto pero sobrecomplicado para mi caso de uso. Justo por eso Claude Code planifica primero. Claude piensa más profundo, Flash ejecuta más rápido. ### Sigues revisando todo La IA comete errores. A veces sutiles. La semana pasada, Gemini generó un test que se veía perfecto pero en realidad estaba probando lo incorrecto. Solo lo cacé porque leí el test con calma. **Si confías ciegamente en código generado por IA, vas a lanzar bugs.** Reviso cada línea antes de hacer commit. No negociable. ### Con lo específico del dominio, a veces acierta y a veces no ¿Código genérico? La IA lo maneja bien. ¿Tu lógica de negocio concreta? No tanto. Ejemplo: mi blog tiene un sistema de formateo de fechas personalizado. La IA insistía en que usara una librería en su lugar. Técnicamente correcto, pero no lo que yo quería. Tuve que añadirlo al prompt: "No sugieras librerías para esto, solo implementa la lógica personalizada." ## Mi setup real (sin GitHub Actions ni API keys) Uso Google One Pro en el navegador, así que el flujo entero son cuatro fases. ### 1. Planificación (Claude Code) Abro Claude Code (web o app) y pregunto: ``` "Necesito [describir feature]. Tech stack: [tu stack] ¿Cuál es el mejor enfoque? Piensa en: - Pasos de implementación - Edge cases - Estrategia de testing - Problemas potenciales" ``` Claude me da un plan detallado. Lo guardo o mantengo el chat abierto. ### 2. Implementación (Gemini Flash) Copio el plan de Claude en Gemini Flash: ``` "Implementa esta feature siguiendo este plan: [pego el plan de Claude] Tech stack: [tu stack] Archivos a modificar: [lista archivos] Genera la implementación completa." ``` Gemini genera código rápido. Lo copio en mi editor. ### 3. Testing (Gemini Flash) ``` "Escribe tests completos para este código: [pego el código] Usa [tu framework de tests] Cubre edge cases y escenarios de error" ``` Gemini genera tests. Los reviso y los añado a mi suite. ### 4. Revisar y refinar (yo) Leo todo el código generado. Busco bugs. Testeo a mano. Arreglo lo que esté mal. Commit cuando todo funciona. No cronometré el tiempo total de una feature típica, así que no te doy cifras. ## Lo que noté tras tres semanas No cronometré nada, así que no hay números aquí. Esto es lo que noté en mis proyectos personales: | Tarea | Con IA | | -------------------------- | ----------------------------------------------------- | | Implementación de features | Más rápido, sobre todo el primer borrador | | Escribir tests | Bastante más rápido, pero los reviso todos | | Estilos con Tailwind | Menos idas y venidas a la documentación | | Investigación de bugs | Sin cambio claro: unas van más rápido y otras no | El pero, otra vez: esto solo funciona porque lo reviso todo. Copia y pega código de IA sin leerlo y lanzarás bugs a diestra y siniestra. ## Flash vs Pro, una semana con cada uno ### Gemini 3 Flash Mejor para tareas de implementación rápidas, generación de tests, trabajo de styling y UI, y seguir un plan claro. No tan bueno para decisiones arquitectónicas complejas, debugging profundo, o lógica de negocio densa. Velocidad: muy rápido en la mayoría de tareas. Coste: gratis con Google One Pro, con límites. ### Gemini 3 Pro Mejor para decisiones arquitectónicas, resolución de problemas complejos, análisis profundo de código, y explicar por qué algo funciona. No tan bueno para iteraciones rápidas (tarda más) ni tareas simples (overkill). Velocidad: más lento. Coste: mismos límites en Google One Pro. Mi conclusión: Flash para tareas de ejecución (más rápido, calidad suficiente), Pro para tareas de pensamiento (razonamiento más profundo). ¿Pero honestamente? Claude Code gana a ambos para planificar. ## Los errores, semana a semana Semana 1: usé solo Gemini Flash, para todo. Resultado: código rápido pero desordenado y con muchos bugs. Lección: Flash ejecuta, no planifica. Semana 2: confié demasiado en la IA. Copié código sin revisar y lancé un bug que rompió mi formulario de contacto. Lección: siempre revisa el código generado por IA. Sin excepciones. Semana 3: encontré el equilibrio. Claude Code para planificar, Gemini Flash para ejecutar, revisión exhaustiva encima. Lección: la herramienta correcta para cada trabajo. ## ¿Deberías probarlo? Sí, si trabajas solo en proyectos personales, odias escribir código repetitivo, quieres lanzar más rápido, y estás dispuesto a revisar el output de la IA con cuidado. No, si disfrutas escribiendo cada línea tú mismo (totalmente válido), no tienes tiempo para revisar código de IA, trabajas en sistemas críticos de producción que necesitan revisión humana más exhaustiva, o esperas que la IA resuelva todos tus problemas. No lo hará. Quizás, si eres escéptico pero curioso. Normal. Pruébalo antes de casarte con nada. ## Mi recomendación honesta No digo que esta sea LA forma de programar. Digo que me está funcionando a mí, ahora mismo, en mis proyectos personales, como alguien que todavía está aprendiendo. Lo que funciona: features en menos tiempo del que habría estimado, buena parte de los tests generados por IA (y revisados por mí), menos tiempo en lo aburrido y más en problemas interesantes. Lo que no es perfecto: tengo que revisarlo todo, alcanzo los límites de Google One Pro, todavía estoy aprendiendo los mejores prompts, y hay tareas que la IA simplemente no maneja bien. Después de tres semanas, estoy convencido de que vale la pena probarlo si estás dispuesto a aprender las herramientas en serio, revisar cada línea, aceptar la imperfección, y seguir ajustando. ¿Te funcionará a ti? Honestamente no lo sé. Pruébalo y verás. ## Preguntas frecuentes ### ¿Puedo usar Gemini Flash sin pagar por Google One Pro? Puedes usar el tier gratuito de Gemini, pero alcanzarás los límites de uso rápidamente. Google One Pro te da límites más generosos. Si necesitas uso ilimitado, la API es pago por uso (consulta [la página de precios de Google](https://ai.google.dev/gemini-api/docs/pricing) para las tarifas actuales de Gemini 3 Flash). ### ¿La revisión de código con IA es tan buena como la humana? No. La IA es buena detectando errores de sintaxis, sugiriendo implementaciones, y generando tests. No entiende tu contexto específico, tu lógica de negocio, ni tus restricciones arquitectónicas. Sigo revisando todo yo mismo; la IA solo acelera las partes mecánicas. ### ¿Cuál es mejor: Gemini Flash o Claude Code? Son buenos para cosas diferentes. Claude Code es mejor para planificación y decisiones arquitectónicas. Gemini Flash es mejor para ejecución rápida y generación de tests. Uso ambos juntos para mejores resultados. ### ¿Cuánto tiempo ahorra realmente? No lo cronometré, así que no te doy cifras. Mi impresión es que las partes mecánicas (tests, estilos, primer borrador) van bastante más rápido. Todavía estoy aprendiendo, así que tu experiencia puede variar. ### ¿Necesito saber programar para usar herramientas de IA para código? Sí. La IA no reemplaza el conocimiento de programación, lo acelera. Necesitas entender código para revisar el output, cazar errores, y guiar a la IA. Estas herramientas funcionan mejor para desarrolladores que ya saben lo que hacen. Llevo tres semanas con esto. Seguro que me estoy perdiendo cosas, haciendo partes de forma ineficiente, equivocándome en otras. Ese es el trato de aprender en público: publicas la versión a medio formar y dejas que la gente le busque los agujeros. Pues búscalos. **Lectura relacionada:** si estás eligiendo modelo de Gemini para este flujo, empieza por [la guía de Gemini 3 para desarrolladores](/blog/gemini-3-guia-desarrollador/). --- **P.D.** ¿Has probado herramientas de IA para programar? ¿Qué flujo te funciona, y en qué me estoy equivocando? Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). Y si pruebas este setup, quiero saber cómo te va, sobre todo las partes que no funcionan. --- URL: https://www.oscargallegoruiz.com/en/blog/astro-6-migration-guide/ Lang: en # Astro 5 to 6 Upgrade: Fix slug→id and Zod 4 Errors Fast > Three checks before bumping to Astro 6: grep .slug, one content.config.ts, no .default() after .transform(). Node 22.12+ and the fix for each error. **Short answer:** before you bump to Astro 6, run three checks. `grep -rn '\.slug' src`: every hit becomes `.id`. Make sure your schema lives at `src/content.config.ts` and nowhere else. And look for any `.default()` that comes after a `.transform()`, because in Zod 4 the default has to match the transformed type. Add Node 22.12 or newer and you've covered the changes that bite. I upgraded this very site from Astro 5 to Astro 6. The plan was a quick `pnpm up astro`, a glance at the changelog, and a celebratory coffee. I did not get the coffee. I spent a good while staring at a `ContentSchemaContainsSlugError` that read like a riddle, and another stretch untangling a Zod default that compiled fine in v5 and exploded in v6. Here is the good news before the war story: v6 is mostly an evolution of v5, not a rewrite. Same Content Layer, same Server Islands. What changed is that the grace periods are over. The legacy escape hatches that let you limp along on v4-shaped code in v5 are gone. So if your v5 upgrade was half-finished, v6 is where the bill comes due. A note on dates: Astro 6 went stable on 10 March 2026, so the upgrade I describe came after this post's original publication date (December 2025). The misplaced `content.config.ts` part does date from November 2025, still on Astro 5.15. This post is the upgrade path I actually walked, v5 to v6, with the breaking changes that bit me first. If you are coming straight from Astro 4, jump to [the section at the bottom](#still-on-astro-4-the-v4-to-v5-story); the v5 foundations still apply and you will want them first. ## What breaks going from 5 to 6 (the 60-second version) Everything below is from the official [upgrade to v6 guide](https://docs.astro.build/en/guides/upgrade-to/v6/), cross-checked against my own diff: - **Node `v22.12.0` is the new minimum**, and only even-numbered releases are supported. v23 will not run it. - **`src/content.config.ts` is mandatory** if you use content collections. The old `src/content/config.ts` location is no longer read. - **The `legacy.collections` flag is gone.** If you were leaning on it in v5, that crutch has been kicked away. - **The identifier is `post.id`, not `post.slug`.** The Content Layer made `id` the identifier back in v5; v6 just removes the legacy collections fallback, so there is no `slug` left to lean on. A `slug` field in a schema throws `ContentSchemaContainsSlugError`. - **`Astro.glob()` is removed.** Replace it with `import.meta.glob()` (which no longer returns a Promise) or `getCollection()`. - **Zod is on v4.** Default values must match the output type after transforms, and `astro:schema` imports move to `astro/zod`. - **`getEntryBySlug()` and `getDataEntryById()` are deprecated** in favor of a single `getEntry()`. If you only read one line: the v5 to v6 jump is not about new toys. It is about finally deleting the compatibility shims you have been ignoring. ## The slug to id trap (the one that cost me an hour) This is where v6 hit me hardest, because the error message points at your schema, not at the real culprit. In Astro 4, every content entry had a `slug`, and most of us wired it straight into `getStaticPaths`. Astro 5's Content Layer already moved the identifier to `id`, but the legacy collections path kept `slug` limping along, so sloppy code survived. Astro 6 removes that legacy path. No more `slug` to fall back on. Here is the diff that fixed my build: ```astro --- // src/pages/blog/[...slug].astro export async function getStaticPaths() { const posts = await getCollection('blog'); return posts.map((post) => ({ // Astro 5 leftover: post.slug is gone in v6 // params: { slug: post.slug }, params: { slug: post.id }, props: post, })); } --- ``` If your schema also declares a `slug` field, that is what trips `ContentSchemaContainsSlugError`. Remove it and let the `glob` loader derive the id from the filename. Do a global search for `.slug` before you upgrade. It is the difference between a quick fix and an afternoon. ## Zod 4: the default that lies to you The second wall. In Zod 3 (Astro 5), a default value matched the *input* type. In Zod 4 (Astro 6), it has to match the *output* type, the one you get after transforms run. So this, which I had copied from my own homepage view counter, broke: ```typescript // Astro 5, Zod 3: default is the pre-transform string views: z.string().transform(Number).default("0"), // Astro 6, Zod 4: default must match the post-transform number views: z.string().transform(Number).default(0), ``` While you are in there, fix the imports too. `astro:schema` is deprecated in v6: ```typescript // Before import { z } from "astro:schema"; // After import { z } from "astro/zod"; ``` You do not strictly need the `astro/zod` path. `zod` is a direct dependency in Astro 6, so plain `import { z } from "zod"` works too, and it is what I run in production. `astro/zod` just re-exports the exact Zod version Astro validates your schemas against, so you cannot drift onto a mismatched copy. `.nonempty()` on strings is also gone in Zod 4. Swap it for `.min(1)`. Getting these type boundaries right (defaults matching the post-transform type, no silent `string`/`number` drift) is the same discipline I lean on across the codebase; I collected the rest in [TypeScript best practices](/en/blog/typescript-best-practices/). ## The removed APIs, and what to use instead `Astro.glob()` was deprecated back in v5 and is now fully removed. The replacement depends on what you were globbing: ```typescript // Querying content collections? Use the Content Layer. const posts = await getCollection('blog'); // Globbing arbitrary source files? import.meta.glob, and note: // it no longer returns a Promise, so drop the await. const modules = import.meta.glob('./data/*.json', { eager: true }); ``` For collection lookups, `getEntryBySlug()` and `getDataEntryById()` both collapse into one function: ```typescript // Before const post = await getEntryBySlug('blog', 'my-post'); // After const post = await getEntry('blog', 'my-post'); ``` And the cleanup that took ten seconds but felt the best: deleting the `legacy` block from `astro.config.mjs`. ```typescript import { defineConfig } from 'astro/config'; export default defineConfig({ // Delete this whole block. It does nothing in v6 except remind // you that you put off the real migration. legacy: { collections: true, }, }); ``` ## Missing schema fields? Check where content.config.ts lives On Astro 5 this one failed silently, which is the worst way to fail. I added a `relatedSlug` field to my blog schema, put it in the frontmatter, and it never showed up: not in the types, not in `post.data`. Making it required didn't throw. Renaming it didn't help. When even a required field is ignored, Astro isn't reading your config at all. The cause was one slash. Back in November 2025, on Astro 5.15, I was editing `src/content/config.ts` while an older `src/content.config.ts` sat at the root of `src/`, and Astro read that one. v6 is kinder: a leftover `src/content/config.ts` now throws `LegacyContentConfigError` instead of being ignored. To confirm which file Astro actually loads, look at the generated types: ```typescript // .astro/content.d.ts export type ContentConfig = typeof import("../src/content.config.js"); ``` The checklist, before you blame the framework: 1. **Location.** `src/content.config.ts`, at the root of `src/`, not inside `src/content/`. 2. **Name.** Exactly `content.config.ts`. Any other variation is ignored. 3. **No duplicates.** `find src -path '*content*' -name 'config.*'` should only find one file. Merge the schema into the real one and delete the other. 4. **Exports.** The file has to `export const collections`. 5. **Cache.** Delete `.astro/` and restart the dev server so the types regenerate from the right file. ## content.config.ts: the glob() loader and defineCollection None of the above is the reason to upgrade. The reason is the thing v5 introduced and v6 makes the only way: the Content Layer is a real data pipeline, not just a Markdown reader. It all lives in `content.config.ts`, where every collection is a `defineCollection` paired with a loader. For local Markdown that loader is `glob()` (shown in the v4 section below); the power is that you can swap it for one you write yourself. The `glob` loader you wire up in `content.config.ts` is just a function that returns an array of objects. Which means you can write your own. Here is the loader I use to pull GitHub stars into my projects section, with no top-level `fetch()` rotting inside a component: ```typescript // src/content.config.ts import { defineCollection } from 'astro:content'; import { z } from 'astro/zod'; const githubLoader = { name: 'github-repos', load: async ({ store, logger }) => { logger.info('Fetching repos from GitHub...'); const response = await fetch('https://api.github.com/users/garbarok/repos'); const repos = await response.json(); for (const repo of repos) { store.set({ id: repo.name, data: { description: repo.description, stars: repo.stargazers_count, url: repo.html_url, }, }); } }, }; const projects = defineCollection({ loader: githubLoader, schema: z.object({ stars: z.coerce.number(), url: z.string().url(), }), }); export const collections = { projects }; ``` In my components I just call `getCollection('projects')`. The frontend has no idea the data came from an API, and Astro caches it at build time. That separation is what the migration buys you. Server Islands (`server:defer`) are the other v5 idea that carries straight into v6 unchanged. A static shell on the CDN with a dynamic hole that gets filled by a tiny per-island fetch. No hydration, no client React. If you skipped it in v5, v6 is a fine excuse to finally use it. ## The honest part: where v6 is annoying I promised a war story, not a brochure. The `ContentSchemaContainsSlugError` message is genuinely bad. It blames your schema when the real problem is usually a `params: { slug: post.slug }` three files away. I lost time chasing the wrong line. The Zod 4 default change is the kind of break that compiles, passes a quick smoke test, and then serves wrong data in production because `"0"` and `0` both look fine until something downstream does math. Test your defaults, not just your types. And the `import.meta.glob()` "no longer returns a Promise" change is easy to miss because removing an `await` from working code feels wrong. It will not error loudly. It will just hand you a Promise where you expected data. None of these are dealbreakers. But anyone selling v6 as a frictionless bump has not migrated a real project. (Astro 7 was the opposite: [a version bump and a coffee](/en/blog/astro-7-painless-migration/).) ## Still on Astro 4? The v4 to v5 story Everything above assumes you already made the v4 to v5 jump. If you did not, this is the part that still matters, because the Content Layer was born here. In Astro 4, you defined collections with a magic string: ```typescript // Astro 4, the old way import { defineCollection, z } from 'astro:content'; const blog = defineCollection({ type: 'content', // "look for files, somehow" schema: z.object({ /* ... */ }), }); ``` Astro 5 stopped believing in magic and asked for explicit loaders: ```typescript // Astro 5+, the new way import { defineCollection, z } from 'astro:content'; import { glob } from 'astro/loaders'; const blog = defineCollection({ loader: glob({ pattern: '**/*.md', base: './src/content/blog' }), schema: z.object({ title: z.string(), pubDate: z.date(), }), }); ``` Two more v4-era traps that v6 simply assumes you have already fixed: The `output: 'hybrid'` mode is gone. Astro is now static by default with opt-in SSR, or server by default with opt-in static. Delete `hybrid` from your config. And `post.render()` no longer exists. Content entries are plain objects now, so you import the renderer: ```typescript import { render } from 'astro:content'; const { Content } = await render(post); ``` Do that work, get a green v5 build, and the v6 step at the top of this post becomes a quiet afternoon instead of a bad one. **Related reading:** if you are pairing with an AI assistant for this kind of multi-file refactor, my [Google Antigravity review](/en/blog/google-antigravity-review/) covers the agent-first IDEs I tried in November 2025, during the Astro 5 work described above. **Related reading:** if you want the Astro 6 overview first (what it is, islands, and why it ships so little JavaScript) before migrating, start with the [Astro 6 introduction](/en/blog/introduction-astro-5/). ## Sources - [Astro docs: Upgrade to v6](https://docs.astro.build/en/guides/upgrade-to/v6/) - [Astro docs: Content Collections](https://docs.astro.build/en/guides/content-collections/) - Astro, [Astro 6.0 announcement](https://astro.build/blog/astro-6/) (stable release date). --- **P.S.** Have you taken the v6 step yet? Did the `slug` to `id` change break your heart twice, once in v5 and once in v6? Tell me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). ## FAQ **Do I have to go through v5 to get to v6?** Yes, in practice. The upgrade guides are sequential, and v6 assumes your collections already use the Content Layer. If you are on v4, follow the steps in "Still on Astro 4?" above, get a green v5 build, then take the v6 step. **Can I keep the legacy collections flag a little longer?** No. `legacy.collections` is removed, and a leftover `src/content/config.ts` throws `LegacyContentConfigError`. v6 does offer `legacy.collectionsBackwardsCompat` as a temporary migration helper, but plan to move to `src/content.config.ts` and drop it. **Can I use Server Islands on Vercel or Netlify?** Yes, with the matching adapter installed. The island is a serverless function that returns HTML, so you need a host that runs functions. Nothing about that changed in v6. --- URL: https://www.oscargallegoruiz.com/blog/astro-6-guia-migracion/ Lang: es # Astro 6: content.config.ts, Zod 4 y la trampa de slug a id > Migré este sitio de Astro 5 a 6 en producción: ContentSchemaContainsSlugError, loaders de content.config.ts, defaults de Zod 4. Cómo arreglé cada uno. **Respuesta corta:** antes de subir a Astro 6, haz tres comprobaciones. `grep -rn '\.slug' src`: cada resultado pasa a ser `.id`. Asegúrate de que el schema está en `src/content.config.ts` y en ningún otro sitio. Y busca cualquier `.default()` que vaya después de un `.transform()`, porque en Zod 4 el default tiene que coincidir con el tipo ya transformado. Súmale Node 22.12 o superior y tienes cubiertos los cambios que muerden. Actualicé este mismo sitio de Astro 5 a Astro 6. El plan era un `pnpm up astro` rápido, un vistazo al changelog y un café para celebrarlo. Del café, nada. Me pasé un buen rato mirando un `ContentSchemaContainsSlugError` que parecía un acertijo, y otro rato desenredando un default de Zod que compilaba perfecto en v5 y explotaba en v6. La buena noticia antes de la batallita: v6 es una evolución de v5, no una reescritura. Mismo Content Layer, mismas Server Islands. Lo que cambia es que se acabaron los periodos de gracia. Las escotillas de emergencia que te dejaban tirar en v5 con código con pinta de v4 ya no están. Así que si tu migración a v5 quedó a medias, v6 es donde te pasan la factura. Una nota sobre las fechas: Astro 6 salió estable el 10 de marzo de 2026, así que la migración que cuento es posterior a la fecha de publicación original de este post (diciembre de 2025). La parte del `content.config.ts` mal colocado sí es de noviembre de 2025, todavía en Astro 5.15. Este post es la ruta que recorrí de verdad, de v5 a v6, con los breaking changes que me mordieron primero. Si vienes directo de Astro 4, salta a [la sección del final](#sigues-en-astro-4-la-historia-de-v4-a-v5): los cimientos de v5 siguen valiendo y los vas a necesitar antes. ## Qué se rompe al pasar de 5 a 6 (versión de 60 segundos) Todo lo de abajo sale de la [guía oficial de upgrade a v6](https://docs.astro.build/en/guides/upgrade-to/v6/), contrastado con mi propio diff: - **Node `v22.12.0` es el nuevo mínimo**, y solo se soportan versiones pares. La v23 no lo arranca. - **`src/content.config.ts` es obligatorio** si usas content collections. La ruta antigua `src/content/config.ts` ya no se lee. - **El flag `legacy.collections` desaparece.** Si te apoyabas en él en v5, te han quitado la muleta. - **El identificador es `post.id`, no `post.slug`.** La Content Layer ya movió el identificador a `id` en v5; v6 solo elimina el fallback de las colecciones legacy, así que no queda `slug` al que agarrarse. Un campo `slug` en un schema lanza `ContentSchemaContainsSlugError`. - **`Astro.glob()` se elimina.** Cámbialo por `import.meta.glob()` (que ya no devuelve una Promise) o por `getCollection()`. - **Zod va por la v4.** Los valores por defecto tienen que coincidir con el tipo de salida tras los transforms, y los imports de `astro:schema` pasan a `astro/zod`. - **`getEntryBySlug()` y `getDataEntryById()` quedan deprecados** en favor de un único `getEntry()`. Si solo te quedas con una idea: el salto de v5 a v6 no va de juguetes nuevos. Va de borrar por fin los parches de compatibilidad que llevabas ignorando. ## La trampa de slug a id (la que me costó una hora) Aquí es donde v6 me pegó más fuerte, porque el mensaje de error apunta a tu schema, no al culpable real. En Astro 4, cada entry tenía un `slug` y casi todos lo metíamos directo en `getStaticPaths`. La Content Layer de Astro 5 ya movió el identificador a `id`, pero la vía de las colecciones legacy mantenía el `slug` con vida, así que el código chapucero sobrevivía. Astro 6 elimina esa vía legacy. Ya no hay `slug` al que recurrir. Este es el diff que arregló mi build: ```astro --- // src/pages/blog/[...slug].astro export async function getStaticPaths() { const posts = await getCollection('blog'); return posts.map((post) => ({ // Resto de Astro 5: post.slug ya no existe en v6 // params: { slug: post.slug }, params: { slug: post.id }, props: post, })); } --- ``` Si tu schema además declara un campo `slug`, eso es lo que dispara `ContentSchemaContainsSlugError`. Quítalo y deja que el loader `glob` derive el id del nombre del archivo. Haz un "Find in Files" de `.slug` antes de actualizar. Es la diferencia entre un arreglo rápido y una tarde entera. ## Zod 4: el default que te miente El segundo golpe. En Zod 3 (Astro 5), el valor por defecto coincidía con el tipo de *entrada*. En Zod 4 (Astro 6) tiene que coincidir con el tipo de *salida*, el que te queda después de que se ejecuten los transforms. Así que esto, copiado de mi propio contador de visitas de la home, se rompió: ```typescript // Astro 5, Zod 3: el default es el string previo al transform views: z.string().transform(Number).default("0"), // Astro 6, Zod 4: el default tiene que ser el number posterior al transform views: z.string().transform(Number).default(0), ``` Ya que estás ahí, arregla también los imports. `astro:schema` queda deprecado en v6: ```typescript // Antes import { z } from "astro:schema"; // Después import { z } from "astro/zod"; ``` No necesitas obligatoriamente la ruta `astro/zod`. `zod` es dependencia directa en Astro 6, así que `import { z } from "zod"` a secas también funciona, y es lo que uso en producción. `astro/zod` solo reexporta la versión exacta de Zod contra la que Astro valida tus schemas, para que no acabes en una copia descuadrada. El `.nonempty()` sobre strings también desaparece en Zod 4. Cámbialo por `.min(1)`. Clavar bien estos límites de tipos (el default coincidiendo con el tipo de salida, sin deriva silenciosa entre `string` y `number`) es la misma disciplina que aplico en todo el código; el resto lo junté en [buenas prácticas en TypeScript](/blog/typescript-mejores-practicas/). ## Las APIs eliminadas, y qué usar en su lugar `Astro.glob()` quedó deprecado ya en v5 y ahora se elimina del todo. El reemplazo depende de qué estuvieras globbeando: ```typescript // ¿Consultas content collections? Usa el Content Layer. const posts = await getCollection('blog'); // ¿Globbeas ficheros sueltos? import.meta.glob, y ojo: // ya no devuelve una Promise, así que quita el await. const modules = import.meta.glob('./data/*.json', { eager: true }); ``` Para buscar entries de una colección, `getEntryBySlug()` y `getDataEntryById()` colapsan en una sola función: ```typescript // Antes const post = await getEntryBySlug('blog', 'my-post'); // Después const post = await getEntry('blog', 'my-post'); ``` Y la limpieza que tardó diez segundos pero sentó mejor que ninguna: borrar el bloque `legacy` de `astro.config.mjs`. ```typescript import { defineConfig } from 'astro/config'; export default defineConfig({ // Borra el bloque entero. En v6 no hace nada salvo recordarte // que pospusiste la migración de verdad. legacy: { collections: true, }, }); ``` ## ¿Faltan campos del schema? Mira dónde está content.config.ts En Astro 5 esto fallaba en silencio, que es la peor forma de fallar. Añadí un campo `relatedSlug` al schema del blog, lo puse en el frontmatter y nunca apareció: ni en los tipos ni en `post.data`. Hacerlo obligatorio no lanzó ningún error. Renombrarlo tampoco sirvió. Cuando hasta un campo obligatorio se ignora, Astro no está leyendo tu config. La causa era una barra. En noviembre de 2025, todavía en Astro 5.15, estaba editando `src/content/config.ts` mientras había un `src/content.config.ts` viejo en la raíz de `src/`, y Astro leía ese. v6 es más amable: si queda un `src/content/config.ts`, salta `LegacyContentConfigError` en vez de ignorarlo. Para confirmar qué fichero carga Astro de verdad, mira los tipos generados: ```typescript // .astro/content.d.ts export type ContentConfig = typeof import("../src/content.config.js"); ``` Repasa esto antes de echarle la culpa al framework: 1. **Ubicación.** `src/content.config.ts`, en la raíz de `src/`, no dentro de `src/content/`. 2. **Nombre.** Exactamente `content.config.ts`. Cualquier variación se ignora. 3. **Sin duplicados.** `find src -path '*content*' -name 'config.*'` solo debería encontrar un fichero. Pasa el schema al bueno y borra el otro. 4. **Exports.** El fichero tiene que hacer `export const collections`. 5. **Caché.** Borra `.astro/` y reinicia el servidor de desarrollo para que los tipos se regeneren desde el fichero correcto. ## content.config.ts: el loader glob() y defineCollection Nada de lo anterior es la razón para actualizar. La razón es lo que v5 introdujo y v6 convierte en el único camino: el Content Layer es un pipeline de datos de verdad, no un simple lector de Markdown. Todo vive en `content.config.ts`, donde cada colección es un `defineCollection` con su loader. Para Markdown local ese loader es `glob()` (lo ves en la sección de v4 más abajo); la potencia está en que puedes cambiarlo por uno que escribas tú. El loader `glob` que montas en `content.config.ts` es solo una función que devuelve un array de objetos. Lo cual significa que puedes escribir el tuyo. Este es el loader que uso para traer mis estrellas de GitHub a la sección de proyectos, sin un `fetch()` pudriéndose en el top-level de un componente: ```typescript // src/content.config.ts import { defineCollection } from 'astro:content'; import { z } from 'astro/zod'; const githubLoader = { name: 'github-repos', load: async ({ store, logger }) => { logger.info('Fetching repos from GitHub...'); const response = await fetch('https://api.github.com/users/garbarok/repos'); const repos = await response.json(); for (const repo of repos) { store.set({ id: repo.name, data: { description: repo.description, stars: repo.stargazers_count, url: repo.html_url, }, }); } }, }; const projects = defineCollection({ loader: githubLoader, schema: z.object({ stars: z.coerce.number(), url: z.string().url(), }), }); export const collections = { projects }; ``` En mis componentes solo llamo a `getCollection('projects')`. Al frontend le da igual de dónde vino el dato, y Astro lo cachea en tiempo de build. Esa separación es lo que ganas con la migración. Las Server Islands (`server:defer`) son la otra idea de v5 que pasa a v6 tal cual. Un shell estático en el CDN con un hueco dinámico que se rellena con un fetch minúsculo por isla. Sin hidratación, sin React en el cliente. Si te la saltaste en v5, v6 es buena excusa para usarla por fin. ## La parte honesta: dónde v6 da rabia Te prometí una batallita, no un folleto comercial. El mensaje `ContentSchemaContainsSlugError` es malo de verdad. Culpa a tu schema cuando el problema real suele ser un `params: { slug: post.slug }` tres ficheros más allá. Perdí tiempo persiguiendo la línea equivocada. El cambio del default de Zod 4 es de los que compilan, pasan un smoke test rápido y luego sirven datos mal en producción, porque `"0"` y `0` parecen iguales hasta que algo más abajo hace cuentas. Testea tus defaults, no solo tus tipos. Y lo de `import.meta.glob()` que "ya no devuelve una Promise" se pasa por alto fácil, porque quitar un `await` de código que funcionaba da cosa. No va a fallar con estruendo. Solo te va a dar una Promise donde esperabas datos. Ninguno es un dealbreaker. Pero quien te venda v6 como un bump sin fricción no ha migrado un proyecto de verdad. (Astro 7 fue lo contrario: [un `pnpm up` y un café](/blog/astro-7-migracion-sin-dolor/).) ## ¿Sigues en Astro 4? La historia de v4 a v5 Todo lo de arriba asume que ya diste el salto de v4 a v5. Si no, esta es la parte que todavía importa, porque el Content Layer nació aquí. En Astro 4, definías las collections con un string mágico: ```typescript // Astro 4, la forma antigua import { defineCollection, z } from 'astro:content'; const blog = defineCollection({ type: 'content', // "busca ficheros, no sé cómo" schema: z.object({ /* ... */ }), }); ``` Astro 5 dejó de creer en la magia y pidió loaders explícitos: ```typescript // Astro 5+, la nueva forma import { defineCollection, z } from 'astro:content'; import { glob } from 'astro/loaders'; const blog = defineCollection({ loader: glob({ pattern: '**/*.md', base: './src/content/blog' }), schema: z.object({ title: z.string(), pubDate: z.date(), }), }); ``` Dos trampas más de la era v4 que v6 da por hecho que ya has arreglado: El modo `output: 'hybrid'` desaparece. Astro es ahora estático por defecto con SSR opt-in, o server por defecto con estático opt-in. Borra `hybrid` de tu config. Y `post.render()` ya no existe. Las content entries son objetos planos, así que importas el render: ```typescript import { render } from 'astro:content'; const { Content } = await render(post); ``` Haz ese trabajo, consigue un build verde en v5, y el paso a v6 del principio de este post se convierte en una tarde tranquila en vez de un infierno. **Lectura relacionada:** si vas a hacer este refactor multi-archivo a cuatro manos con un asistente de IA, mi [reseña de Google Antigravity](/blog/resena-google-antigravity/) cuenta cómo se portan los IDEs agénticos que probé en noviembre de 2025, durante el trabajo en Astro 5 que cuento arriba. **Lectura relacionada:** si primero quieres el panorama de Astro 6 (qué es, islas y por qué carga tan poco JavaScript) antes de migrar, empieza por la [introducción a Astro 6](/blog/introduccion-astro-5/). ## Fuentes - [Docs de Astro: Upgrade to v6](https://docs.astro.build/en/guides/upgrade-to/v6/) - [Docs de Astro: Content Collections](https://docs.astro.build/en/guides/content-collections/) - Astro, [anuncio de Astro 6.0](https://astro.build/blog/astro-6/) (fecha de lanzamiento estable). --- **P.D.** ¿Ya diste el paso a v6? ¿El cambio de `slug` a `id` te rompió el corazón dos veces, una en v5 y otra en v6? Cuéntamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). ## FAQ **¿Tengo que pasar por v5 para llegar a v6?** En la práctica, sí. Las guías de upgrade son secuenciales, y v6 asume que tus colecciones ya usan el Content Layer. Si estás en v4, sigue los pasos de "¿Sigues en Astro 4?" más arriba, consigue un build verde en v5 y entonces da el paso a v6. **¿Puedo aguantar un poco más con el flag de legacy collections?** No. `legacy.collections` está eliminado, y si queda un `src/content/config.ts` salta `LegacyContentConfigError`. v6 sí ofrece `legacy.collectionsBackwardsCompat` como ayuda temporal para migrar, pero cuenta con pasar a `src/content.config.ts` y quitarlo. **¿Puedo usar Server Islands en Vercel o Netlify?** Sí, con el adapter correspondiente instalado. La isla es una serverless function que devuelve HTML, así que necesitas un host que ejecute functions. Nada de eso ha cambiado en v6. --- URL: https://www.oscargallegoruiz.com/en/blog/gemini-3-developer-guide/ Lang: en # Gemini 3 Pro for Developers: One Week of Hands-On Testing > A week with Gemini 3 Pro: Deep Think planning a sample migration, a bug diagnosed from a short video, and the agentic stuff that still needs a babysitter. I've been testing Gemini 3 Pro for the past week, and honestly? I'm surprised how well it works. I'd finally gotten comfortable with my Claude/GPT-4 workflow, and then Google launched this in November and I had to adjust everything again. But here's the thing: after forcing myself to rebuild a feature of mine that I'd already finished (yeah, I rewrote working code just to test this), I get the hype. This isn't your typical "a bit better at benchmarks" release. Deep Think and actual multimodality (not the fake kind) change how you can work. Let me show you what I mean. ## What's actually different this time ### 1. Deep Think, or why it actually pauses now You know how previous models would just... start spitting out tokens? Mid-thought, zero planning, just word prediction? Gemini 3 actually stops. It thinks. You'll see "[Thinking...]" in the API response, and at first I thought my connection dropped. Nope. It's genuinely spending compute time planning its answer before committing. **What I look for:** If you ask it to plan a migration from a monolithic SPA to micro-frontends (hypothetical example, not a project of mine), instead of dumping code it should first ask about the deployment pipeline and the legacy dependencies that would break, then propose a phased rollout. That is the difference I look for in a model that plans before it writes. **The catch:** It's slower. If you're used to instant responses, the thinking pause feels eternal. But for architecture decisions? I'll take accuracy over speed. ### 2. Multimodality without the duct tape Every model claims "multimodality" now. Usually, it means they duct-taped three different models together and hoped for the best. Gemini 3 is different: one model handles everything. Text, code, video, audio, images. Same weights, same architecture. **Real test I did:** I recorded a short Loom video of a UI bug (button wouldn't disable after clicking). No transcript, no code snippets. Just me clicking around and complaining in Spanish. Uploaded it. Asked: "What's broken?" It responded: - Identified the event handler wasn't preventing double-clicks - Pointed to the React component by name (this is what surprised me most) - Suggested adding a `isLoading` state with `disabled={isLoading}` I checked. It was right. The component name was correct, and it got it from a video. **The weird part:** With long videos it seemed to hallucinate component names more easily (my impression, I did not measure it). For quick bug hunts, I haven't used anything better. ### 3. Agentic Capabilities (With a Giant Asterisk) The benchmark results Google published look great on paper, but I have not verified them myself. In practice? It's... complicated. **What works:** - Running terminal commands (I let it debug a Docker networking issue, and it actually used `docker inspect` correctly) - Editing files (made a multi-file refactor without breaking tests) - Running tests and interpreting failures **What doesn't:** - It still sometimes tries to run commands that don't exist (`git commit -fix` is not a thing, Gemini) - Gets confused if your project structure is unconventional - Will confidently suggest deleting files that are actually critical (caught this more than once; always review) Trust, but verify. Always. ## Where it slots into a real workflow ### 1. Stop writing boilerplate by hand Forget "vibe coding". Let's talk about the stuff you actually hate doing. **How I would approach it (hypothetical example):** For scaffolding a CRUD API you would hand it something like: > "I need a FastAPI endpoint for user authentication. JWT tokens, refresh logic, PostgreSQL with SQLAlchemy. Follow the existing pattern from the `/products` endpoints." With an existing module as context, the pattern is clear. What usually fails with this kind of generation is import paths and environment variables. **Time saved:** I did not time it, so no numbers. **The catch:** You need a consistent codebase pattern. If your project is chaos, Gemini 3 will reflect that chaos. ### 2. Code reviews (but not how you think) I don't trust AI for full code reviews yet. Where it fits is as a "first pass filter". **How I'd use it:** paste the diff in, let it flag the **obvious** stuff (hardcoded credentials, missing error handling, SQL injection risks), then do the real review of logic and architecture yourself. That way it catches the boring stuff and you can focus on whether the code actually solves the problem. **Warning:** It will sometimes flag false positives. Once it complained about a `.env` file that was actually a `.env.example`. Don't blindly merge based on AI feedback. ### 3. Legacy code (where it can shine) Remember that old jQuery spaghetti nobody wants to touch? The huge context window Google advertises for Gemini 3 fits this well. **How I would approach it (hypothetical example, I haven't tried it on a real project):** Picture a legacy admin panel in vanilla JS. You would ask it to: - Identify which files are actually used - Create a dependency graph - Rewrite the user management module in React Expect to fix things like event handling by hand, so treat its output as a first draft. **Pro tip:** Do this incrementally. Don't ask it to rewrite your entire app. Start with one isolated module, verify it works, then move to the next. ## So... Should You Care? Look, I'm not switching from Claude entirely. For brainstorming and writing, Claude still feels more "human." But for code? Gemini 3 is convincing me. Deep Think's plan-before-code approach is what I'd use it for, and the multimodality is genuinely useful (not gimmicky). The large context window for legacy code I haven't tried on a real project yet. **My advice:** - **Try it** if you're refactoring or chasing UI bugs from a video - **Stick with Claude/GPT-4** if you need creative writing or nuanced explanations - **Don't trust it blindly:** I've caught it suggesting bad practices when it's outside its knowledge cutoff The future of development is probably agentic. But we're not there yet. Gemini 3 is a big step, though. **Related reading:** more on letting AI take the first review pass: [I tried using AI for code review on my side projects](/en/blog/gemini-flash-code-review-automation/). --- **P.S.** If you've tried Gemini 3, I'd love to hear what you think. Did it hallucinate component names for you too, or is that just me? Hit me up on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/google-antigravity-review/ Lang: en # Google Antigravity vs Cursor: Side Projects Yes, Production No > Five months on: parallel agents that pay off on boilerplate, RAM that still creeps on long sessions, and why I keep Cursor for production code. My verdict. **Short answer:** Google Antigravity is a VS Code fork built around an Agent Manager that runs several coding agents at once. Reach for it over Cursor on boilerplate, scaffolding and side projects, where parallel agents pay off and you can live with less control. Stay on Cursor for production code and careful refactors. Long sessions still eat RAM, and niche extensions and themes may not make the trip. > **Update (April 2026).** Five months on, the take shifted a bit. The day-one crashes are mostly gone, parallel agents earn their keep on boilerplate-heavy work, but the RAM creep on long sessions is still real. Verdict moved from _"give it a shot on side projects"_ to _"keep it on a second machine for the kind of work that benefits from agents working in parallel"._ Added a comparison table against Cursor / Windsurf / Copilot and an FAQ at the bottom for the questions people kept emailing me. ## Why I Even Tried This (Because Twitter Made Me Do It) Look, I wasn't planning to switch IDEs. I'm comfortable with VS Code. My setup works. My extensions work. Life is good. But then Twitter happened. Some guy posting screenshots all day long. "Antigravity is insane." "This kills Cursor." "Agent-first is the future." Classic hype cycle. But I had a free Saturday and a side project I didn't care about breaking, so... let's see what the fuss is about. Downloaded the preview. Opened it. First thought: _This isn't an IDE. This is a spaceship cockpit._ No friendly chat sidebar like Cursor. Instead you get this "Agent Manager" panel with permissions, toggles, warnings, and policies everywhere. Either this is genius, or it's going to be a beautiful disaster. ## Day 1: Installation Was Fine, But Then... Installation on macOS was actually smooth. Download, drag to Applications, done. But here's the first surprise: it looks like VS Code because it is a VS Code fork (Google shipped it on November 18, 2025, the same day as Gemini 3). Then you realize how heavily they reworked it. People online keep insisting it actually reuses Windsurf internals (there are Cascade references floating around, and Google did hire the Windsurf team), but Google has not confirmed that, so treat the Windsurf angle as a rumor, not a fact. Which means: **not all your VS Code extensions work.** I spent a good while trying to figure out why my favorite theme wasn't loading. Turns out, it's just not compatible. Most popular extensions are there (Prettier, ESLint, GitLens), but if you have niche ones... tough luck. Minor annoyance, but annoying nonetheless. Then comes the setup wizard: - Choose your model (Claude? GPT? Gemini?) - Configure agent permissions (can they run commands automatically or ask first?) - Set execution policies I'm setting up an IDE, not deploying to production. Felt heavy. I just clicked "recommended defaults" and hoped I wasn't about to nuke my project. ## Day 2: When Agents Do Things Without Asking Simple test: "Create an auth endpoint with JWT and refresh tokens." Hit enter. Went to make coffee. Came back. The endpoint code was there. Great. But there's another agent running. I look. It's writing unit tests. _I didn't ask for unit tests._ At first I thought: "Did I mistype? Did I accidentally trigger something?" Nope. The agents just... act. Independently. In parallel. One agent writes the endpoint. Another agent sees the new code and thinks "hey, this needs tests" and starts writing them. Without asking. Is this cool? Yeah, kinda. Is this unsettling? Also yeah. Because now you're sitting there thinking: _What else are they doing when I'm not looking?_ (Honest question: does anyone else get this weird feeling like someone's watching over your shoulder while these agents work? Like a reviewer breathing down your neck but in software form. Uncomfortable but useful.) ## Artifacts: Good Idea, Execution Needs Work Antigravity has this "Artifacts" feature where each agent leaves behind a record of what it did: - Code diffs - Screenshots - Browser session recordings - Reasoning logs Sounds great on paper. In reality? When you have several agents running at once, the Artifacts panel becomes a mess. Overlapping logs, diffs everywhere, screenshots from different tasks piling up. I ended up just checking the final code and hoping nothing broke silently in the background. The "audit trail" quickly becomes "audit noise." ## When the Browser Opened Itself (And Then Exploded) This was the moment I went: _okay, this IS next-level._ I asked an agent to fix a UI bug. What happened next: 1. Agent edited the component 2. Restarted the dev server 3. Opened a headless browser 4. Clicked through the UI 5. Verified the bug was gone 6. Committed the fix I did nothing. Just watched. _Cursor would never do this._ But then: memory leak. The browser process hung. IDE froze. RAM spiked. Had to force-quit. Happened **more than once**. So yeah, autonomous agents are cool until they eat all your RAM and crash your machine. ## The "Am I Being Paranoid?" Moment There's something inherently weird about handing control to agents. You're working on one part of the codebase. Meanwhile, agents are refactoring another file, writing tests for a third, and opening browsers to validate a fourth. All. At. The. Same. Time. For small, experimental projects? Maybe fine. For production code or anything with sensitive data? I'm not comfortable yet. I keep thinking: _What if one of these agents decides to refactor my entire API layer in the middle of the night?_ (Probably won't happen. But the anxiety is real.) ## Cursor vs Antigravity vs Windsurf vs Copilot (The Honest Take) Cursor feels like pair programming with someone senior. They suggest, you decide, nothing happens unless you say so. Antigravity is more like hiring that one intern who ships faster than everyone else but also refactors your entire folder structure in the middle of the night because "it made more sense this way." You love the output. You hate the surprises. Here's how the four AI-IDEs I actually use stack up after extended trials: | | **Antigravity** | **Cursor** | **Windsurf** | **GitHub Copilot** | |---|---|---|---|---| | **Agent style** | Multiple, autonomous, parallel | Single, supervised, you-confirm-each-step | Cascade flow with manual checkpoints | Inline suggestions + chat | | **Best for** | Boilerplate, scaffolding, side projects | Production code, careful refactors | Mid-size features with explicit phases | Day-to-day completions in any editor | | **Models** | Gemini 3 Pro/Flash, Claude Sonnet 4.6 & Opus 4.6 (bring your own Anthropic key in preview), GPT-OSS-120B | Claude, GPT, Gemini | Claude, GPT, Gemini | OpenAI / GPT family | | **Browser automation** | Yes (built-in headless verify) | No | Limited | No | | **Editor base** | VS Code fork (Windsurf reuse is an unconfirmed community theory) | VS Code fork | Custom (Codeium) | Plugin (any editor) | | **Extension compat** | Partial (most VS Code OK, themes flaky) | Full VS Code | Custom marketplace | N/A (host editor's own) | | **RAM at idle** | High in my use (not measured) | Not measured | Not measured | Not measured | | **RAM under load** | Spikes hard, occasional leaks | Stable | Stable | Negligible | | **Pricing** | Free preview (rate-limited) | Paid (Pro plan) | $20 / mo Pro (raised from $15 in March 2026) | Paid (individual and Business plans) | | **Friction to commit** | Almost zero (agent will do it) | Medium (explicit accept) | Medium (phase reviews) | High (you do it) | | **Best mental model** | "Hire an intern" | "Pair with a senior" | "Run a checklist" | "Spell-check, but for code" | The short version: **pick by how much autonomy you can stomach**. Antigravity gives the most, Copilot the least, Cursor and Windsurf land in between with different defaults. ## Do I Recommend It? Honestly, I Don't Know Yet Ask me again in a month. Right now I'm mostly impressed (the parallel agents thing IS cool), fairly frustrated (missing extensions, memory leaks, too much noise), and a little paranoid (what are these agents doing when I'm not watching?). If you're writing a lot of CRUD endpoints, forms, and boilerplate APIs, and you have a side project you genuinely don't care about breaking, yeah, give it a shot. You'll probably have fun. If you're working on anything production-critical, or you're the kind of person who gets anxious when tools do things without asking, stay away for now. Seriously. This thing will stress you out. I'm keeping it installed. On a separate machine. Just in case. That probably tells you everything you need to know. ## Who Should Actually Use This? After five months of on-and-off use, here is the honest split: **Try Antigravity if you:** - Spin up a lot of CRUD APIs, internal tools, prototypes, or boilerplate-heavy features. - Have a side project where _shipped_ matters more than _supervised_. - Want to see what a multi-agent IDE feels like before the rest of the industry catches up. - Already keep your work machine and your experiments machine separate. **Skip it (for now) if you:** - Work in regulated codebases or anything with sensitive data: the autonomy is real and the audit trail is still messy. - Rely on a deep VS Code extension setup that includes anything niche. - Are easily stressed by tools doing things without asking. This thing _will_ stress you out. - Run a low-RAM laptop. The leaks I hit aren't theoretical. **Worth checking back later if you:** - Liked the idea but waited for stability. - Use Cursor today and want a clean side-by-side once Antigravity exits preview. ## Sources For the claims I couldn't verify first-hand (the VS Code fork, the model roster, the pricing), here is what I leaned on: - [Build with Google Antigravity, our new agentic development platform](https://developers.googleblog.com/build-with-google-antigravity-our-new-agentic-development-platform/) (Google Developers Blog) for the November 18, 2025 launch, the agent-first design, and model optionality across Gemini 3 Pro, Claude, and OpenAI's GPT-OSS. - [Google Antigravity](https://en.wikipedia.org/wiki/Google_Antigravity) (Wikipedia) for the "fork of VS Code" framing and the note that Google has not publicly confirmed the exact technical relationship. - [Google Antigravity models](https://antigravity.google/docs/models) (official docs) for the current model list: Gemini 3 Pro/Flash, Claude Sonnet 4.6 and Opus 4.6, GPT-OSS-120B. - [Windsurf Pricing in 2026](https://www.cloudzero.com/blog/windsurf-pricing/) (CloudZero) for the Windsurf Pro move from $15 to $20/month in March 2026. **Related reading:** agents that act on their own is exactly where the whole field is heading. The bigger picture is in [Stop Prompting Your Agent. Start Writing Loops.](/en/blog/stop-prompting-write-loops/) --- **P.S.** If you've tried Antigravity, let me know: Did you hit the same memory issues? Did agents refactor stuff without asking? Am I being paranoid or is this actually a thing? Hit me up on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). ## FAQ **Is Google Antigravity free?** It is currently a free preview with rate limits. Google has hinted at a paid tier once it leaves preview but has not published pricing yet. Expect something competitive with Cursor's paid plans. **Does Antigravity replace VS Code?** Not really. It is a VS Code fork, so it looks like VS Code and most popular extensions (Prettier, ESLint, GitLens) work, but theme and niche extensions often do not. If your VS Code setup is heavily customised, treat Antigravity as a separate tool, not a drop-in replacement. **Does GitLens (and my other VS Code extensions) work in Antigravity?** Most of the popular ones do. In my setup Prettier, ESLint, and GitLens all loaded and worked normally. Because Antigravity is a VS Code fork rather than stock VS Code, the gaps show up in themes and niche extensions rather than the everyday staples. **What models does Antigravity support?** At launch the roster is Gemini 3 Pro and Gemini 3 Flash, Anthropic's Claude Sonnet 4.6 and Opus 4.6, and OpenAI's open-weights `GPT-OSS-120B`. In the free preview the Claude models need your own Anthropic API key. You pick one in the setup wizard and switch per-agent later. **Is Antigravity safe to use on a real project?** For experimental and side projects, yes. For anything production-critical or compliance-sensitive, not yet: the agents act independently in parallel, the artifacts panel gets noisy fast, and the memory issues still bite on long sessions. If you do use it on real work, scope agent permissions tightly in the setup wizard and keep version control aggressive. **Antigravity vs Cursor: which one should I pick in 2026?** Cursor if you want supervised pair-programming with explicit accept-each-suggestion flow. Antigravity if you want multiple agents working in parallel and you can stomach the loss of fine-grained control. They optimise for different anxieties: Cursor for keeping control, Antigravity for shipping faster. **Has the memory leak been fixed, and can Antigravity run a browser by itself?** Memory usage is significantly better than at launch, though long sessions with multiple agents and browser automation still spike RAM hard. And yes: the agent can open a headless browser, click through the UI, verify a fix, and commit. --- URL: https://www.oscargallegoruiz.com/blog/gemini-3-guia-desarrollador/ Lang: es # Gemini 3 Pro: una semana de pruebas como desarrollador > Una semana con Gemini 3 Pro: Deep Think planificando una migración de ejemplo, un bug diagnosticado desde un vídeo y el lado agéntico que hay que vigilar. Llevo una semana probando Gemini 3 Pro, y ¿sabes qué? Me ha sorprendido lo bien que va. Justo cuando me había acostumbrado a mi workflow con Claude/GPT-4, Google lanza esto en noviembre y toca reajustarlo todo otra vez. Pero vamos al grano: después de obligarme a reconstruir una feature mía que ya tenía funcionando (sí, reescribí código que funcionaba solo para probar esto), entiendo el hype. No es el típico release de "un poco mejor en benchmarks". Deep Think y multimodalidad real (no la fake de siempre) cambian cómo puedes trabajar. Te explico. ## Lo que de verdad ha cambiado esta vez ### 1. Deep Think, o por qué ahora se para a pensar ¿Sabes cómo los modelos anteriores simplemente empezaban a soltar tokens? En medio del pensamiento, cero planificación, solo predicción de palabras. Gemini 3 realmente se para. Piensa. Verás "[Thinking...]" en la respuesta de la API, y al principio pensé que se me había caído la conexión. Pues no. Realmente está gastando tiempo de cómputo planificando la respuesta antes de soltarla. **Qué busco:** Si le pides planificar la migración de una SPA monolítica a micro-frontends (ejemplo hipotético, no un proyecto mío), en vez de soltar código lo que debería hacer es preguntar primero por el pipeline de deploy y por las dependencias legacy que se romperían, y proponer un rollout por fases. Esa es la diferencia que busco en un modelo que planifica antes de escribir. **El pero:** Es más lento. Si estás acostumbrado a respuestas instantáneas, esa pausa mientras piensa se hace eterna. Pero para decisiones de arquitectura, prefiero precisión antes que velocidad. ### 2. Multimodalidad sin cinta aislante Todos los modelos ahora dicen tener "multimodalidad". Normalmente significa que pegaron tres modelos diferentes con cinta aislante y cruzaron los dedos. Gemini 3 es diferente: un solo modelo lo maneja todo. Texto, código, vídeo, audio, imágenes. Mismos pesos, misma arquitectura. **Test real que hice:** Grabé un vídeo corto en Loom de un bug en la UI (un botón que no se deshabilitaba al hacer clic). Sin transcripción, sin snippets de código. Solo yo haciendo clic por ahí y quejándome en español. Lo subí. Pregunté: "¿Qué está roto?" Respondió: - Identificó que el event handler no estaba previniendo doble-click - Señaló el componente React por nombre (esto fue lo que más me sorprendió) - Sugirió añadir un estado `isLoading` con `disabled={isLoading}` Lo comprobé. Tenía razón. El nombre del componente era correcto, y lo sacó de un vídeo. **La parte rara:** Con vídeos largos me pareció que alucinaba nombres de componentes con más facilidad (impresión mía, no lo medí). Para cazar bugs rápido, no he usado nada mejor. ### 3. Capacidades de agente (con un asterisco gigante) Los resultados en benchmarks que publicó Google pintan muy bien sobre el papel, pero no los he comprobado yo. En la práctica... es complicado. **Lo que funciona:** - Ejecutar comandos de terminal (le dejé debuggear un problema de networking en Docker y usó `docker inspect` correctamente) - Editar archivos (hizo un refactor de varios archivos sin romper tests) - Ejecutar tests e interpretar fallos **Lo que no:** - Todavía intenta ejecutar comandos que no existen (`git commit -fix` no es real, Gemini) - Se lía si la estructura de tu proyecto es poco convencional - Sugiere con confianza borrar archivos que en realidad son críticos (lo pillé más de una vez; revisa siempre) Confía, pero verifica. Siempre. ## Dónde encaja en un workflow real ### 1. Deja de escribir boilerplate a mano Olvídate del "vibe coding". Hablemos de lo que de verdad odias hacer. **Cómo lo plantearía (ejemplo hipotético):** Para el scaffolding de una API CRUD le pasarías algo así: > "Necesito un endpoint de FastAPI para autenticación de usuarios. Tokens JWT, lógica de refresh, PostgreSQL con SQLAlchemy. Sigue el patrón existente de los endpoints de `/products`." Con un módulo existente como contexto, el patrón queda claro. Lo que suele fallar con este tipo de generación son las rutas de imports y las variables de entorno. **Tiempo ahorrado:** no lo cronometré, así que no te doy cifras. **El truco:** Necesitas un patrón de codebase consistente. Si tu proyecto es un caos, Gemini 3 va a reflejar ese caos. ### 2. Code reviews (pero no como piensas) Aún no confío en la IA para code reviews completos. Donde encaja es como "filtro de primera pasada". **Cómo lo usaría:** pegas el diff, dejas que marque lo **obvio** (credenciales hardcodeadas, falta de error handling, riesgos de SQL injection) y la review real de lógica y arquitectura la haces tú. Así pilla lo aburrido y tú te centras en si el código resuelve el problema. **Aviso:** A veces marca falsos positivos. En alguna ocasión se quejó de un archivo `.env` que en realidad era `.env.example`. No hagas merge ciegamente basándote en feedback de IA. ### 3. Código legacy (donde puede brillar) ¿Recuerdas ese espagueti de jQuery de hace años que nadie quiere tocar? El context window enorme que anuncia Google para Gemini 3 encaja bien con esto. **Cómo lo plantearía (ejemplo hipotético, no lo he probado con un proyecto real):** Imagina un panel de admin legacy en vanilla JS. Le pedirías que: - Identificara qué archivos se usan realmente - Creara un grafo de dependencias - Reescribiera el módulo de gestión de usuarios en React Lo normal es que haya que arreglar a mano cosas como el manejo de eventos, así que trata su salida como un primer borrador. **Pro tip:** Haz esto incrementalmente. No le pidas que reescriba toda tu app. Empieza con un módulo aislado, verifica que funciona, y luego sigue con el siguiente. ## Entonces... ¿te debería importar? Mira, no voy a dejar Claude del todo. Para brainstorming y escribir, Claude sigue sintiéndose más "humano". Pero ¿para código? Gemini 3 me está convenciendo. Para lo que usaría Deep Think es para eso, planificar antes de escribir código, y la multimodalidad es genuinamente útil (no un gimmick). Lo del context window grande para código legacy todavía no lo he probado con un proyecto real. **Mi consejo:** - **Pruébalo** si estás haciendo refactoring o cazando bugs de UI desde un vídeo - **Quédate con Claude/GPT-4** si necesitas escritura creativa o explicaciones matizadas - **No confíes ciegamente:** le he pillado sugiriendo malas prácticas cuando está fuera de su knowledge cutoff El futuro del desarrollo probablemente es agéntico. Pero aún no estamos ahí. Gemini 3 es un paso grande, eso sí. **Lectura relacionada:** más sobre dejar que la IA haga la primera pasada de review: [probé usar IA para revisión de código en mis proyectos](/blog/gemini-flash-code-review-automatizado/). --- **P.D.** Si has probado Gemini 3, me encantaría saber qué piensas. ¿También te alucinó nombres de componentes, o soy solo yo? Escríbeme en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/resena-google-antigravity/ Lang: es # Google Antigravity: sí a side projects, no a producción > Google Antigravity tras una semana a fondo y cinco meses de uso: agentes en paralelo que compensan, RAM que crece y extensiones de VS Code que aguantan. **Respuesta corta:** Google Antigravity es un fork de VS Code que gira en torno a un Agent Manager que lanza varios agentes de código a la vez. Tira de él antes que de Cursor para boilerplate, scaffolding y side projects, donde los agentes en paralelo compensan y te da igual tener menos control. Para código de producción y refactors cuidadosos, quédate con Cursor. En sesiones largas se sigue comiendo la RAM, y algunas extensiones y temas de VS Code menos conocidos directamente no cargan. > **Actualización (Abril 2026).** Cinco meses después, mi opinión ha cambiado un poco. Los crashes del primer día han desaparecido en su mayoría, los agentes en paralelo se ganan el sueldo cuando hay mucho boilerplate, pero el RAM creep en sesiones largas sigue siendo real. El veredicto pasó de _"pruébalo en side projects"_ a _"tenlo en una segunda máquina para el tipo de trabajo que se beneficia de agentes corriendo en paralelo"._ He añadido una tabla comparativa con Cursor / Windsurf / Copilot y una FAQ al final con las preguntas que más me llegan por email. ## Por qué probé esto (porque Twitter me obligó) Mira, no tenía pensado cambiar de IDE. Estoy cómodo con VS Code. Mi setup funciona. Mis extensiones funcionan. Todo bien. Pero luego llegó Twitter. Un tío posteando screenshots a todas horas. "Antigravity es una locura." "Esto mata a Cursor." "El futuro es agent-first." El típico hype. Pero tenía un sábado libre y un side project que me daba igual romper, así que... vamos a ver de qué va esto. Descargué el preview. Lo abrí. Primera impresión: _Esto no es un IDE. Esto es la cabina de una nave espacial._ Nada de chat amigable como Cursor. En su lugar tienes este panel de "Agent Manager" con permisos, toggles, warnings y policies por todas partes. O esto es genial, o va a ser un desastre precioso. ## Día 1: la instalación bien, pero luego... La instalación en macOS fue fluida. Descargar, arrastrar a Aplicaciones, listo. Pero aquí viene la primera sorpresa: parece VS Code porque es un fork de VS Code (Google lo lanzó el 18 de noviembre de 2025, el mismo día que Gemini 3). Luego te das cuenta de lo mucho que lo han reescrito. Por internet hay gente que insiste en que en realidad reutiliza tripas de Windsurf (se ven referencias a Cascade por ahí, y Google fichó al equipo de Windsurf), pero Google no lo ha confirmado, así que toma lo de Windsurf como rumor, no como dato. Lo que significa: **no todas tus extensiones de VS Code funcionan.** Me pasé un buen rato intentando entender por qué mi theme favorito no cargaba. Resulta que simplemente no es compatible. La mayoría de extensiones populares están (Prettier, ESLint, GitLens), pero si tienes alguna de nicho... mala suerte. Molesto, pero bueno. Luego viene el wizard de setup: - Elige tu modelo (¿Claude? ¿GPT? ¿Gemini?) - Configura permisos de agentes (¿pueden ejecutar comandos automáticamente o preguntan primero?) - Define políticas de ejecución Estoy configurando un IDE, no haciendo un deploy a producción. Se me hizo pesado. Hice clic en "defaults recomendados" y crucé los dedos para no cepillarme el proyecto. ## Día 2: cuando los agentes hacen cosas sin preguntar Test simple: "Crea un endpoint de auth con JWT y refresh tokens." Enter. Fui a por café. Volví. El código del endpoint estaba ahí. Genial. Pero hay otro agente corriendo. Miro. Está escribiendo tests unitarios. _Yo no pedí tests unitarios._ Al principio pensé: "¿Me habré equivocado al escribir? ¿Habré triggereado algo sin querer?" Nada. Los agentes simplemente... actúan. Independientemente. En paralelo. Un agente escribe el endpoint. Otro agente ve el código nuevo y piensa "eh, esto necesita tests" y se pone a escribirlos. Sin preguntar. ¿Mola? Sí, un poco. ¿Inquieta? También. Porque ahora estás ahí sentado pensando: _¿Qué más están haciendo cuando no miro?_ (Pregunta honesta: ¿alguien más tiene esta sensación rara de que alguien te está mirando por encima del hombro mientras estos agentes trabajan? Como un revisor respirándote en el cuello pero en versión software. Incómodo pero útil.) ## Artifacts: buena idea, ejecución mejorable Antigravity tiene esta feature de "Artifacts" donde cada agente te deja un registro de lo que hizo: - Diffs de código - Screenshots - Grabaciones de sesiones del browser - Logs de razonamiento Suena bien sobre el papel. ¿En la práctica? Cuando tienes varios agentes corriendo a la vez, el panel de Artifacts se convierte en un caos. Logs solapados, diffs por todas partes, screenshots de diferentes tareas apilándose. Acabé simplemente revisando el código final y cruzando los dedos para que nada se hubiera roto en silencio. El "audit trail" se convierte rápidamente en "ruido de auditoría". ## Cuando el browser se abrió solo (y luego explotó) Este fue el momento en el que pensé: _vale, esto SÍ es next-level._ Le pedí a un agente que arreglara un bug en la UI. Lo que pasó después: 1. El agente editó el componente 2. Reinició el dev server 3. Abrió un headless browser 4. Hizo clic por la UI 5. Verificó que el bug había desaparecido 6. Hizo commit del fix Yo no hice nada. Solo mirar. _Cursor nunca haría esto._ Pero luego: memory leak. El proceso del browser se colgó. El IDE se congeló. La RAM se disparó. Tuve que hacer force-quit. Me pasó **más de una vez**. Así que sí, los agentes autónomos molan hasta que se comen toda tu RAM y te crashean la máquina. ## El momento "¿Estoy siendo paranoico?" Hay algo inherentemente raro en ceder el control a los agentes. Estás trabajando en una parte del codebase. Mientras tanto, los agentes están refactorizando otro archivo, escribiendo tests para un tercero, y abriendo browsers para validar un cuarto. Todo. Al. Mismo. Tiempo. ¿Para proyectos pequeños y experimentales? Quizás vale. ¿Para código de producción o cualquier cosa con datos sensibles? Aún no me fío. Sigo pensando: _¿Y si uno de estos agentes decide refactorizar toda mi capa de API de madrugada?_ (Probablemente no pase. Pero la ansiedad es real.) Lo que pongo alrededor de un agente para vigilarlo lo cuento en [qué es harness engineering](/blog/harness-engineering-por-que-falla-tu-agente/). ## Cursor vs Antigravity vs Windsurf vs Copilot (la versión honesta) Cursor es como hacer pair programming con alguien senior. Sugiere, tú decides, no pasa nada hasta que tú dices. Antigravity es más como contratar a ese intern que shippea más rápido que los demás pero también reorganiza toda tu estructura de carpetas de madrugada porque "tenía más sentido así". Te encanta el resultado. Odias las sorpresas. Así quedan los cuatro AI-IDEs que uso de verdad después de pruebas largas: | | **Antigravity** | **Cursor** | **Windsurf** | **GitHub Copilot** | |---|---|---|---|---| | **Estilo de agente** | Múltiples, autónomos, en paralelo | Único, supervisado, confirmas cada paso | Cascade con checkpoints manuales | Sugerencias inline + chat | | **Mejor para** | Boilerplate, scaffolding, side projects | Código de producción, refactors cuidadosos | Features medianas con fases explícitas | Completados día a día en cualquier editor | | **Modelos** | Gemini 3 Pro/Flash, Claude Sonnet 4.6 y Opus 4.6 (con tu propia API key de Anthropic en el preview), GPT-OSS-120B | Claude, GPT, Gemini | Claude, GPT, Gemini | Familia OpenAI / GPT | | **Automatización del browser** | Sí (verifica con headless integrado) | No | Limitada | No | | **Editor base** | Fork de VS Code (lo de reutilizar Windsurf es una teoría de la comunidad sin confirmar) | Fork de VS Code | Custom (Codeium) | Plugin (cualquier editor) | | **Compatibilidad de extensiones** | Parcial (la mayoría VS Code OK, themes flojos) | VS Code completo | Marketplace propio | N/A (el del editor host) | | **RAM en idle** | Alta en mi uso (sin medir) | Sin medir | Sin medir | Sin medir | | **RAM bajo carga** | Picos fuertes, leaks ocasionales | Estable | Estable | Despreciable | | **Precio** | Preview gratis (con rate limit) | De pago (plan Pro) | 20 $/mes Pro (subió desde 15 $ en marzo de 2026) | De pago (planes individual y Business) | | **Fricción para commitear** | Casi cero (el agente lo hace) | Media (aceptas explícitamente) | Media (revisión por fases) | Alta (lo haces tú) | | **Modelo mental** | "Contratas a un intern" | "Pair con un senior" | "Sigues una checklist" | "Spell-check, pero para código" | Resumen rápido: **elige según cuánta autonomía aguantas**. Antigravity te da la máxima, Copilot la mínima, Cursor y Windsurf van por el medio con defaults distintos. ## ¿Lo recomiendo? Honestamente, aún no lo sé Pregúntame otra vez en un mes. Ahora mismo estoy sobre todo impresionado (lo de los agentes en paralelo SÍ mola), bastante frustrado (extensiones que faltan, memory leaks, demasiado ruido) y un poco paranoico (¿qué están haciendo estos agentes cuando no miro?). Si picas muchos endpoints CRUD, formularios y APIs con boilerplate, y tienes un side project que de verdad te da igual romper, sí, dale una oportunidad. Probablemente te lo pases bien. Si trabajas en algo crítico de producción, o eres de los que se ponen ansiosos cuando las herramientas hacen cosas sin preguntar, mantente lejos de momento. En serio. Esto va a estresarte. Lo tengo instalado. En una máquina separada. Por si acaso. Eso probablemente te dice todo lo que necesitas saber. ## ¿Para quién es esto realmente? Tras cinco meses usándolo a ratos, este es el reparto honesto: **Pruébalo si:** - Picas mucha CRUD API, herramientas internas, prototipos o features con mucho boilerplate. - Tienes un side project donde _shipped_ pesa más que _supervisado_. - Te apetece ver cómo se siente un IDE multi-agente antes de que lo haga el resto del sector. - Ya tienes separadas la máquina de trabajo y la de experimentos. **Pásalo (de momento) si:** - Trabajas en código regulado o cualquier cosa con datos sensibles: la autonomía es real y el audit trail aún es un desastre. - Dependes de un setup denso de extensiones de VS Code, especialmente las de nicho. - Te pone ansioso que las herramientas hagan cosas sin preguntar. Esto _va_ a estresarte. - Tienes un portátil con poca RAM. Los leaks no son teóricos. **Vuélvelo a mirar más adelante si:** - Te interesa la idea pero esperas a que estabilice. - Hoy usas Cursor y quieres una comparativa side-by-side cuando Antigravity salga del preview. ## Fuentes Para lo que no pude verificar de primera mano (que es un fork de VS Code, el catálogo de modelos, los precios), esto es en lo que me apoyé: - [Build with Google Antigravity, our new agentic development platform](https://developers.googleblog.com/build-with-google-antigravity-our-new-agentic-development-platform/) (Google Developers Blog) para el lanzamiento del 18 de noviembre de 2025, el diseño agent-first y la opción de modelos entre Gemini 3 Pro, Claude y el GPT-OSS de OpenAI. - [Google Antigravity](https://en.wikipedia.org/wiki/Google_Antigravity) (Wikipedia) para lo del "fork de VS Code" y la nota de que Google no ha confirmado públicamente la relación técnica exacta. - [Google Antigravity models](https://antigravity.google/docs/models) (documentación oficial) para la lista actual de modelos: Gemini 3 Pro/Flash, Claude Sonnet 4.6 y Opus 4.6, GPT-OSS-120B. - [Windsurf Pricing in 2026](https://www.cloudzero.com/blog/windsurf-pricing/) (CloudZero) para el salto de Windsurf Pro de 15 $ a 20 $/mes en marzo de 2026. **Lectura relacionada:** agentes que actúan por su cuenta es exactamente hacia donde va todo el sector. La foto grande está en [Deja de Promptear a tu Agente. Escribe Loops.](/blog/deja-de-promptear-escribe-loops/) --- **P.D.** Si has probado Antigravity, cuéntame: ¿Te has encontrado los mismos problemas de memoria? ¿Los agentes te han refactorizado cosas sin preguntar? ¿Soy paranoico o esto es real? Escríbeme en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). ## FAQ **¿Google Antigravity es gratis?** Ahora mismo es un preview gratuito con rate limits. Google ha dejado caer que habrá tier de pago cuando salga del preview, pero todavía no hay precios públicos. Espera algo competitivo con los planes de pago de Cursor. **¿Antigravity reemplaza a VS Code?** No del todo. Es un fork de VS Code, así que parece VS Code y la mayoría de extensiones populares (Prettier, ESLint, GitLens) funcionan, pero los themes y muchas extensiones de nicho no. Si tu setup de VS Code está muy customizado, trátalo como una herramienta aparte, no como un drop-in replacement. **¿Funciona GitLens (y mis otras extensiones de VS Code) en Antigravity?** La mayoría de las populares sí. En mi setup Prettier, ESLint y GitLens cargaron y funcionaron con normalidad. Como Antigravity es un fork de VS Code y no el VS Code original, los huecos aparecen en themes y extensiones de nicho, no en las del día a día. **¿Qué modelos soporta Antigravity?** De salida el catálogo es Gemini 3 Pro y Gemini 3 Flash, Claude Sonnet 4.6 y Opus 4.6 de Anthropic, y `GPT-OSS-120B`, el modelo open-weights de OpenAI. En el preview gratuito los modelos de Claude piden tu propia API key de Anthropic. Eliges uno en el wizard de setup y luego cambias por agente. **¿Es seguro usar Antigravity en un proyecto real?** Para experimentos y side projects, sí. Para producción crítica o código sujeto a compliance, todavía no: los agentes actúan en paralelo, el panel de Artifacts se ensucia rápido y los problemas de memoria siguen apareciendo en sesiones largas. Si lo usas en trabajo real, restringe los permisos de los agentes en el wizard y mantén el control de versiones agresivo. **Antigravity vs Cursor: ¿cuál elijo en 2026?** Cursor si quieres pair programming supervisado con flujo de aceptar cada sugerencia. Antigravity si quieres varios agentes trabajando en paralelo y aguantas perder control fino. Optimizan para ansiedades distintas: Cursor para mantener el control, Antigravity para shippear más rápido. **¿Han arreglado el memory leak y puede ejecutar un browser por sí solo?** El consumo de RAM está mejor que en el lanzamiento, pero sesiones largas con varios agentes y automatización del browser todavía hacen picos fuertes de RAM. Y sí: el agente abre un browser headless, clickea por la UI, verifica que el fix funciona y hace commit. --- URL: https://www.oscargallegoruiz.com/en/blog/ai-prompt-engineering-tips/ Lang: en # One-Shot Prompting: Better AI Answers With One Example > One-shot prompting and context placement: examples for classification, code refactoring and JSON extraction, with checks for output errors and missing data. When AI gives me a vague answer, I first check what I asked for and what context I provided. Two techniques you can test are **one-shot prompting** (give the model one good example) and **context placement** (put critical instructions at the beginning or end). Neither requires a framework or fine-tuning; results depend on the model and task. ## One good example beats a paragraph of instructions One-shot prompting means exactly what it sounds like: you include one high-quality example in your prompt and let the model generalize from it. Think of pair programming with a coworker. You don't hand them a spec on "how we format things here". You say: look at how we did this last time, now build the new one the same way. An example gives the model a concrete pattern for format, tone or transformation. It can clarify what a description leaves ambiguous, but it does not replace test cases: check inputs that differ from the example too. ### Sentiment analysis: show the format once Say you want customer reviews classified as positive, negative, or neutral. The example shows how to handle a review with mixed opinions. **Prompt:** > You are a sentiment analysis expert. Classify the following customer review into one of three categories: "Positive", "Negative", or "Neutral". > > **Example:** > **Review:** "The product arrived quickly, but the packaging was damaged. The item itself works perfectly." > **Sentiment:** "Neutral" > > Now, classify the sentiment of this review: > > **Review to Classify:** "This software update is terrible! It broke half my features and is incredibly slow now." ### The example does the heavy lifting, so pick it well - Choose it carefully: it sets the pattern for everything that follows. - Make it representative. An edge case as your only example teaches the model the edge case. - Include every element you want in the output. - Add explicit instructions where the example alone is ambiguous. - Don't overcomplicate it. The model generalizes the pattern. ### Code refactoring: the pattern is the prompt Here's a one-shot prompt that refactors JavaScript from promise chains to async/await. **Prompt:** > You are an expert JavaScript developer. Refactor the following function to use `async/await` syntax while keeping the logic identical. > > **Example:** > **Original Code:** > > ```javascript > function fetchData(url) { > return fetch(url) > .then((response) => { > if (!response.ok) { > throw new Error("Network response was not ok"); > } > return response.json(); > }) > .then((data) => { > console.log("Data received:", data); > return data; > }) > .catch((error) => { > console.error("Fetch error:", error); > throw error; > }); > } > ``` > > **Refactored Code:** > > ```javascript > async function fetchData(url) { > try { > const response = await fetch(url); > if (!response.ok) { > throw new Error("Network response was not ok"); > } > const data = await response.json(); > console.log("Data received:", data); > return data; > } catch (error) { > console.error("Fetch error:", error); > throw error; > } > } > ``` > > Now, refactor this function: > > **Function to Refactor:** > > ```javascript > function getUser(id) { > return database.findUser(id).then((user) => { > return getPermissions(user.role).then((permissions) => { > user.permissions = permissions; > return user; > }); > }); > } > ``` ## Data extraction: an example to define the structure This is where one-shot earns its keep. Show the model the input text and the exact JSON you want back, and you turn unstructured text into something your code can parse without ceremony. The example clarifies the expected structure, but it guarantees neither valid JSON nor correct data. Parse the response and validate its fields against a schema before storing it. Avoid filling missing data with guesses. **Prompt:** > You are a data extraction specialist. Your task is to extract specific information from a user's message and format it as a JSON object. > > **EXAMPLE:** > **Text:** "Hi, I'd like to book a flight for two adults from New York (JFK) to Los Angeles (LAX) on December 25th, 2025. I'd prefer a morning flight on Delta." > > **JSON Output:** > > ```json > { > "intent": "book_flight", > "passengers": { > "adults": 2, > "children": 0 > }, > "origin": { > "city": "New York", > "airport_code": "JFK" > }, > "destination": { > "city": "Los Angeles", > "airport_code": "LAX" > }, > "date": "2025-12-25", > "preferences": { > "time_of_day": "morning", > "airline": "Delta" > } > } > ``` > > --- > > **YOUR TASK:** Extract the relevant information from the following text and format it as a JSON object, following the example's structure. > > **Text to Process:** "Hi, I'd like to book a flight for three adults from Austin (AUS) to New York (JFK) on March 10th, 2026. We'd prefer an afternoon flight with American Airlines." ## Information in the middle of a long context can get lost Context windows keep growing, and the marketing implies you can throw anything at them and the model will sort it out. The research says otherwise. ["Lost in the Middle: How Language Models Use Long Contexts"](https://arxiv.org/abs/2307.03172) found that models perform best when the critical information sits at the **beginning** or **end** of the context window. For the tasks and models in the study, performance could fall when relevant information sat in the middle of the context. That does not show that every current model ignores that part of a prompt: test the model you use with your own documents. If you build a RAG pipeline that adds documents to a prompt, test different positions for relevant information. A large window lets you include more text; it does not guarantee that the model uses every passage well. ### A constraint buried mid-document gets silently dropped Picture a task where you summarize a long document under one specific constraint: the summary must include a particular piece of information (a product code, a key date, someone's name) that might appear exactly once, in the middle of the text. Put the constraint ("Include product code XYZ123 in the summary") in the middle of a long document and the model may skate right past it, handing you a summary that misses the one detail you needed. To make it stick, place it at the beginning or end of your prompt, clearly separated from the document itself. **Prompt:** > **IMPORTANT CONSTRAINT:** Your summary MUST include the product code "PROD-789". > > Summarize the following document in 3-4 sentences, focusing on the key features and benefits. > > [Long Document Content Here, where "PROD-789" might be mentioned once in the middle] > > Alternatively, you could place the constraint at the very end: > > Summarize the following document in 3-4 sentences, focusing on the key features and benefits. > > [Long Document Content Here] > > **IMPORTANT CONSTRAINT:** Ensure the summary mentions product code "PROD-789". ### Where to put what - Start fresh when you can: a new chat is a focused context. - Front-load the critical instructions, data, or questions. - New important information? Append it to the end. Don't splice it into the middle. - The middle is for the supplementary stuff the model can afford to skim. Test the same case with and without an example, and move the critical instruction to the beginning or end. Compare the answers and check whether they meet the task before using the prompt in your application. **Related reading:** once your prompts behave, the next rung is not writing them at all: [stop prompting your agent, start writing loops](/en/blog/stop-prompting-write-loops/). --- **P.S.** Got a prompt that refuses to behave no matter where you put the context? Show me on [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/blog/consejos-ingenieria-prompts-ai/ Lang: es # One-shot prompting: un buen ejemplo gana a las instrucciones > One-shot prompting es darle al modelo un único ejemplo de calidad. Clasificación, refactorización y JSON, y cómo validar la salida antes de usarla. Cuando la IA me devuelve una respuesta vaga, reviso primero qué le he pedido y qué contexto le he dado. Dos técnicas que puedes probar son el **one-shot prompting** (darle al modelo un único buen ejemplo) y la **colocación del contexto** (poner las instrucciones críticas al principio o al final). No requieren frameworks ni fine-tuning; el resultado depende del modelo y de la tarea. ## Un buen ejemplo vale más que un párrafo de instrucciones One-shot prompting significa exactamente lo que parece: incluyes un solo ejemplo de calidad en el prompt y dejas que el modelo generalice a partir de él. Piensa en pair programming con un compañero. No le pasas una especificación de "cómo formateamos aquí". Le dices: mira cómo hicimos esto la última vez, ahora haz lo nuevo igual. Un ejemplo le da al modelo un patrón concreto de formato, tono o transformación. Puede aclarar lo que una descripción deja ambiguo, pero no sustituye los casos de prueba: comprueba también las entradas que se alejan del ejemplo. ### Análisis de sentimiento: enseña el formato una vez Supón que quieres clasificar reseñas de clientes como positivas, negativas o neutras. El ejemplo muestra cómo tratar una reseña con opiniones mezcladas. **Prompt:** > Eres un experto en análisis de sentimiento. Clasifica la siguiente reseña de cliente en una de tres categorías: "Positiva", "Negativa" o "Neutra". > > **Ejemplo:** > **Reseña:** "El producto llegó rápidamente, pero el embalaje estaba dañado. El artículo en sí funciona perfectamente." > **Sentimiento:** "Neutra" > > Ahora, clasifica el sentimiento de esta reseña: > > **Reseña a Clasificar:** "¡Esta actualización de software es terrible! Rompió la mitad de mis funciones y ahora es increíblemente lenta." ### El ejemplo hace el trabajo pesado, así que elígelo bien - Elígelo con cuidado: marca el patrón de todo lo que viene después. - Que sea representativo. Un caso extremo como único ejemplo le enseña al modelo el caso extremo. - Incluye todos los elementos que quieres en la salida. - Añade instrucciones explícitas donde el ejemplo solo se quede ambiguo. - No lo compliques. El modelo generaliza el patrón. ### Refactorización de código: el patrón es el prompt Aquí tienes un prompt one-shot que refactoriza JavaScript de cadenas de promesas a async/await. **Prompt:** > Eres un desarrollador experto en JavaScript. Refactoriza la siguiente función para usar la sintaxis `async/await` manteniendo la lógica idéntica. > > **Ejemplo:** > **Código Original:** > > ```javascript > function fetchData(url) { > return fetch(url) > .then((response) => { > if (!response.ok) { > throw new Error("La respuesta de la red no fue correcta"); > } > return response.json(); > }) > .then((data) => { > console.log("Datos recibidos:", data); > return data; > }) > .catch((error) => { > console.error("Error en fetch:", error); > throw error; > }); > } > ``` > > **Código Refactorizado:** > > ```javascript > async function fetchData(url) { > try { > const response = await fetch(url); > if (!response.ok) { > throw new Error("La respuesta de la red no fue correcta"); > } > const data = await response.json(); > console.log("Datos recibidos:", data); > return data; > } catch (error) { > console.error("Error en fetch:", error); > throw error; > } > } > ``` > > Ahora, refactoriza esta función: > > **Función a Refactorizar:** > > ```javascript > function getUser(id) { > return database.findUser(id).then((user) => { > return getPermissions(user.role).then((permissions) => { > user.permissions = permissions; > return user; > }); > }); > } > ``` ## Extracción de datos: un ejemplo para fijar la estructura Aquí es donde el one-shot se gana el sueldo. Enséñale al modelo el texto de entrada y el JSON exacto que quieres de vuelta, y conviertes texto sin estructura en algo que tu código puede parsear sin ceremonia. El ejemplo aclara la estructura esperada, pero no garantiza que el modelo devuelva JSON válido ni que los datos sean correctos. Antes de guardarlos, parsea la respuesta y valida los campos con un esquema. Si faltan datos, evita rellenarlos con suposiciones. **Prompt:** > Eres un especialista en extracción de datos. Tu tarea es extraer información específica del mensaje de un usuario y formatearla como un objeto JSON. > > **EJEMPLO:** > **Texto:** "Hola, me gustaría reservar un vuelo para dos adultos desde Nueva York (JFK) a Los Ángeles (LAX) el 25 de diciembre de 2025. Preferiría un vuelo por la mañana con Delta." > > **Salida JSON:** > > ```json > { > "intent": "reservar_vuelo", > "pasajeros": { > "adultos": 2, > "niños": 0 > }, > "origen": { > "ciudad": "Nueva York", > "codigo_aeropuerto": "JFK" > }, > "destino": { > "ciudad": "Los Ángeles", > "codigo_aeropuerto": "LAX" > }, > "fecha": "2025-12-25", > "preferencias": { > "hora_del_dia": "mañana", > "aerolinea": "Delta" > } > } > ``` > > --- > > **TU TAREA:** Extrae la información relevante del siguiente texto y formatéala como un objeto JSON, siguiendo la estructura del ejemplo. > > **Texto a Procesar:** "Hola, quiero reservar un vuelo para tres adultos desde Austin (AUS) a Nueva York (JFK) el 10 de marzo de 2026. Preferimos salir por la tarde con American Airlines." ## La información en medio de un contexto largo puede perderse Las ventanas de contexto no paran de crecer, y el marketing sugiere que puedes tirarles cualquier cosa y el modelo se aclarará. La investigación dice otra cosa. ["Lost in the Middle: How Language Models Use Long Contexts"](https://arxiv.org/abs/2307.03172) encontró que los modelos rinden mejor cuando la información crítica está al **principio** o al **final** de la ventana de contexto. En las tareas y modelos del estudio, el rendimiento podía bajar cuando la información relevante estaba en medio del contexto. Eso no demuestra que todos los modelos actuales ignoren esa parte del prompt: comprueba cómo responde el que usas con tus propios documentos. Si construyes un pipeline RAG que añade documentos al prompt, prueba distintas posiciones para la información relevante. Una ventana grande permite incluir más texto; no garantiza que el modelo use bien cada fragmento. ### Una restricción enterrada a mitad de documento se pierde en silencio Imagina que tienes que resumir un documento largo con una restricción muy concreta: el resumen debe incluir un dato específico (un código de producto, una fecha clave, el nombre de alguien) que quizá aparece exactamente una vez, en mitad del texto. Pon la restricción ("Incluir el código de producto XYZ123 en el resumen") en medio de un documento muy largo y el modelo puede pasarla de largo, entregándote un resumen sin el único detalle que necesitabas. Para que la respete, colócala al principio o al final del prompt, claramente separada del documento. **Prompt:** > **RESTRICCIÓN IMPORTANTE:** Tu resumen DEBE incluir el código de producto "PROD-789". > > Resume el siguiente documento en 3-4 oraciones, centrándote en las características y beneficios clave. > > [Contenido del Documento Largo Aquí, donde "PROD-789" podría mencionarse una vez en el medio] > > Alternativamente, podrías colocar la restricción al final: > > Resume el siguiente documento en 3-4 oraciones, centrándote en las características y beneficios clave. > > [Contenido del Documento Largo Aquí] > > **RESTRICCIÓN IMPORTANTE:** Asegúrate de que el resumen mencione el código de producto "PROD-789". ### Dónde va cada cosa - Empieza de cero cuando puedas: un chat nuevo es un contexto enfocado. - Pon al principio las instrucciones, datos o preguntas críticas. - ¿Llega información nueva e importante? Añádela al final. No la insertes en el medio. - El medio es para lo suplementario, lo que el modelo puede permitirse hojear. Prueba el mismo caso con y sin ejemplo, y mueve la instrucción crítica al principio o al final. Compara las respuestas y valida si cumplen la tarea antes de incorporar el prompt a tu aplicación. Si el prompt alimenta a un agente que además informa de su propio trabajo, mira [cómo verifico esas frases con un segundo agente](/blog/verificador-agente-ia-mentira/). **Lectura relacionada:** cuando tus prompts se porten bien, el siguiente escalón es no escribirlos: [deja de promptear a tu agente, escribe loops](/blog/deja-de-promptear-escribe-loops/). --- **P.D.** ¿Tienes un prompt que no obedece lo pongas donde lo pongas? Enséñamelo en [LinkedIn](https://www.linkedin.com/in/oscargallegoruiz). --- URL: https://www.oscargallegoruiz.com/en/blog/introduction-astro-5/ Lang: en # Astro 6 in 2026: what it is and why it ships so little JS > What Astro is and why it ships so little JS: Islands, the Content Layer API, what changed in Astro 6, and the real Next.js to Astro migration on my portfolio. > **Updated May 2026: now covers Astro 6.** I originally wrote this for Astro 5 in late 2025. I've since upgraded this site to **Astro 6** ([stable since 10 March 2026](https://astro.build/blog/astro-6/)), and the headline pitch is unchanged: zero JS by default, Islands, and Core Web Vitals you can actually pass. The Content Layer API and `client:*` hydration directives below are exactly the same in v6. The visible deltas are mostly under the hood: Node `^22.12.0 || ^24.0.0` minimum, Zod v4, and the v5 legacy grace periods are over. If you want the upgrade-from-Astro-5 angle instead of an intro, see my [Astro 6 migration guide](/en/blog/astro-6-migration-guide/), and for the next jump, [the Astro 7 upgrade](/en/blog/astro-7-painless-migration/). My portfolio used to ship a heavy JavaScript bundle to render what is mostly text. On Astro the homepage ships little more than the dark mode toggle's JavaScript. I'm not quoting before-and-after scores here. Same content. Same design. This post is the why and the how. ## What Astro is, and why version 6 matters Astro is a modern web framework designed for building fast, content-focused websites: blogs, portfolios, marketing sites. Its key feature is the "zero JavaScript by default" architecture, which ships only HTML and CSS to the browser and loads JavaScript only for the interactive components that need it. The main new features in Astro 5 (all carried into 6) focus on performance and flexibility: - **Content Layer API:** unifies content loading from multiple sources (local files, headless CMS) with build-time data validation and type-safety through its new *loader* system. - **Improved Islands Architecture:** allows for more granular component hydration with directives like `client:visible`, drastically reducing the amount of JavaScript shipped to the client. - **Faster builds:** Astro says a new caching system and parallel processing cut build times. I have not timed my own build before and after. - **Integrated asset optimization:** the `` component now handles image optimization, automatically generating multiple sizes and formats. ## Why I migrated my portfolio to Astro 5 After trying Next.js, Gatsby, and other frameworks, Astro 5 won me over with its radical approach: zero JavaScript by default. Not as a marketing line, as the actual architecture. ### The problem Astro solves Most modern frameworks ship all JavaScript code to the browser, even for static content. The result: - **JavaScript bundles** bigger than a simple page needs - **Time to Interactive (TTI)** that runs high on mobile - **JavaScript execution time** that blocks the main thread Astro flips the paradigm: **HTML first, JavaScript only when necessary**. ## Content Layer API: the feature that earns the version number Astro 5's biggest innovation is the Content Layer API. Previously, Content Collections only supported local files. Now you can load content from any source. ### Practical example: blog with headless CMS ```typescript import { defineCollection, z } from 'astro:content'; import { glob } from 'astro/loaders'; // Local content (Markdown) const blog = defineCollection({ loader: glob({ pattern: "**/*.{md,mdx}", base: "./src/content/blog" }), schema: z.object({ title: z.string(), description: z.string(), pubDate: z.coerce.date(), updatedDate: z.coerce.date().optional(), author: z.string().default("Your Name"), tags: z.array(z.string()).default([]), draft: z.boolean().default(false), }), }); export const collections = { blog }; ``` ### What the new loader system buys you **1. Real type-safety** Before, TypeScript trusted that your files followed the schema. Trusted. Now, with Zod validation: ```typescript // FAILS: this throws at BUILD TIME, not runtime --- title: 123 # Error: Expected string, received number pubDate: "invalid-date" # Error: Invalid date --- ``` **2. Build performance** In theory the build should be faster; I have not timed my build before and after, so I won't give you a figure. Why should it be faster? - **Smart caching**: only recompiles modified files - **Parallel processing**: handles multiple sources simultaneously - **Optimized tree-shaking**: eliminates unused code from Zod validations **3. Unlimited flexibility** You can combine multiple sources: ```typescript // Future: Load from external API import { strapiLoader } from '@astrojs/strapi-loader'; const externalBlog = defineCollection({ loader: strapiLoader({ url: 'https://api.example.com', collection: 'posts' }), schema: z.object({...}), }); ``` ## Islands: hydrate the button, not the page This is the concept that sets Astro apart from other frameworks. ### The traditional problem With Next.js or Nuxt, if you have one interactive button, **the entire page** gets hydrated: ```jsx // Next.js: Ships the ENTIRE bundle to the browser export default function Page() { return (
{/* Static, but gets hydrated */}
{/* Static, but gets hydrated */} {/* Needs hydration */}
{/* Static, but gets hydrated */}
); } ``` ### The Astro version ```astro --- import Header from './Header.astro'; import Article from './Article.astro'; import InteractiveButton from './InteractiveButton.svelte'; import Footer from './Footer.astro'; ---