← все видео

How I built an agentic loop with Cursor subagents

Blue Cactus AI · 2026-01-26 · 11м 2с · 11 553 просмотров · YouTube ↗

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

🎧 Аудио

📝 Summary

model=deepseek-v4-flash · prompt=summary-v7 · 3 832→1 882 tokens · 2026-07-20 11:48:36

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

Автор построил в Cursor агентный цикл кодирования: один главный суб-агент after hours запускает 3–5 итераций, на каждой из которых порождается 3–5 узкоспециализированных суб-агентов (бэкенд, БД, качество, фронтенд, конфиг, UI). Цикл управляется через Cursor Hooks (хуки на завершение сессии и на блокировку коммитов в main) и Cursor Skills (Git, Kubernetes, Kafka). Такой подход эффективен для исследования кодовой базы (discovery), но менее подходит для точной доработки, где проще управлять одним агентом вручную.

Архитектура агентного цикла: суб-агент after hours

Суб-агент after hours — это набор инструкций и навыков (skills), хранящихся в .cursor директории проекта. При активации по ключевому слову after hours в чате Cursor срабатывает скрипт хука, который:

Механизм хуков: запуск следующей итерации и блокировка main

Два ключевых хука управляют циклом:

  1. After hours hook — bash-скрипт, который отслеживает стоп-сигнал (stop event) от завершившейся сессии Cursor. Когда сессия суб-агента заканчивается, хук срабатывает и запускает следующую итерацию цикла. Это позволяет последовательно или параллельно вызывать новые группы суб-агентов.
  2. Block main commit hook — предотвращает любые попытки суб-агентов пушить изменения в main ветку. Если агент во время цикла пытается выполнить git push в main, хук блокирует операцию. Это даёт автору безопасность запускать долгие автономные циклы, не боясь повредить основную ветку.

Практический запуск: пример задачи

Автор даёт задачу: «Проверить реализацию драйвера (driver implementation) для подготовки кода к миграции в production. Найти, как реализован driver ID, и выдать блоки кода и новые файлы». Цикл запускается. На первой итерации (hook turn one) суб-агенты начинают работу:

Используемые навыки (Skills) и их роль

Помимо суб-агентов, автор загрузил в Cursor Skills команды для работы с конкретными инструментами:

Эмерджентное поведение и практические ограничения

Автор отмечает, что на GPT 5.2 Codex Extra High (максимально «умная» модель) агентный цикл работает медленно — выполнение затягивается. При использовании суб-агентов часто возникает эмерджентное поведение: иногда алгоритм делает неожиданно полезные вещи (например, находит связи между сервисами), а иногда — неожиданно плохие (например, пытается записать неправильные миграции). Для точной работы (рефакторинг, исправление багов) автор пока предпочитает управлять одним агентом вручную, а агентный цикл считает лучшим для discovery — быстрого сканирования всей кодовой базы (13 микросервисов, фронтенд, бэкенд) и формулирования плана.

Рекомендации по использованию и будущие направления

Автор предупреждает, что кастомные суб-агенты и циклы сжигают значительно больше токенов, чем обычная работа с одним агентом. Нужно следить за лимитами и не увлекаться количеством агентов и правил. Встроенные в Cursor суб-агенты можно использовать без кастомных хуков — достаточно попросить Cursor «спавнить суб-агентов». В будущем автор видит потенциал в запуске открытых локальных моделей 24/7 в таком цикле, но считает, что современные модели пока недостаточно умны для стабильной работы: они делают и ценные, и вредные вещи.

📜 Transcript

en · 1 673 слов · 23 сегментов · clean

