← все видео

Agent Loops: Complete Guide (Claude Code + Codex)

Owain Lewis · 2026-06-13 · 20м 40с · 34 908 просмотров · YouTube ↗

Топики: ai-loop-engineering

🎧 Аудио

📝 Summary

model=deepseek-v4-flash · prompt=summary-v7 · 7 518→1 942 tokens · 2026-07-20 11:47:33

🎯 Главная суть

Вместо того чтобы вручную давать промпты каждому агенту, нужно проектировать системы, в которых агенты запускаются в циклах, сами пишут промпты для суб-агентов и выполняют работу автономно. На практике это реализуется через два связанных цикла: менеджер-цикл (классификация задач в бэклоге) и воркер-цикл (написание кода, тестирование и открытие PR). Ключевые элементы — контрольная плоскость (GitHub Issues), чёткие guardrails и верификационный слой.

От «loop engineering» к системному дизайну

Термин «loop engineering» часто воспринимается как абстрактная метафора, но его суть проста: вместо того чтобы каждый раз вводить команды агенту в терминале, пишется цикл, который сам решает, что делать, как проверять результат и когда переходить к следующей задаче. Автор предпочитает говорить «building systems with agents» — это точнее описывает процесс: проектирование системы, где агенты — исполнители, а человек — проектировщик цикла и постановщик guardrails. Агенты не заменяют человека, но берут на себя рутинные низкорисковые задачи.

Контрольная плоскость (control plane) и состояние мира

При автономной работе агенты должны оставлять следы своих действий, иначе система становится «чёрным ящиком». В качестве контрольной плоскости используется GitHub Issues (можно Linear и т.п.): агенты обновляют статус тикета, добавляют метки, пишут комментарии с подтверждением выполненной работы (например, вывод тестов). Человек в любой момент может зайти и увидеть, что сделано. Это снижает риск неконтролируемого поведения.

Цикл менеджера: автономная классификация бэклога

Первый цикл запускается по расписанию (cron) или при добавлении нового тикета. В нём агент (Claude Code) выполняет роль менеджера: проходит по всем открытым тикетам, классифицирует их по риску (low/high), по типу (bug, documentation, feature, refactor) и помечает, готов ли тикет для работы агента (agent ready) или требует человеческого ввода (needs human input). Пример: тикет с меткой «risk: low, type: feature, agent ready» может быть передан воркеру. Тикеты high risk или требующие рефакторинга остаются человеку. Этот цикл автоматически поддерживает порядок в бэклоге — то, что раньше отнимало много времени у тимлида.

Цикл воркера: автономное выполнение задач

Второй цикл тоже запускается по расписанию. Агент (Codex или Claude Code) опрашивает GitHub, находит тикеты с метками «agent ready» и «risk: low» (до 3 за один запуск — guardrail). Затем для каждого тикета запускается внутренний воркфлоу:

  1. Создаётся чистая ветка (проверка, что нет незакоммиченных изменений).
  2. Агент читает задачу, пишет код.
  3. Запускает тесты.
  4. Спавнит суб-агента для code review (агенты промптят агентов).
  5. Исправляет замечания.
  6. Открывает Pull Request с описанием и доказательствами (вывод тестов в комментарии).
  7. Переводит тикет в статус «ready for review».

Важно: воркеры работают последовательно, чтобы избежать конфликтов, хотя возможен и параллельный режим.

Архитектура агентов: координатор, рабочие, суб-агенты

Ключевой паттерн — координатор (primary agent), который распределяет задачи между рабочими. В Codex для этого используются отдельные threads (Codex threads) — каждый thread может сам порождать суб-агентов. В Claude Code появилась поддержка вложенных суб-агентов, что позволяет строить иерархию: координатор → рабочий → ревьювер. Все промпты для суб-агентов генерируются агентом, а не пишутся человеком — именно это имели в виду Борис и Питер, когда говорили «агенты пишут промпты для агентов».

Guardrails и верификация как основа доверия

Без барьеров автономные агенты могут натворить бед. В системе заложены несколько уровней защиты:

Чем больше таких guardrails и чем строже оценка качества (evaluation: сколько PR потребовало доработок), тем выше можно поднять доверие и делегировать агенту более сложные задачи.

