The post has been translated automatically. Original language: Russian
You all know convenient tools like Terraform, Ansible, Puppet, and it is these tools that are part of the IAC architectural pattern (infrastructure as code), everything is in git, versioned, reviewed, and rolled out. Now imagine that the context that we are currently keeping in disjointed pieces (rules, restrictions, what an agent can and cannot do) lies and is managed exactly the same way, that is, it is versioned, has an owner, undergoes peer review and, if necessary, compiled before generation. That's about what Arthur Hook's article "Context as Code" is about, which I would like to review. By the way, he himself does not write about teraforms, but the analogy suggests itself. Below is my analysis.
The problem is Frankenstein Factories
Hook introduces the term Frankenstein factories and relies on two others - dark factories (dark factories, the term of Dan Shapiro) and comprehension debt (debt of understanding, the term of Eddie Osmani). The bottom line is that code generators have become so good at producing working syntax that they have put into production systems that cannot be architecturally controlled. The creature leaves the laboratory alive and functional on the day of release, and the crisis comes on the day when the system needs to be monitored.
In order to better understand what I'm talking about, here's an example from the article — a regular ticket in Jira: "Add an email notification after successful payment." June will try to push the email sending directly into the PaymentProcessor class. The senior will say "No" to the review. Throw the PaymentSuccessEvent event into the message bus." It's this human friction, this architectural "no", that keeps the system in shape.
And the default agent is the compromiser (ultimate yes-men in the text). Give him the same ticket, and he won't argue about bounded contexts. He will burn tokens, issue 300 lines of syntactically perfect code, import the SMTP library directly into the billing core and open a pull request. The tests will pass (the usual feature tests about the boundaries of contexts do not check anything), CI will turn green, and structurally the system has turned into a disaster. Not out of malice, but precisely because that's how the agent cycle works — without explicit architectural constraints, the emergency behavior of the system is to fulfill a momentary request, not to protect the architecture.
Hence the main thesis of the article, if the current era has automated the word "YES", we need to automate the word "NO".
What's really blurred
Hook has a very hot part here, and it's right on our security topic. The compiler never guaranteed the correct software, but deterministically kept one layer of risk — syntax validity, type compatibility, and linking. Over time, boundaries were deliberately softened for the sake of speed (dynamic languages, reflection, thick frameworks), and the risk was shifted to runtime tests, observability, and discipline.
With agent-based AI, the border has been softened most radically. Natural language has become the control plane for software generation, and because of this, one of the oldest boundaries in computing has been erased - between data and instructions. There is still a border outside the model (scopes of rights, diagrams, sandboxes). But inside the inference, everything collapses into one stream of tokens, namely, the system prompt, the tightened documents, the user's message, the conclusions of the bodies and the external content flow through the same weights. There is no hard privileged boundary between the instruction and the input data. Modern models resist the naive "ignore previous instructions", but remain vulnerable to indirect injections disguised as a legitimate work context — malicious instructions in a client's email, on a web page, or in Tula's response may become behavioral influences rather than passive data.
The conclusion that should be hung on the wall is that the AI code runs is no longer proof that the system is correct. The risk has moved from the build stage to runtime.
The idea is to compile the context, not to pray for promptness.
And that's where the Context Compilation Pattern appears.