Показать текст транскрипта
Hey, I hope everybody's good. I've been seeing a lot of news recently about agentic coding assistance and agentic coding loop tools. I built an agentic coding loop in Cursor. I just wanted to make a really quick video showing how this works. um so i'll just briefly uh talk about this and then we'll go ahead and start running the query so i used a cursor agents cursor hooks and cursor skills um to do this so i set up a sub agent in cursor called after hours and what this sub agent does is it will loop anywhere between three to five times and on each loop iteration it spawns a three to five uh sub agents for each loop iteration so and what are those three to five sub agents so i've created like a mixture of experts like back-end api off data db migrations quality front-end config product ui and we also are using the default cursor sub-agents so the sub-agent explorer or the sub-agent general purpose i believe there's a bash shell sub-agent that we're using too so If I use the keyword after hours in the chat, it'll go look through the subagent instructions and then pull in the skill. So we have a skill that goes along with the subagent. And these are the files that this subagent creates. So we have the markdown file that's the subagent instructions. We have a log. So each iteration of the agentic coding loop. And let me go ahead and start this now. So I can show you guys. So for now, what I'm doing is I'm giving a simple task, just run after hours to check the driver implementation. I need to prepare the code to migrate to production. I need to go find how we implemented driver ID and give me the code blocks and new files I need to add. So I'm just going to let that start running. And so really what happens is every time we go through an iteration loop, um this hook fires so so there's a session that happens right and then that session when the session's done it sends a stop event or a stop signal right and what this hook is doing is this hook is looking uh for this stop signal here you can see um these are the uh sub agents uh starting to spawn um so it's like it looks like a discovery agent uh spawning here uh looks like it used the default uh discovery agent now we're spawning um additional sub agents so we got the db migration scan here sub agent so what this hook does is it looks for when the session um is done and when the session is done pretty much that hook fires and it will start another loop right here's another agent um that it's spawning a quality test scan um and so so this is a hook that looks for stop events then a very another important hook so what i realized is um with the agentic loop coding number one what i found is gpt 5.2 codex extra high um is the best at long running agentic loop coding um and it's interesting because usually these sub agents will spawn simultaneously but it looks like they they kind of spawned in sequential order here um but one important one i think i noticed is there's a lot of like emergent behavior so um sometimes when i'm doing this agentic loop coding sometimes it's doing things that i like sometimes it's doing things that i don't like um so what i did was i also created a block main commit hook So what does that hook do? So really what that hook does is at any point in time, if the agent during this agentic loop tries to push to the main branch, this hook will identify that and block that from happening. And so this makes me feel comfortable when I'm running this agentic coding loop. So here it looks like it's about to write to the log file and then we can check out the log file together. uh and these are different skills that i also have um that i just want to show you guys so i also have a git skill here it is writing to the after hours log but this is a git skill and this is any git commands that i run i loaded that up in in as a skill and these are all inside of the dot cursor uh hidden directory um and then i have a kubernetes skill with all my kubernetes um tasks uh are all my kubernetes commands and then i have a cafta skill with all my kubernetes kafka uh commands and so cool it just wrote to the after hours log so let's look so hook turn one um status interesting aborted uh i think that's from the pre-hook so we have a pre-hook that creates new files um but we'll have to look into this but here's the coordinator so i have one coordinator that's managing all of the sub-agents um so let's see so signal driver id and jess writes um in event media portraits got it reports enrichment expects so it's kind of looking at all of my services so i have 13 microservices uh some front end stuff some back end stuff um and so so those mixture of sub agents um helped me quickly uh uh you know look at both the front end and the back end um and consider all of that right um so let's see um reviewed ingest reports front-end accounts migration checklists and plan ddl for driver id flow okay decisions treat this turn as discovery no code changes yet cool so this was a discovery turn it looks like um i maybe shouldn't have told it to give me all of the code blocks because it's really really slowing this down okay boom so the hook just fired so i'm going to show you guys this um let's see if i go to settings and then i go to hooks you'll see that uh the hook the after hours dot sh that was that bash shell script that looks for the stop event um and then starts the loop right and so uh so here you go uh here's the loop uh starting again And I maybe shouldn't have used Codex Extra High on this because it's going to be like a super long time before this video is over. But here you go. Here's the subagent. So we launched a backend API driver scan, a DB migration scan, a quality test scan, an infra ops scan. And so this is pretty awesome. All of these subagents are running right now. um at the same time and so now really really as i tune this what i'm going to be doing is as i keep going through the code base understanding the code base deeper right think about all right if i needed to assemble a team uh uh uh what type of people would i hire right and and and that's how i'm gonna design my mixture of of sub-agents um now this is me using custom sub-agents and custom agentic looping um but you also can use the cursor built-in sub agents all you have to do is tell cursor to spin up the sub agents now you do want to be careful um you know with these sub agents um it will burn um tokens right so just just uh more tokens than if you were not using sub agents um so it's just important to to understand that and make sure you don't get crazy with tons of agents and rules and skills because things can get really out of control fast. Here you can see we added more data to the log. We're still on hook turn one. There we go. Loop count zero. It's still running here. We also have a pre-hook. While that's running, I'll show you the pre-hook. uh let's see i don't think i opened it let's go back to hooks after hours prep okay so what does this pre-hook do so we have a file called after hours mode um and what that file does is pretty much if that file is created um we know to keep looping so here you go here we're on loop two um and guys i really want to keep the video under 10 minutes and it's unfortunate next time i do a video like this i'll do it um with the agent that's faster um but now uh here you can see we're on loop two we're spawning another three to five sub agents um so anyways guys if you're interested in agentic and and the last thing my thoughts on this is that i don't think um it would be interesting to get open source local models running locally um and have those in an agentic loop uh running 24 7 and see what happens now what i think is i think that the models are not smart enough yet um to be really really good at this um i have seen some really interesting emerging behavior though where um it has like this emergent quality where it'll do these really interesting things that i really find valuable but then i'll do these really interesting bad things that i don't find valuable at all um and so for now i think you know me like steering uh just a single agent unless i'm doing discovery i think if i'm doing discovery sub agents is awesome if i'm really doing precise work you know steering a single agent and understanding the code base um is maybe better for me at least for right now but anyways this was a video on um agentic loop uh coding uh using cursor agents hooks and skills thanks

⚙️ Pipeline jobs

StageStatusAtt.UpdatedError
download done 1/3 2026-07-20 11:47:39
transcribe done 1/3 2026-07-20 11:48:13
summarize done 1/3 2026-07-20 11:48:36
embed done 1/3 2026-07-20 11:48:39

📄 Описание YouTube

Показать
I am tuning a Cursor subagent called afterhours that runs iterative loops until a task is complete capped at 10 passes. Each loop spawns multiple expert subagents in parallel and writes shared context to a rolling log that carries forward between passes. Hooks manage the loop control and prevent commits to main.