Формализация процесса: скиллы вместо жёсткой инструкции

Лучшая практика — выносить логику в отдельные «скиллы» (skills). Например, skill «backlog manager» содержит три задачи: триаж бэклога, подготовка очереди (классификация по риску и типу) и ведение отчёта. В самом цикле (GitHub Action) остаётся лишь минимальная команда: «запустить такой-то скилл». Это упрощает поддержку и позволяет менять поведение агента без правки CI-кода. Скиллы кодируют процесс, а не знания — агенту не нужно объяснять TDD, он уже знает.

📜 Transcript

en · 4 801 слов · 46 сегментов · clean

Показать текст транскрипта
This is a complete guide to building agent loops and autonomous AI systems. You may have heard a lot of hype around the term loop engineering, but very few people show you how to actually apply these ideas in practice. Most of us dream about having autonomous agents working for us 24-7, doing work, making money, and saving us time. But in reality, building agent systems requires real design thinking. I'm going to show you how I'm using a combination of forward code and codecs to automate a significant part of my development process. By the end, you'll know how autonomous agent loops work and how to build them yourself. All of the resources and prompts and everything you need is going to be linked for free in the description below. So let's get into it. If you're new to the channel, my name is Owen. I've been a software engineer, engineering manager and engineering director for the past 20 years. And I build autonomous AI systems every single day within my own business. Okay, so this is the tweet from Peter Steinberger that kind of triggered this whole kind of discussion. So this idea that your monthly reminder, you shouldn't be prompting coding agents anymore. You should be designing loops that prompt your agents. It's a pretty abstract concept. Anytime you're using a subagent, for example, you're already doing this. So a subagent will... be triggered with a prompt that was written by the parent agent. So anytime you're triggering a subagent, you're already having agents that write prompts. But I think what Peter's talking about here is more about system design. Boris talks about another concept as well. So Boris talks about this idea that I don't prompt Claude code anymore. I write loops and the loops do the work. My job is to write loops. Again, it's a very vague and very abstract kind of idea. One of the reasons I dislike the term loop engineering in general is because it's very abstract and it's very unclear what it means. I think a better term is building systems with agents. I think that's kind of a clearer way to think about this. The other term I really dislike is harness engineering for the same reasons. It's very opaque and very unclear what it actually means in practice. So a loop is a very simple concept. It's generally just doing things over and over again. Loops have always existed in coding. It's a fundamental part of building code, obviously. And so the idea of a loop here in this context is we're running an agent in a loop. So this is what's different here. So on a schedule or when an event happens, an agent will read the state of the world. This could be reading a GitHub issues ticket queue. It will do some kind of work and then it will update the state of the world. It will go back to sleep and then it will repeat in a loop. This is like the most basic loop that you could build. So the agent has a very specific job. It runs on a schedule and it can update the state of the world. So an important thing to think about when you build autonomous agent systems is to always think about the control plane or the state of the world. And so When these agents are running autonomously, you need a way to inspect what they're doing. As a human, you don't want agents to run unattended with no visibility into what's actually happening. That would be very dangerous. So a control plane could be something like a linear or GitHub issues where you can have agents updating tickets or tasks they're working on. You can see the tickets move through a status queue going from in progress to in review to done. and every ticket can have a comment from the agent. You can see all of the work that's going on. Agents can comment on things. They can update the state of the tickets. So in this video, we'll look at a simple system which has two loops. So the first loop is what I call the manager loop. This is a loop where an AI agent is looking at a project backlog, looking at all of the work items and classifying all of the tickets as low risk or high risk and whether a ticket is suitable for an agent to work on the ticket. So you have an autonomous agent classifying the work. And what this enables then is you can have a second agent loop, which I call the worker loop. This is where we have an agent polling a GitHub issues queue or a control plane looking for work to do. When the agent finds the work to do, the agent then is going to run through its own workflow. So it's going to take the ticket and basically run a pipeline. In this case, I've got an inner loop where the agent will first read the ticket. It will then write the code. It will spawn a subagent to review the code. it will then do some additional checks and then finally it will open a pull request at the end. So this is really important you have the agent prompting itself throughout this loop so the agent is prompting the sub-agent to review the code and the agents are just running in a loop here so it's a pretty simple setup but it's very very powerful as we'll see. So the first loop we're going to look at is the manager loop so as a former engineering manager and former tech lead one of the jobs I had to do or one of the jobs of an engineering manager in general is to keep the backlog tidy. This is because people in your team or engineers are going to be working on these tasks and you need to make sure that everything is ordered correctly, things have the right priority, everything on the board is in the right state. One of the biggest frustrations if you work in an engineering team is when you look at a board like this, things are marked as in progress that have already been completed, things are marked as in review which are not or they're still being worked on. So this kind of out of sync problem is really frustrating in the real world. So we're going to use agents to label and classify all of our tickets for us autonomously. And the agents are also then going to check that everything is in the right state. The agents are also going to review our code base. And anytime they find a bug or a documentation mismatch or something wrong with our code, the agents can then also file a ticket. So we have this autonomous agent manager that is looking after everything in our project. So here's the code for this automation. It's pretty simple. You can ask Claude Code to basically write these things for you nowadays. You don't need to write them by hand anymore, thankfully. But essentially what this will do, it will run clawed code on a loop and it says use the backlog manager skill to triage the repository basically. So go through all of the tickets, run the skill and make sure everything is okay. That's pretty much all we're doing here as the automation. You can set a cron here for example if you want to schedule this to run every single day. Okay so what we're going to do now is kick off this automation. So this is an agent loop. The GitHub action is going to run in a loop. We're running clawed code. to act as an agent to go and manage our backlog for us. We're going to move this into the apply mode. This is going to allow Claude Code to make changes to our backlog. So we're just going to kick this off now and see where we get to. So in theory, as this runs through, you should see Claude Code actually thinking through the problem, and then we should see these tickets being updated as Claude Code goes through the backlog. So the other thing to say is as you go through, when you build these agent loops, you also want to consider the guardrails. So for example, when this agent automation loop runs, the agent can't go and push code or do any destructive operations. And so anytime you build an agent loop, you need to think very carefully about the design of the guardrails. So for example, the only thing that this agent automation or Claude can do in this situation is update and manage our tickets. That's all it can do. You can lock this down. This allows you to build these kind of agent loops very, very securely. And this is kind of the key to building these autonomous systems. You need to put the guardrails in place to protect everything. Okay, now you can see that the agent is updating things. So it looks like this agent is now alive and working. So the agent loop has classified this ticket. So it's marked as agent ready, risk low type feature. So this is perfect. Now, so the agent is reading the tickets, is updating all of the labels. Hopefully now we're going to see the rest of them. You can see some other additional labels are now being classified. So this ticket here, this one needs human input. You can see now the agent is adding all the labels. So this is a high risk feature. It also needs human input. This is an exploration. So obviously we need some kind of human input on these tickets and we just need to wait for it to run through the rest of them, classify the rest. So this is an agent loop running in action. The agent is classifying all of the tickets. We're not doing a thing. This is going to run every single day, whatever you schedule it at. So anytime you add a new ticket or every single day, you get the AI agent loop to run through, classify and manage your entire project backlog. This is the work that would have taken a human a long time previously. So we have a couple of tickets here that looks like we can work on. So this ticket looks like we can assign this to an agent. So this is ready for an agent because it's low risk and it doesn't need any human input. You can configure this. Obviously, you could make any of these tickets ready for an agent as well. So the more you trust the system, the more you can delegate to agents. I would start off by giving agents the very basic easy things like bug fixes, documentation updates. And then as you build more confidence in these autonomous agent loops, you can then start delegating bigger and bigger pieces of work to the agents. I would probably be quite happy to delegate some of these medium tasks to agents, to be honest. All right, so if we go back to our diagram, you can see here now we've completed the manager loop. So this autonomous agent loop now can run every single day or every single time you add a ticket. You can have this manager loop run, classify all of your tickets to make sure that they're agent ready, decide what things an agent can work on, classify the risk level, make sure everything is in the right status, etc. So now we need to go and build the second loop, which I call the work loop. Okay, so this is the really exciting and interesting part of the loop. So essentially the job of the loop engineer is to actually write all of the code. So we have an agent that is running on a loop every single day. What it's doing, it's going to look for any tickets that are open, that have a label of agent ready and risk equals low. So any tickets that are suitable for an autonomous AI agent to work on is going to basically pull down the tickets, start doing the work, and it's going to run an inner workflow. This is where we have agents prompting agents. So the first thing we do is basically make sure that we're in the right branch. So we make sure that we're not in a dirty branch. We don't have any unstaged changes. Make sure everything in the environment is clean. This again is a useful safeguard to protect you from having agents kind of mess up your work or cause problems. You want to make sure that it will abort if anything is unclean. And then what we're going to do is we're going to work sequentially. This is really important. You could either run these tickets in parallel if you wanted to. So you could run multiple different agents working on multiple different tickets at a time. I tend to not do that because it can cause a lot of problems. You'll probably find that you'll have agents conflicting with each other. Often these tickets have dependencies anyway. So there's like a logical ordering, but you can ask the coordinator to run these in parallel if you want to. This primary agent is acting as a coordinator for the rest of the system. So what we're going to do is actually spin up a new codex thread. So let's read through the automation, create a new codex thread. This is unique to codex. You can't do this in Claude code, but this creates an entirely new session or conversation or agent instance that can then itself spawn subagents. And you can go in and inspect any of these, essentially these threads at any single time. So what we're going to do is we're going to read the ticket, write the code, ensure there's good test coverage, run relevant tests, use a subagent to review the diff. So this is where we're using agents to prompt other agents. And then we're going to fix any findings, open a pull request, and then move the ticket into ready for review. Comment on the original issue. This is really important when you're working with autonomous agent systems. You always want the agents to give evidence in the tickets of what they did. This allows you to see the work they did. This allows you to make sure that they ran the tests because they can provide evidence inside the ticket. When you work with human engineers, you do the same thing. Generally, it's really good practice to put screenshots. evidence of test output into your tickets because it confirms to the reviewer that the tests were actually run. So that's just very good practice in general. Only after the pull request is open can you continue to the next issue. So this is kind of just running the entire loop. We also have a maximum number of three issues per automation run. This is important because again it's just another guardrail. Because these agents are running autonomously there might be a bug where you have like 50 tickets and the agent working through 50 tickets would burn a lot of tokens. So you want to be a little bit conservative and again just put guardrails inside your automations. You can obviously change this number as you build confidence in the system. So what we're going to do now is just kick off this automation. We're going to run it and then we can click down here to see that the automation has now started. So this is what's going to be run every single day. What's really useful is when you run these automations, although you can see that I did hard code a lot of instructions here, so I put a lot of detail in this set of instructions, what I would recommend doing as best practice is to not do this. What I recommend is to have a skill that will run a workflow. So basically this automation should be relatively simple. It should say pull down the tickets, delegate them to the workers and then run the skill basically. So that allows you to have less noise in this automation. It's much easier to maintain. So that's just something I would recommend. So now you can see that the agent is querying GitHub. So it's running the GitHub query now. So we've got four candidate issues. So we've got issue number 18, issue 63, 1110 and 129. So the agent can work on any of these. It can only work on three at a time. So now the agent has to use its own intelligence or judgment about what it's going to work on. Again, this is why the systems like this are so powerful. You have agents using their intelligence to make decisions about what to do. This is why this is so much more powerful than maybe a traditional automation would be. So your approach here, if you're using codecs, your approach for this kind of thing will be slightly different to Claude Code. but it's the same principle. Within ClaudeCode, you can now have nested sub-agents. So what I'd probably do in ClaudeCode is to have the primary agent as a coordinator that would then spawn a sub-agent. The sub-agent would do all of the work and then report back to the coordinator. The sub-agents in ClaudeCode can now be nested. So you can have a orchestrator, you can have a worker, and then you can have a sub-agent from the sub-worker as well. So that's kind of a powerful pattern you can now do in ClaudeCode. What you can see here is that this is the agent that is running the work. So this is the idea of an agent prompting an agent. So obviously we didn't write this prompt. So it says you are worker one for this repository, work only on this GitHub issue. So again, the agent is writing this prompt. This is an example of what Peter was saying. Agents are prompting themselves. We're not writing the prompt. The system is writing its own prompts. If you're interested in the skills, I'll put a link in the description below, but this is my backlog manager skill. And you can see here it says manage an engineering backlog for humans and AI agents. So pretty simple. The goal of this skill is to basically classify tickets. We use the jobs to be done framework here to define the roles within this skill. So the agent has three jobs. So triage the backlog, make sure everything is labeled correctly, everything is in the right state, prepare the queue, so classify issues by risk type, then maintain a report, basically just tidy up everything and make sure it's in a good state. And then you can also see that we're using this set of labels. So we have a risk label, we have a type label and a routing label. So the first risk classification will say whether a ticket is high risk or low risk. You don't want agents to be working on high risk tickets or changes. You don't want them deploying your software autonomously. You probably don't want them making very risky product decisions themselves. And you also have a type of ticket. So you can see whether it's a bug or a documentation change or a refactor. And then you can also see these two labels are critical. So is this ticket ready for an agent to work on? Or does this ticket need human input? This allows you to kind of come back to the system, give your input or your feedback. And then the next time the agent loop runs, it will obviously then be able to kind of move it into agent ready state. So this is kind of the coordination layer between you as a human and your agents running the system. Again, you do need human input here. This doesn't replace human judgment or human thinking. but it does allow you to have agents work on low risk or simple tickets, which is just going to massively increase your productivity and your quality of your code base because agents are going to be looking for bugs. They're then going to be proactively fixing things with inside your code base. So this is quite a powerful concept. Again, you have to tailor this to your risk level. In certain companies and situations, you maybe don't want agents to be running this loop, but I think it's pretty safe because you're always reviewing the pull request at the end. So let's take a look at what the agent did. So you can see here there's a pull request open. So which one was it? So this was open two minutes ago. So this is our agent writing the pull request. So what's really powerful here is you're going to wake up in the morning to a bunch of pull requests, hopefully some high quality work done by your agent. So as long as you're building the system correctly, this work is going to be suitable to merge. You're running checks, you're running code review, you're running tests, you're making sure your system is doing all of the right things. You can see here the files changed by the agent. So we've added this test. into our system. So this is a pretty simple one. We're just adding an additional test. This is the kind of thing where very, very simple, no real risk here to merge this is very low risk. So this is the perfect kind of task for an agent, just slightly improving your code base, making things better, happening autonomously 24 seven, you'll notice I have some additional checks as well. So going back to this point about guardrails, when you build autonomous AI systems, you need a lot of guardrails. So the guardrail we have here is that Codex will run some kind of automated code review check so that even when the agent pushes up the PR, even though the agent has reviewed its own work, we then have a secondary code review. You could build in other tooling here like Greptile or CodeRabbit or any other kind of automation to verify the quality of the code. You could run a bunch of automated tests, whatever you need to do. But the point is the agent has a second reviewer, which is automation checking its work basically every single time. So this is what allows us to run these autonomous systems. If you are interested in this topic, I'll link you to the skills repo that I have called Blueprints. And inside here, you'll have a guide on loop engineering in general and kind of my mindset on this. You can see here we have the three phases. You have ideas. So you think about what you want to build. Then you basically create the tickets. You create all of the work to be done. You have an agent do the work. And then you have this kind of review or feedback check. So this is really important. And the main thing you want to think about when building these agent systems now is the quality checks. You don't want agents to be merging low quality work. You want this feedback loop, the verification layer. This is really, really important. If you're interested in this, I do have a bunch of skills here. And I also have a bunch of guides and documentation on building autonomous agent systems and how I'm doing this myself. And you can see here that we have a bunch of different skills. And so what we're doing is we're encoding process, not knowledge. These skills are very lightweight. They're mostly relying on the intelligence of the agents. We don't need to tell agents how to do test-driven development. They already know. So within this repo, you'll find a bunch of skills around loops. So there's various types of loop we have here. So we have an inner loop where we take a task and then we open a pull request. So if you think about systems, if you're a systems thinker, the input is a task and the output is a pull request. This is the level of abstraction you want to think about when you're building autonomous agent systems. You want to think like a systems thinker. What's the input? What's the output? And then what's the quality check? Multitask allows you to run several tickets at once. So you can see here we have this multitasking coordinator. Again, these are just design patterns that you can adopt. So we have a list of tickets. You have one primary agent act as a coordinator that will then spin up parallel tickets or do them sequentially. The point here is that the primary agent, whether that's Claude Code or whether it's Codex, the primary agent It's coordinating all of the work and then delegating that either to Codex threads or Claude Code subagents. So you have a coordinator, you have these workers doing all of the work, and then you are obviously then opening pull requests and doing your verification layer. So this is a really powerful closed loop workflow that allows you to scale your agentic engineering. What you'll notice is these loops can take a long time. So as agents work through these tickets and they get smarter and more powerful, These agent loops will run for longer and longer. So these might take an hour to two hours to run through. You don't want to be babysitting these kind of loops. They can run for many, many hours. And so this is why we want to always have these kind of agent loop systems. And while we're moving away from just prompting the agents in our terminal to letting the agents just run the workflow, and then we can just review the work. This is what Boris and Peter were talking about. Agents prompting agents, build systems, build loops, and get out of the loop. So the final thing you want to think about is when you build these systems, you really want to think about the guardrails so you can see how powerful they are. We now have agents working on our codebase 24-7. They're actually doing work for us. We have an agent loop, which is classifying all of our tickets. This is running continually, making sure our backlog and our project is in good shape. This is kind of doing the job of an engineering manager or a tech lead, triaging a backlog. And then you have another agent loop, which is actually executing the work. But the key thing is to remember, you need these guardrails in place. We didn't have agents working on everything. We had agents working on a small subset of the work. This is kind of the key point. You don't want to take yourself fully out of the loop on certain things. You want to always be reviewing and making that final decision. But the more guardrails you put in place and the more rigorous you're designing the systems, the more you can allow yourself to step out of the loop. So this is really a systems design problem. So you want to think about the evaluations as well. So how would you know if this system is doing a good job? You'd think about how many of the tickets needed to be reworked. Did the agents close the ticket on the first time? Did they get the code correct? Or did you have to go back and give lots and lots of feedback? So as you design these systems, you want to think about the evaluations and the guardrails. They're probably the critical parts to building these autonomous agent systems that can run unattended. Without the guardrails and without the way of evaluating the agent's work, you're not going to be able to kind of scale this pattern. But if you can figure out those things, then you can definitely build these incredible systems that are able to run significant part of your workflow autonomously using AI agents. So I hope you find this useful. If you do have any comments or thoughts on this, let me know in the comments below and I'll see you in the next one.