It is important to note right away that Hook emphasizes that this is not industrial engineering (asking the probabilistic model for a better answer). This is build-time governance, two layers of protection even before the inference was launched - structured context injection (we collect prompta from prioritized artifacts) and post-generation static verification (deterministic AST checks that the model cannot rewrite). Prompt shifts generation towards "correct" solutions, and static checks make declared border violations physically unsuitable for migration.
What it looks like in reality. The most valuable code in the repository can now live not in src/, but in /context. Versioned artifacts are placed there — intent.md , boundaries.md , threat-model.md , acceptance-criteria.md , coding-standards.md . Each one is written by a specialist before generation. The key technique is hybrid artifacts, namely a natural language document (it restricts LLM) in a rigid pair with a deterministic rule for the CI runner.
A simple example of an idea. In boundaries.md for billing, we write in human language: the Billing module, no external network I/O, never import requests or smtplib. And next to it we put a rule for the static analyzer (Semgrep takes the hook, but calls both Bandit and CodeQL), which stupidly knocks down the build with ERROR if import smtplib or import requests appear in src/billing/**. The AI reads the map and generates it within its framework, and the CI runner executes the yaml and holds the border. An important detail is that these CI rules are written or reviewed by a person who is not trusted to generate them on the fly.
The "context compiler" itself sounds pretentious, but in fact it's a boring thing, namely a deterministic assembly layer plus routing. In its simplest form, the potatoes are hand—fed to the agent, or a small python/bash script is concatenated.md is sent to the system prompt and returns it .yml in CI, or tools like MCP pull the necessary boundaries right into the IDE. The rules are strict for /billing, and softer for /frontend — the compiler will simply buy them up in the directory.
And separately about conflicts. When instructions contradict each other, LLM does not throw a compilation error — it hallucinates a dangerous compromise. Therefore, a strict hierarchy of priorities is set: threat-model > boundaries > coding-standards > intent + acceptance-criteria. Security and architecture certainly beat feature delivery. And the conflict is "resolved" not by a philosophical conversation between the model and himself, but by a deterministic refusal to CI — if intent asks to "send a check to the mail", and boundaries prohibits network calls in billing, the build simply crashes, and the person (context orchestrator) goes to redo the design on the event bus.
Roles remain, artifacts change
The hook shifts SDLC from a linear relay race to parallel constraint vectors. The posts on the business cards are the same, the artifacts are different:
- the architect becomes a world builder and owns boundaries.md (domain ontology, invariants, allowed interactions);
- QA and Security officer — adversarial context provider, owns threat-model.md (attack vectors and ways of abuse before generation);
- business analyst — intent definer, owns intent.md and acceptance-criteria.md (what is needed and a deterministic proof that it is done);
- DevOps — governance platform engineer, owns a compiler and CI gates;
- The developer is context orchestrator, resolves artifact conflicts, writes critical paths with his hands and repairs why the artifact did not work.
The most useful thing here is to change the question when analyzing the incident. Instead of "what did the agent think?" we ask "which contract didn't work?". The fall ceases to be an opaque hallucination and becomes a traceable collision of boundaries.
Where is the honest boundary of the method (otherwise you got carried away)
This is the part for which the article is worth reading in its entirety, and Hook himself does not hide it. Deterministic checks guarantee invariants, not the whole architecture. Static catches prohibited imports, prohibited external I/O, layer violations, and inconsistencies with circuits. Static does NOT capture domain semantics, the correctness of ownership of aggregates, subtle coherence and conceptual integrity. In other words, the method proves compliance with the declared structural invariants, but does not prove that the architecture is correct.
There is also a context debt. If boundaries.md outdated or crooked, the pipeline will iron out the curve. Therefore, management artifacts are production code with strict versioning, ownership, and periodic review, and not a stick that is adjusted casually.
And the economy. Hook says bluntly — don't build a bank vault door for a barn. For prototypes, one-time scripts, marketing sites and low-risk internal projects, let the generator work without brakes, only speed is important there. But for payment cores, trading platforms, healthcare, and regulated systems, the economy is turning upside down, because speed without deterministic boundaries is just the rate of accumulation of responsibility.
My conclusion
The analogy with infrastructure as a code closes beautifully here. We have already learned once not to hold servers "somehow with our hands", but to describe them with code, versioning and reviewing. Context as Code suggests doing exactly the same thing with intent and boundaries— turning implicit rules into explicit declarations that the compiler and CI must follow. Hook frames this as a shift from imperative procedure engineering to declarative engineering borders, and the main skill now is not to write syntax, but to design the conditions under which the correct syntax can appear at all.
The article is the finale of a three—part series (it's also about the Decision Intelligence Runtime, which protects execution in the product, and about responsibility-oriented agents who protect what can be offered at all). The author has an open reference implementation — github.com/huka81/decision-intelligence-runtime who is interested in touching.
In practice, I would add that most teams are now "aiming an unlimited agent at a code base full of invisible magic, and waiting for the CI, sharpened by handwritten code, to catch trouble." I am helping to build that very stone shore before the water is let in, that is, to set boundaries, a threat model and deterministic gates before the agent reaches the combat systems. Because it's impossible to fix the overproduction of code by hiring more people for review, it's no longer scale-able.
A source:
https://www.oreilly.com/radar/context-as-code/
Вы все знаете удобные инструменты типа Terraform, Ansible, Puppet а именно эти инструменты являются частью архитектурного паттерна IAC(инфраструктура как код), всё в гите, версионируется, проходит ревью, раскатывается. А теперь представьте, что контекст, который мы сейчас держим разрозненными мд-шками (правила, ограничения, что агенту можно, а что категорически нельзя), лежит и управляется ровно так же тоесть версионируется, имеет владельца, проходит peer review и если нужно компилируется перед генерацией. Вот примерно об этом и есть статья Артура Хука «Context as Code» кеоторую хотел бы рассмотреть. Сам он, к слову, про тераформ не пишет — но аналогия напрашивается сама. Ниже мой разбор.
Проблема — фабрики Франкенштейна
Хук вводит термин Frankenstein factories(фабрики Франкенштейна) и опирается на два чужих - dark factories(тёмные фабрики, термин Дэна Шапиро) и comprehension debt(долг понимания, термин Эдди Османи). Суть а именно генераторы кода стали так хороши в выдаче рабочего синтаксиса, что поставили на поток производство систем, которыми невозможно управлять архитектурно. Тварь выходит из лаборатории живой и функциональной в день релиза, а кризис наступает в день, когда систему надо начать контролировать.
Для того чтобы лучше понять о чем я вот вам пример из статьи — обычный тикет в Jira: «Добавь email-уведомление после успешной оплаты». Джун попробует впихнуть отправку письма прямо в класс PaymentProcessor. Сеньор на ревью скажет «Нет. Кидай событие PaymentSuccessEvent в шину сообщений». Вот это человеческое трение, это архитектурное «нет», и держит систему в форме.
А агент по умолчанию — соглашатель(ultimate yes-men по тексту). Дай ему тот же тикет, и он не будет спорить про bounded contexts. Он сожжёт токены, выдаст 300 строк синтаксически идеального кода, заимпортит SMTP-библиотеку прямо в ядро биллинга и откроет пулл-реквест. Тесты пройдут (обычные фиче-тесты про границы контекстов ничего не проверяют), CI позеленеет, а структурно система превратилась в катастрофу. Не со зла а именно потому что так устроен агентный цикл — без явных архитектурных ограничений Экстренное поведение системы это выполнить сиюминутный запрос, а не защитить архитектуру.
Отсюда главный тезис статьи, если нынешняя эпоха автоматизировала слово «ДА», нам нужно автоматизировать слово «НЕТ».
Что реально размылось
Тут у Хука смаая горячая часть, и она прямо по нашей теме безопасности. Компилятор никогда не гарантировал правильный софт, но детерминированно держал один слой риска — валидность синтаксиса, совместимость типов, линковку. Со временем границы намеренно размягчали ради скорости (динамические языки, рефлексия, толстые фреймворки), а риск перекидывали на рантайм — тесты, observability, дисциплину.
С агентным AI границу размягчили радикальнее всего. Естественный язык стал control plane'ом для генерации софта, и из-за этого стёрлась одна из старейших границ в computing — между данными и инструкциями. Снаружи модели граница ещё есть (скоупы прав, схемы, песочницы). Но внутри инференса всё схлопывается в один поток токенов а именно системный промпт, подтянутые документы, сообщение юзера, выводы тулов и внешний контент текут через одни и те же веса. Нет жёсткой привилегированной границы между инструкцией и входными данными. Современные модели сопротивляются наивному «ignore previous instructions», но остаются уязвимы к непрямым инъекциям, замаскированным под легитимный рабочий контекст — вредоносная инструкция в письме клиента, на веб-странице или в ответе тула может стать поведенческим влиянием, а не пассивными данными.
Вывод, который стоит повесить на стену - то, что AI-код запускается, больше не доказательство, что система корректна. Риск переехал со стадии сборки на рантайм.
Идея — компилировать контекст, а не молиться на промпт
И вот тут появляется Context Compilation Pattern.

Важно сразу заметит что Хук подчёркивает, что это не промпт инжениринг (выпрашивание у вероятностной модели ответа получше). Это build-time governance, два слоя защиты ещё до того, как запустился инференс - структурированная инъекция контекста (собираем промпт из приоритизированных артефактов) и пост-генерационная статическая проверка (детерминированные AST-проверки, которые модель не может переписать). Промпт смещает генерацию в сторону «правильных» решений, а статические проверки делают объявленные нарушения границ физически непригодными для мержа.
Как это выглядит в реалиях. Самый ценный код в репозитории теперь может жить не в src/, а в /context. Туда кладутся версионируемые артефакты — intent.md, boundaries.md, threat-model.md, acceptance-criteria.md, coding-standards.md. Каждый пишет специалист до генерации. Ключевой приём — гибридные артефакты а именно документ на естественном языке (он ограничивает LLM) в жёсткой паре с детерминированным правилом для CI-раннера.
Простой пример идеи. В boundaries.md для биллинга пишем человеческим языком: модуль Billing, никакого внешнего сетевого I/O, никогда не импортируй requests или smtplib. А рядом кладём правило для статического анализатора (Хук берёт Semgrep, но называет и Bandit, и CodeQL), которое тупо валит билд с ERROR, если в src/billing/** появился import smtplib или import requests. AI читает мдшку и генерит в её рамках, а CI-раннер исполняет ямл и держит границу. Важная деталь — эти CI-правила пишет или ревьюит человек, на лету их LLM-у генерировать не доверяют.
Сам «компилятор контекста» звучит пафосно, но по факту это скучная штука а именно детерминированный слой сборки плюс маршрутизация. В простейшем виде — мдшки руками скармливаются агенту, или мелкий скрипт на питоне/баше конкатенирует .md в системный промпт и отдаёт .yml в CI, или тулы вроде MCP дёргают нужные границы прямо в IDE. Для /billing правила строгие, для /frontend помягче — компилятор просто скоупит их по директории.
И отдельно про конфликты. Когда инструкции противоречат друг другу, LLM не кидает ошибку компиляции — он галлюцинирует опасный компромисс. Поэтому задаётся жёсткая иерархия приоритетов: threat-model > boundaries > coding-standards > intent + acceptance-criteria. Безопасность и архитектура безусловно бьют доставку фичи. И «разрешается» конфликт не философской беседой модели с собой, а детерминированным отказом в CI — если intent просит «отправь чек на почту», а boundaries запрещает сетевые вызовы в биллинге, билд просто падает, и человек (context orchestrator) идёт переделывать дизайн на шину событий.
Роли остаются, артефакты меняются
Хук перекладывает SDLC с линейной эстафеты на параллельные векторы ограничений. Должности на визитках те же, артефакты другие:
- архитектор становится world builder и владеет boundaries.md (онтология домена, инварианты, разрешённые взаимодействия);
- QA и безопасник — adversarial context provider, владеет threat-model.md (векторы атак и пути злоупотребления до генерации);
- бизнес-аналитик — intent definer, владеет intent.md и acceptance-criteria.md (что нужно и детерминированное доказательство, что это сделано);
- DevOps — governance platform engineer, владеет компилятором и CI-гейтами;
- разработчик — context orchestrator, разруливает конфликты артефактов, пишет критичные пути руками и чинит, почему артефакт не сработал.
Самое полезное тут — смена вопроса при разборе инцидента. Вместо «что там агент подумал?» спрашиваем «какой контракт не сработал?». Падение перестаёт быть непрозрачной галлюцинацией и становится прослеживаемым столкновением границ.
Где честно проходит граница метода (а то увлеклись)
Это та часть, ради которой статью стоит читать целиком, и Хук сам её не прячет. Детерминированные проверки гарантируют инварианты, а не архитектуру целиком. Статикой ловятся запрещённые импорты, запрещённый внешний I/O, нарушение слоёв, несоответствие схемам. Статикой НЕ ловятся доменная семантика, корректность владения агрегатами, тонкая связанность и концептуальная цельность. То есть метод доказывает соответствие объявленным структурным инвариантам, но не доказывает, что архитектура правильная.
Туда же — context debt(долг контекста). Если boundaries.md устарел или кривой, пайплайн будет железно энфорсить кривое. Поэтому артефакты управления это production-код со строгим версионированием, владельцем и периодическим ревью, а не мдшка, которую правят между делом.
И экономика. Хук прямо говорит — не строй дверь банковского хранилища для сарая. Для прототипов, одноразовых скриптов, маркетинговых сайтов и низкорисковых внутренних тулов пусть генератор работает без тормозов, там важна только скорость. А вот для платёжных ядер, торговых платформ, healthcare и регулируемых систем экономика переворачивается, потому что скорость без детерминированных границ — это просто скорость накопления ответственности.
Мой вывод
Аналогия с инфраструктурой как кодом тут закрывается красиво. Мы один раз уже научились не держать серверы «как-нибудь руками», а описывать их кодом, версионировать и ревьюить. Context as Code предлагает сделать ровно то же самое с намерением и границами — превратить неявные правила в явные декларации, которые компилятор и CI обязаны соблюсти. Хук формулирует это как сдвиг от императивной инженерии процедур к декларативной инженерии границ, и главный навык теперь не писать синтаксис, а проектировать условия, при которых правильный синтаксис вообще может появиться.
Статья — финал трёхчастной серии (там ещё про Decision Intelligence Runtime, который стережёт исполнение в проде, и про responsibility-oriented агентов, которые стерегут то, что вообще можно предложить). У автора есть открытая референс-реализация — github.com/huka81/decision-intelligence-runtime, кому интересно пощупать.
От себя добавлю практикой - большинство команд сейчас именно «целятся неограниченным агентом в кодовую базу, полную невидимой магии, и ждут, что CI, заточенный под рукописный код, поймает беду». Я помогаю строить тот самый каменный берег до того, как пускают воду то есть ставить границы, threat-модель и детерминированные гейты раньше, чем агент дойдёт до боевых систем. Потому что починить перепроизводство кода наймом ещё людей на ревью нельзя, это уже не масштабируется.
Источник:
https://www.oreilly.com/radar/context-as-code/