⚙️ Pipeline jobs

StageStatusAtt.UpdatedError
download done 1/3 2026-07-20 11:46:54
transcribe done 1/3 2026-07-20 11:47:08
summarize done 1/3 2026-07-20 11:47:33
embed done 1/3 2026-07-20 11:47:34

📄 Описание YouTube

Показать
💬 Community: https://aiengineer.co
🔗 Free resources: https://owainlewis.com/youtube

A complete guide to building autonomous agent loops. You've probably heard a lot of hype around the term loop engineering, but very few people show you how to actually apply it in practice. That's what this video does.

In this video I build a real system with Claude Code and Codex that automates a significant part of my development workflow. It runs as two loops. A manager loop reads my project backlog and classifies every ticket by risk, type, and whether it's safe for an agent to work on. A worker loop then picks up the low-risk, agent-ready tickets, writes the code, spawns a subagent to review the diff, runs checks, and opens a pull request. The agents prompt each other the whole way through, and I just review the work at the end.

I also cover the part most people skip: the guardrails and evaluations that make a system like this safe to run unattended.

What you'll learn:
- What an agent loop actually is, minus the jargon
- The control plane: using GitHub Issues as shared state agents can update
- The manager loop: autonomously triaging and labelling a backlog
- The worker loop: turning agent-ready tickets into pull requests
- How agents prompt agents (coordinator, workers, nested subagents)
- The guardrails that keep it safe
- How to think about evaluations
- Why I encode process, not knowledge, in lightweight skills

🔗 Links
Guide: https://github.com/owainlewis/youtube-tutorials/tree/main/tutorials/loop-engineering
Free skills / resources: https://owainlewis.com/youtube
Community: https://aiengineer.co

If this was useful, a like and subscribe genuinely helps the channel. Drop a comment with any topics you'd like me to cover.

#LoopEngineering #ClaudeCode #Codex #AIAgents #AgenticCoding #AIEngineering #SoftwareEngineering