# Context Architecture vs. context engineering vs. harness engineering The terms get confused easily because they all touch AI agents and code. They are not competitors. They operate on different objects, at different layers. The distinction is best drawn with one question: what does each one design? ## The three disciplines | Discipline | What it designs | Layer | Question it answers | | ------------------------ | ---------------------------------- | --------------------------------------- | -------------------------------------------------------------------- | | Context engineering | The contents of the context window | Runtime | What does the model see right now? | | Harness engineering | The agent's execution environment | Infrastructure / operations | How does the agent operate safely and self-correct? | | **Context Architecture** | **The codebase itself** | **Software architecture (design-time)** | **How is the system structured so people and agents understand it?** | :diagram-layers ## The codebase as input vs. the codebase as object The other disciplines treat the codebase as an *input*. The harness reads it. Context engineering compresses it into a window. The agent navigates it. In every case the codebase is a given, something to be consumed. Context Architecture treats the codebase as the *object of design*. It asks how the repo should be structured in the first place, before any agent reads it. And there is a causal relationship between the two. A codebase with good Context Architecture takes work off every other layer: less to compress at runtime, fewer corrective guardrails in the harness, fewer errors to patch across sessions. Structure done well at design time pays off at every layer downstream. ## An analogy Harness engineering designs the vehicle and its safety controls. Context engineering decides which map to load for each trip. Context Architecture is the urbanism of the city itself: streets with clear names and neighborhoods with internal logic let any driver, person or agent, navigate without a sophisticated GPS. A well-planned city is not a function you bolt onto a bad one. It is the substrate that makes every trip through it cheaper. That is Context Architecture's relationship to the layers above. # Glossary: Context Architecture and adjacent terms The terms around AI agents and code are used loosely and get confused. This glossary gives each one a short, self-contained definition and says how it relates to Context Architecture. For the full treatment of the three disciplines, see the [comparison](https://context-architecture.dev/comparison). ## Context Architecture A software architecture for the age of AI agents: it structures a repository so that everything it claims about itself, its structure, its behavior, and who can change it, is legible to the agent writing the code and to the people who answer for it, and bound to a mechanism that fails when that claim stops being true. It treats the repository itself (its file tree, boundaries, conventions, and embedded context) as a designed artifact, not an accident of growth. It is the structural counterpart to context engineering and harness engineering. Introduced by Sergio Azócar in October 2025\. ## Context engineering The runtime discipline of deciding what enters the model's context window at each step: which files, instructions, and tool results are loaded. It designs the contents of the window. Context Architecture designs the thing the window looks at, the codebase. Better Context Architecture means there is less to compress at runtime. ## Harness engineering The operational discipline of designing the environment an agent runs in: the execution loop, the tools it can call, and the guardrails that keep it safe and let it self-correct. It designs the agent's operating environment. Context Architecture designs the codebase that environment operates on. Better Context Architecture means fewer corrective guardrails in the harness. ## AGENTS.md A file of embedded context placed at a meaningful boundary in a repository, holding only what cannot be learned by reading the code: the source of truth, the invariants, the accepted tech debt, and the rationale a spec leaves behind. Because it sits next to the code, it is reviewed in the same pull request, ages at the same rate, and is found by the same agent about to edit it. `CLAUDE.md` is the tool-specific equivalent some agents read. In Context Architecture, an `AGENTS.md` is the artifact of the second principle (Context Lives With Code), and each claim it makes should be bound to a mechanism. ## Spec-driven development Writing intent as a specification before the code exists: the spec defines the what, not the how, with acceptance criteria the implementation is checked against. In Context Architecture (sixth principle, Intent Becomes Mechanism), the spec is design-time scaffolding, not a durable artifact. Once its acceptance criteria become tests, its contracts become types, and its conventions become lint, it has done its job and is removed, so it cannot drift. It is kept only when it stays generative, feeding code generation or a spec-driven loop. ## Context-rot The silent decay of documentation as the code it describes changes: a doc that cites a deleted file, names a renamed module, or contradicts the current behavior, while still reading as authoritative. A confident reader obeys it, so rotted context is worse than none. The rule at the heart of Context Architecture exists to prevent it: every claim a repository makes about itself must be bound to a mechanism that fails when that claim stops being true. ## Where to go next - The [specification](https://context-architecture.dev): the rule, the autonomy spectrum, the mechanisms, and the nine principles. - The [comparison](https://context-architecture.dev/comparison): Context Architecture vs. context engineering vs. harness engineering. - The [guide](https://context-architecture.dev/guide): how to apply it to an existing codebase. # How to apply Context Architecture The [specification](https://context-architecture.dev) says what Context Architecture is and why. This page is the part you do with your hands. It applies in two situations, and you pick your path by which one you are in. You are starting a new repository. You want it born legible: the structure says what the system does, and every claim it makes about itself is bound to a mechanism from the first commit. Nothing has drifted yet, so the work is to keep drift from ever starting. Jump to [starting a repo legible](https://context-architecture.dev/#path-a-start-a-repo-legible). You have a repository that already grew. It started clean and grew for three years. Conventions drifted. The docs stopped matching the code. The folder names tell you which framework built the thing, not what the thing does. Hand it to a reader with no memory, someone on their first day or an agent started cold, and ask for one change: they cannot tell what anything means, where the change goes, or which of two competing patterns is current. Nobody designed it to be read. Jump to [reworking a repo that grew](https://context-architecture.dev/#path-b-rework-a-repo-that-grew). Both paths converge on the same end state and the same loop. The difference is only the starting point and the cost. Born legible is cheaper, you pay as you go. Reworked is more expensive, you pay down what already accrued, in steps. ## The loop, either way Working with an agent is a continuous flow of code changes. Context Architecture lives inside that flow, not off to the side. Every change does two things: 1. **Write the claim.** When a change introduces or modifies something the repo holds about itself, a source of truth, an invariant, a convention, you write that claim down where it belongs. 2. **Verify it.** You bind that claim to a mechanism that fails when it stops being true, in the same change. Repeat on every change. A new repo runs this loop from commit one. An existing repo runs it too, plus a backlog of claims that were never bound, which you work through in steps. That is the whole difference between the two paths. This is why the context grows with the system instead of trailing behind it. It is not a setup you do once, it is a property maintained change by change. When a change adds a claim and leaves it loose, review, by a person or an agent, catches it and requires it bound before the change is accepted. ## The one reader to design for ::callout{color="neutral"} Assume a reader who keeps nothing between sessions and knows only what the repo states out loud. An AI agent is exactly that reader. A new teammate is close. The question underneath all of it is one: how long until that reader makes a correct change. :: ## Before you start: is it worth it? It has a real cost. The structure up front, the checks that are themselves code you have to keep green, and a small tax on every change to keep each claim tied to a mechanism. It pays off in proportion to how much agent or multi-person work the repo takes on. Worth it on a codebase that absorbs refactors, migrations, spec-driven features, agent contributions. Not worth it on a throwaway prototype or a problem you have not figured out yet. There the tax costs more than it returns, and skipping it is the right call. Saying that out loud is part of the discipline. This holds for both paths. A new repo you know is throwaway does not need the discipline either. ## Path A: start a repo legible A new project starts with the structure its framework hands it. That structure names the framework, not the product, and the drift starts the day the second person commits. Starting legible means you do not inherit that default and then fight it later. You are building in the order the principles fall, and each piece ships with its mechanism: 1. **Lay out the top level by domain, not by framework layer.** `billing/`, `onboarding/`, `payments/`, not `controllers/`, `services/`, `utils/`. The framework lives one level down, inside the domain it serves. Doing this on day one costs nothing; doing it after three years is the most expensive move there is. 2. **Name every boundary for what it owns.** No `utils/`, `common/`, `helpers/` as a default dumping ground. A small `shared/` for genuinely generic, dependency-free code is fine, and it stays small. The mechanism: a lint rule that errors when a file lands in a folder that does not match its domain, and an import rule that breaks the build when a module reaches across a boundary it should not. 3. **Put a root `AGENTS.md` in from the first commit**, and one at each boundary as you create it. It holds only what the code cannot say on its own: the source of truth, the invariants, the tech debt you took on purpose. The mechanism: a test that fails if an `AGENTS.md` cites a path that no longer exists. 4. **Codify each convention the moment you decide it**, instead of writing it in a doc and hoping. The first time you would leave a review comment, make it a lint rule or a type instead. A convention an agent cannot read is a convention it will break. 5. **Bind behavior to a test, not to a sentence.** The first time you write "this operation responds within a certain time" or "this format must not break for current users," that line ships with the automated test that goes red when it stops holding. 6. **Generate the capability list, do not hand-maintain it.** From the first script, keep scripts and commands in predictable, named places and generate the list from those paths, with a test that fails if a real capability is missing from it. 7. **Bind the verification surface itself.** The set of tests and rules is a claim too. Protect it so a change cannot weaken or delete a check to get itself through. Done this way, the five failure modes below never get a chance to accrue. You are not undoing drift, you are refusing to start it. When you finish setup, you are already running [the loop](https://context-architecture.dev/#the-loop-either-way): each new change writes its claims and binds them in the same change. ## Path B: rework a repo that grew You are not building a new city, you are putting street names on one that already sprawled. Do it in small steps. You do not stop everything and restructure at once. You land one bounded, reversible change at a time, and each one ships with the mechanism that keeps its claim honest. No big-bang rewrite. The order runs cheapest and safest first: 1. Read the repo as a cold reader, and name the failure modes you hit. 2. Fix the docs that lie. 3. Put `AGENTS.md` at the top boundaries. 4. Turn your most-repeated review comment into a lint rule. 5. Break up one junk-drawer folder. 6. Make the capabilities findable. 7. Move toward a domain-first layout, last, and only if it earns the churn. There is no separate final step to "turn on" the loop. Once a change writes its claims and binds them, you are already running [the loop](https://context-architecture.dev/#the-loop-either-way). The steps below are the backlog of claims the repo never bound; the loop is what stops a new one from going loose again. The rest of this path is one step per section, then one full example. ### Step 1: audit the repo as a cold reader Open the repo as if you had never seen it and remember nothing. Read the top-level tree, then the boundaries, then a handful of leaf files. At each level, one question: could I make a correct change here without asking anyone? Every "no" is a defect you just found. The defects come in five shapes. These are diagnostic signals, the symptoms you look for when a repo is silent about itself, not a fixed law. A better model lowers how often each one happens, but it does not remove them where the repo states nothing out loud: with no source of truth to find, even a strong model reimplements; with two live conventions and nothing saying which is current, it still has to guess. 1. **Reimplementation.** The source of truth was not findable, so the reader rebuilds what already exists. 2. **Invented structure.** Nothing was imposed, so the reader imposes its own. 3. **Obedience to false docs.** It cites deleted files or contradicts the current code, with full confidence. 4. **Deprecated-pattern spread.** It copies the loudest pattern even when that pattern is dead. 5. **Coin-flip on ambiguity.** Two conventions coexist, so it picks whichever it read first. Write down, per principle, a verdict and the evidence. Do it by hand, or load the [Context Architecture skill](https://context-architecture.dev/skill) into your agent and let it write the report. **What this looks like.** On a payments service, the first pass finds refund logic spread across three folders (reimplementation waiting to happen), a `README` pointing at a deploy script that was deleted months ago (false docs), and two date helpers with different signatures (a coin-flip). Three failure modes named before you touch a line. ### Step 2: fix context-rot first Start by stopping the docs from lying. A doc that cites a deleted file or contradicts the code is worse than no doc at all, because a confident reader does what it says. Find it by hand or by script: pull every file path, command, symbol, and link out of your `README`, your `AGENTS.md` and `CLAUDE.md` files, and your design docs, and check that each one still exists or still runs. Fix each lie against what the code actually does today. Then make the rot impossible to bring back. Add a test that asserts every path the docs cite still exists on disk. Now "this doc is accurate" is a claim with a mechanism behind it, instead of a hope. **What this looks like.** The `README` documents a `deploy.sh` that was deleted a year ago. You drop the dead reference, write down the real command, and add that path-check test. The next time someone moves a file out from under a doc, the suite goes red in the same change, not in production six weeks later. ### Step 3: place AGENTS.md at the top boundaries Context belongs next to the code it describes, at every boundary that owns something. Put there, it ages at the same rate as the code and gets read by the same agent about to edit it. Start at the root and the two or three busiest directories. That is where each `AGENTS.md` buys the most legibility. Write down only what you cannot get from reading the code: the source of truth, the invariants, the tech debt you accepted on purpose, and the reasoning a spec left behind. Keep each one short. ```markdown # AGENTS.md (billing) Owns invoicing, refunds, and the dunning schedule. ## Source of truth Prices come from the `pricing-engine` package, never hard-coded here. ## Invariants - A refund never exceeds the captured amount. Enforced by `refunds/guard.test.ts`. - All money is integer cents, no floats. Enforced by the `no-float-money` lint rule. ## Accepted tech debt The legacy `chargeV1` path stays until the 2026-Q3 migration. Do not extend it. ``` Look at the invariants: each one names the mechanism that enforces it. That is the whole point. An invariant with nothing behind it is just a new line that can rot. If the mechanism does not exist yet, write it in the same change, or phrase the line as a known gap, not a guarantee. ### Step 4: codify the loudest convention Take the comment you leave most often in review, the one that lives only in your team's heads, and put it in the toolchain. A convention an agent cannot read is a convention it will break, every time. This is the move the rest of the steps lean on. When a claim needs to hold, this is how it holds: a lint rule that states the convention and fails in the same place, or a type that makes the wrong thing refuse to compile. **What this looks like.** The comment you leave most is "import from the package root, not deep paths." Today it lives in reviewers' heads, so an agent breaks it on its first commit. ```text # before: a convention that lives in reviewers' heads "always import from the package root, never deep paths" # after: the convention, written down and enforced .oxlintrc.json # a no-restricted-imports rule that fails the deep path in CI ``` Once the rule is in the linter, the deep path fails on the spot, with a message that cites the rule, not a reviewer who happened to be paying attention that day. ### Step 5: name a junk-drawer boundary `utils/`, `common/`, `helpers/`, `core/`, `lib/`. This is where responsibility goes to die. Nothing in the name pushes back on unrelated code, so the folder grows forever. Pick the worst one and split it into folders whose names each say what they own. ```text # before src/utils/ # 40 unrelated files # after src/pricing/ # the price math that was hiding in utils src/auth-session/ # the session helpers that were hiding in utils src/shared/ # what is genuinely generic, kept small and dependency-free ``` The name is doing the work. A folder called `pricing` resists code that is not about pricing, because it stops fitting. If you cannot name a boundary precisely, the boundary is wrong, and `shared` is not the answer. A tiny `shared/` for a date formatter or a result type is fine. Reaching for the generic name to dodge the question of where something belongs is the debt. ### Step 6: make capabilities discoverable A capability an agent cannot find is, to that agent, a capability that does not exist. It just gets rebuilt, or skipped. Move your scripts, generators, and commands to predictable, named places, and name them for what they do: `package.json` scripts, a `scripts/` or `skills/` directory, commands you actually wrote down. Better, generate the list of capabilities from those conventional paths instead of keeping it by hand, and test that the list is complete. A hand-kept list is one more claim waiting to rot. **What this looks like.** Three deploy and seed scripts live in one engineer's home directory and a Slack thread nobody can find. You move them into `scripts/` with names that say what they do and list them in `package.json`. The next agent finds them where it looks first, instead of writing a fourth. ### Step 7: move toward a domain-first structure (last) The top level should say what the system does, not which framework built it: `billing/`, `onboarding/`, `payments/`, not `controllers/`, `services/`, `utils/`. The framework lives one level down, inside the domain it serves. This is the expensive move and the one most likely to break imports, so it goes last and goes in slices. Often a partial move plus a root `AGENTS.md` that spells out the structure you are migrating toward buys more legibility, per file moved, than reshuffling everything at once. ```text # before: organized by technical layer src/ controllers/ services/ models/ utils/ # after: organized by domain, framework one level down src/ billing/ controllers/ # the framework, inside the domain it serves services/ models/ onboarding/ payments/ ``` Keep it from sliding back with a lint rule that stops domain code from leaking into a layer folder, and keep the target structure in the root `AGENTS.md` so a reader who lands mid-migration knows which way is forward. ## A worked example, end to end This walks Path B, the harder one. A service that started as one framework app and grew for three years. The tree screams the framework, not the product, and the only doc is a `README` that is half wrong. ```text # before src/ controllers/ # 22 files, mixed domains services/ # 18 files, mixed domains models/ utils/ # the junk drawer helpers/ # a second junk drawer README.md # points at a deploy script deleted last year ``` Ask an agent to "add a partial-refund flow" here and watch it hit three of the five failure modes in one task: it cannot find where refunds live (split across `controllers/`, `services/`, `models/`), it rebuilds money math that already sits in `utils/`, and it follows the `README` to a deploy script that is gone. The fix, in the order above, with no big-bang commit: 1. **Context-rot.** Drop the dead deploy reference from the `README`, write the real command, add a test that every path the `README` and `AGENTS.md` cite still exists. 2. **Embedded context.** A root `AGENTS.md` (what the service owns, the structure it is migrating toward) and one in the busiest area. 3. **Codify.** The most-repeated review comment was "money is integer cents." That becomes a `no-float-money` lint rule. 4. **Name.** Split `utils/` and `helpers/`: money math becomes `money/`, session code becomes `auth-session/`, the genuinely generic remainder stays in a small `shared/`. 5. **Discoverable.** The ad-hoc scripts move into `scripts/` with real names, listed in `package.json`. 6. **Domain-first, in slices.** Move `refunds` first: a `billing/refunds/` that keeps its controller, service, and model together. The next agent asked about refunds finds them in one place. ```text # after src/ billing/ AGENTS.md # invariants and the source of truth for billing refunds/ # controller + service + model, together invoices/ auth-session/ money/ # the math that was buried in utils, now named and enforced shared/ # small, generic, dependency-free scripts/ # named, listed in package.json AGENTS.md # the rules of the house, and the structure being migrated toward README.md # accurate, and a test keeps it that way ``` Now the same task lands in `billing/refunds/`, against an `AGENTS.md` that states the refund invariant, reusing the `money/` package the lint rule already points at. Each claim the repo makes is bound to a mechanism, and from here the loop keeps it that way: the next change that adds a claim binds it in the same change. The failure modes have nowhere left to happen. ## Run it with the skill Step 1 and most of the moves above are things an agent can run. The [Context Architecture skill](https://context-architecture.dev/skill) is a single file you load into your agent: it reads the repo as a cold reader, finds the docs that lie, and hands back the backlog in the order above. Point it at your repository and start with what it flags first. ## Where to go next - The [specification](https://context-architecture.dev): the rule, the autonomy spectrum, the mechanism kinds, and the nine principles in full. - The [comparison](https://context-architecture.dev/comparison) with context engineering and harness engineering: which layer each one designs, and why this one sits below them at design time. - The [skill](https://context-architecture.dev/skill): to run the work with your own agent. - The [glossary](https://context-architecture.dev/glossary): the terms used across the specification, defined. # Context Architecture ## The rule A software architecture for agents comes down to one rule. ::rule Every claim a repository makes about itself must be bound to a mechanism that fails when that claim stops being true. :: That is the whole architecture. Everything else is how you apply it. The rule is evaluated against any repository, claim by claim. Take each thing the repository holds about itself (where the source of truth lives, what the correct pattern is, what must not be touched) and ask whether there is a compiler, a linter rule, an automated test, or a review step that breaks when that stops being true. If there is not, it is prose, and prose goes stale without anything noticing. A claim is anything the repository holds about itself, not just the shape of its folders. "Prices are computed in this module and nowhere else" is a claim. "This operation responds within a certain time" is a claim. "This data format does not break for the people already using it" is a claim. They are all the same kind of thing: something the repository promises, and that at some point can stop being true. The mechanism has to actually fail, not just exist. A performance test that never exercises the slow path does not satisfy the rule, it violates it. Either the claim is bound to something that goes red when it breaks, or it is not. The rule applies to itself. The set of tests and rules that verify the repository is, in turn, a set of claims about the repository, so it too is bound to a mechanism that fails if it is weakened. The architecture has to hold up with or without a person reviewing the code. When a person reviews, the mechanisms do the checking the person would otherwise do by hand. When there is no person, they are the reviewer. ## The problem Architecture used to optimize one thing: how fast a new engineer could understand the code. The reader changed. Today much of the code that reaches production is read and written by an agent. Writing code stopped being the bottleneck. Models write well, and they review themselves better every day. The bottleneck moved to verifying that a growing volume of changes does not break anything, at the speed the agent produces them. A small error rate, multiplied by that volume and that speed, with no mechanism that fails when a claim is violated, is silent breakage at scale. It takes two forms. With a person reviewing, verification does not scale: code is generated faster than it can be read, and the person ends up approving code they did not actually read. Without a person, a change that looks correct gets integrated, because nothing failed when a claim that lived only in prose was violated. The job of the architecture is not to make the agent wrong less often. The model handles that, and better every day. The job is to make every violated claim fail at once, in the place where it broke, instead of integrating without anything noticing. That is why the problem grows with better models instead of going away: the faster and more autonomous the agent, the more the repository has to verify itself. > Design for a reader who remembers nothing between sessions and only knows what the repository says out loud. An agent meets that exactly. A new person approximates it. ## The autonomy spectrum Context Architecture works with or without a person in the loop. Today the norm is someone orchestrating the agent; more of the work is moving to agents running on their own. The architecture has to serve the whole range. | Level | Who reviews | What breaks without repository discipline | | ------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | Inline | a person approves each edit | the agent reimplements things that already exist and the person burns time fixing what the tools could have caught | | Async | a person reviews the change before integrating it | review does not scale; the integration gate exists but enforces nothing, one click lets a change through | | Autonomous | a person sets the rules, does not look at each change | if the mechanisms are missing, the definition of "done" is empty: the agent calls a change finished when it passes but is wrong | | Orchestrated | nobody in the middle | the error multiplies at machine speed; the only arbiters are the repository's mechanisms | What changes across the spectrum is who consumes the verification, not the verification. The same `AGENTS.md` and the same mechanisms work in an interactive session, in a change reviewed separately, and in an agent running on its own. When there is a person, the mechanisms absorb the routine checks, so the person spends attention on what needs judgment, not on re-checking a convention. When there is no person, the mechanisms are the reviewer. ## How it applies Working with an agent is a continuous flow of code changes. The rule lives inside that flow, not off to the side. Every time a change introduces or modifies something the repository holds about itself (a new source of truth, an invariant, a convention), that something is bound to a mechanism in the same change. And every change that touches existing code meets the mechanisms already there: if it violates a claim, something goes red before it reaches production. That is why the repository's context grows with the system instead of falling behind. It is not a setup you do once, it is a property maintained change by change. When a change adds a new claim and leaves it loose, review, whether by a person or an agent, catches it and requires it to be bound before the change is accepted. Binding a claim is connecting it to something that fails when it stops being true. Context Architecture names the kinds of mechanism, not the tool: - **The compiler** catches what can be expressed in types: reintroducing a forbidden import breaks the build. - **The linter** catches problems of structure and convention: a file in the wrong folder fails the lint and cites the rule it breaks. - **Automated tests** catch documentation that lies and behavior that strays from what is expected: an `AGENTS.md` that mentions a deleted file turns the tests red. - **Review**, by a person or an agent, catches what the others do not see, the meaning: on each change it asks whether any document now says something false, and requires the fix in the same change. The split with the infrastructure the agent runs on is clear: Context Architecture decides what gets verified and guarantees the mechanism exists and fails. The infrastructure runs it. Binding the claim belongs to the architecture; running that mechanism on each change belongs to the environment. ## The principles Each principle is a property you can check, not an aspiration. Either it is true of your repository and bound to a mechanism, or it is not. If it cannot be bound to something that fails, it is not a principle. ### Let the repository say what it is **01 · Structure Screams Intent.** The file tree says what the system does, not what framework built it. A `billing/` folder names a business responsibility; a `controllers/` folder names a technical detail that could belong to any system. The framework lives one level down, inside the domain it serves. That way a reader locates where a change goes before reading a single line. *Mechanism: a linter rule that errors when a file lands in a folder that does not match its domain.* :diagram-tree **02 · Context Lives With Code.** Context lives next to the code it describes, at every important boundary, not in a separate wiki that goes stale. It holds only what the code cannot say on its own: where the source of truth is, what invariants must be respected, what technical debt was accepted on purpose, and what behavioral limits apply to that part. Because it sits next to the code, it ages at the same pace and is found by the same agent that will edit it. *Mechanism: a test that fails if an `AGENTS.md` mentions a file that no longer exists.* **03 · Boundaries Are Explicit and Named.** Each module and package is named for the responsibility it owns. Folders like `utils/`, `common/`, or `helpers/` collect anything, because the name rules nothing out. Genuinely shared, domain-free code exists, and it has a place: a date formatter, a Result type, a reusable UI hook. It goes in a small `shared/`, with no dependencies toward any domain, and it stays small. The debt is not having shared things, it is using the generic name to avoid deciding where something that does have an owner goes. If you cannot name a boundary precisely, that is usually a sign the boundary is drawn wrong, not that you need another generic folder. *Mechanism: a rule that forbids a module from importing across another boundary through paths that are not allowed, and breaks the build when it happens.* **04 · The Repo Is Legible at Every Zoom Level.** Legibility is not only a top-level property, it reaches into the body of every function. You can have a clean root, `billing/`, `payments/`, and three folders down a `helpers.ts` with a `process(data)` function that does not say what it processes or what it returns. That is where legibility falls off. The same discipline that made you name `billing/` at the root has to name `applyLateFee(invoice)` at the leaf, and call `invoice` what is now `data`. *Mechanism: linter rules on names and complexity limits.* **05 · Capabilities Are Discoverable.** The project's tools, scripts, and commands live in predictable places with names that say what they do: the `package.json` scripts, a `scripts/` folder, a skills folder. A capability that exists but that an agent cannot find does not exist for that agent: it reimplements it from scratch. The list of capabilities is not written by hand, it is generated from those predictable places. A hand-written list is one more claim that goes stale: someone adds a script and forgets to note it. A list generated from the conventional folders cannot leave out something that is there, and if it goes out of date, a test catches it and goes red. *Mechanism: the list generated from the conventional paths, and a test that fails if a real capability does not appear in it.* ### Bind every claim to a mechanism **06 · Intent Becomes Mechanism.** Intent is written as a spec before the code, then turned into the code and into the tests and rules that enforce it, and the spec is removed once its content already lives there. What stays is the intent and its verification, not the code that satisfies it: as long as the tests pin down the behavior, that code can be regenerated. A spec is kept only if it still generates something (code, configuration); if not, it is removed, so no second description is left to go stale. *Mechanism: the tests, the types, and the rules the spec was turned into.* **07 · Conventions Are Codified, Not Implicit.** A convention that lives only in people's heads is invisible to an agent, and the agent will break it. Take it out of the culture and put it in the tools that review the code: linter rules, type constraints, automated validations in CI that state the rule and enforce it in the same place. *Mechanism: the linter rules and the type constraints.* **08 · Behavior Is Verifiable, Not Asserted.** Every claim about how the system behaves (how long an operation may take, what data must not cross a certain boundary, what format must not break for the people already using it) is bound to an automated test that lives in the repository and goes red when the behavior strays from what was promised. A time limit written in a document goes stale; the same limit bound to a test that fails when it is exceeded is architecture. The test lives in the repository and runs before the change is integrated. If the system in production also fires an alert when something degrades, that is already the job of the environment it runs in, not of the architecture. *Mechanism: an automated behavior test (performance, data contract, security) that lives in the repository and fails when the behavior deviates.* **09 · The Verification Surface Is Itself Bound.** The set of tests and rules that verify the repository is, in turn, a set of claims about the repository, so it too is bound. An agent can rewrite the code freely, but it cannot weaken or delete a test, a rule, or a validation to get a change through. Without a person reviewing, this is the principle that matters most: the cheapest way to make a validation pass is to remove it. *Mechanism: a validation that goes red if the set of tests and rules changes without the authorization the repository defined.* ## What Context Architecture does not do An honest architecture says what it is not. It is not an isolation or permissions system. The isolated environment the agent runs in, the network connections coming in and going out, the agent's credentials and identity are matters for the infrastructure, not for the repository's architecture. It is not the machinery that runs the controls. The automated validations, the branch protection, the required reviewers already exist and apply the same way to an agent's change. Context Architecture decides what they must check, the infrastructure runs them. It is not regulatory compliance. It is agnostic to regulations. That a company needs a person's signature because of a rule is the company's decision and the company's problem. It does not impose tools. It names the kinds of mechanism, the repository picks the product. `oxlint` or `eslint`, it makes no difference. It does not make the agent smarter or fix its hallucinations. It makes the truth of the repository checkable automatically, so the agent's error fails at once and where it happened, instead of integrating without anything noticing. ## Limits and cost It does not apply everywhere. It applies to repositories that absorb work from agents or from several people: refactors at scale, migrations, features with a clear spec. It applies from the first commit (a repository can be born legible) and to one that grew without design, which is then restructured in steps, never all at once. Do not apply it to the first prototype of something you do not understand yet, nor to a poorly defined problem. Structuring is an investment that pays in proportion to the work the repository absorbs. On a throwaway project, the cost outweighs the return. There is a cost: structuring up front, maintaining the tests and rules that are code and have to be cared for, an extra discipline on every change. But that work is mechanical, well specified, and repetitive, which is exactly what an agent does well. The person writes the intent and signs what they decide to sign, the agent maintains the mechanisms. Context Architecture guarantees that a claim is bound to something that fails, not that the claim is the right one nor that the mechanism is sufficient. Knowing what to claim is still human judgment, the one scarce resource this architecture does not supply. That is why the set of verifications is the part that gets reviewed the most, not the part that gets delegated the most. # The Context Architecture skill, run it with your agent The skill is the specification, turned into something your agent runs. One Markdown file. You load it, point it at a repo, and it reads the code as a reader with no memory, audits it against the [nine principles](https://context-architecture.dev), and finds the claims the repository makes about itself that are not bound to a mechanism that fails when they stop being true. Then it hands back the backlog in the order the [guide](https://context-architecture.dev/guide) lays out. No server, no dependency, no special tooling. It is a file your agent reads, which is principle 05 (Capabilities Are Discoverable) applied to the skill itself. ## What it does - **Audits** the repo against the nine principles and writes a report with a verdict and the evidence behind it, one per principle: which claims are bound to a mechanism, and which are only prose. - **Finds unbound claims**: docs that cite deleted files, name renamed modules, or contradict the code, and conventions that live only in prose with nothing that fails when they break. - **Proposes a backlog**: PR-sized changes ordered by payoff, each paired with the mechanism (compiler, linter, automated test, review) that fails when its claim stops being true. - **Drafts `AGENTS.md` files** at the boundaries, holding only what you cannot get from the code. It applies from the first commit, so a repo can be born legible, and to a repo that grew without design, restructured in steps. It does the same audit either way. ## Install it One command covers most tools. The [`skills` CLI](https://skills.sh){rel=""nofollow""} reads the skill from the repo and drops it into whatever agent you have: ```bash npx skills add sergioazoc/context-architecture ``` It asks which tool to install into. Pass `-a ` to pick one (for example `-a claude-code`), `-g` to install it for all your projects, and `-y` to skip the prompts. The per-tool sections below cover the manual path if you would rather drop the file in yourself, or your tool is not on its list. ### Claude Code ```bash npx skills add sergioazoc/context-architecture -a claude-code -g ``` By hand, with no Node: save the file into a folder named for the skill, then restart Claude Code. The folder name is what you type as the `/context-architecture` command, so keep it exactly that. ```bash mkdir -p ~/.claude/skills/context-architecture curl -fsSL https://context-architecture.dev/skill.md -o ~/.claude/skills/context-architecture/SKILL.md ``` Drop the `~/.claude` for a personal install; use `.claude/skills/context-architecture/SKILL.md` to scope it to one project instead. ### Cursor Save it as a project rule. The `.mdc` extension matters, a plain `.md` in that folder is ignored: ```bash mkdir -p .cursor/rules curl -fsSL https://context-architecture.dev/skill.md -o .cursor/rules/context-architecture.mdc ``` The skill's `description` frontmatter tells Cursor to pull the rule in when it is relevant. ### GitHub Copilot (VS Code) VS Code reads Agent Skills natively, the same `SKILL.md` format. The folder must be named for the skill, or Copilot will not load it: ```bash mkdir -p .github/skills/context-architecture curl -fsSL https://context-architecture.dev/skill.md -o .github/skills/context-architecture/SKILL.md ``` On JetBrains, or older Copilot without skills, paste the file into `.github/copilot-instructions.md` instead. ### OpenAI Codex ```bash mkdir -p ~/.agents/skills/context-architecture curl -fsSL https://context-architecture.dev/skill.md -o ~/.agents/skills/context-architecture/SKILL.md ``` Use a project-local `.agents/skills/context-architecture/SKILL.md` to scope it to one repo. Restart Codex if it does not pick the skill up. ### Other tools Same idea: the file goes where the tool reads its rules. - **Windsurf**: `.windsurf/rules/context-architecture.md`. If Windsurf complains about size, point it at the file instead of pasting the whole thing. - **Cline**: `.clinerules/context-architecture.md`. - **Zed**: append it to your `AGENTS.md`, which Zed reads. A loose `.rules` file can shadow an existing one, so appending is safer. - **Aider**: save it as `CONVENTIONS.md`, then run `aider --read CONVENTIONS.md`. ### Any other agent Grab the raw file and paste it into your tool's instructions, or point the tool at it: ```bash curl -fsSL https://context-architecture.dev/skill.md ``` It is self-contained. It restates the rule and the nine principles, so it works with no way back to this site. ## Use it Load the skill and point your agent at a repo: > Apply the Context Architecture skill to this repository. It writes the audit first, read-only, then the ordered backlog. Work it one change at a time, each landing with the mechanism that fails when its claim stops being true. Start where it tells you to: the claims that are only prose, and the `AGENTS.md` files at the top boundaries. That is where you get the most back per edit. ## Keep it updated Updates travel through the default branch: a change reaches anyone only once it is merged to `main` and the site is redeployed. After that, how you pull it in depends on how you installed it. - **Claude Code plugin** (`/plugin marketplace add`): run `/plugin marketplace update context-architecture`. Each release bumps the plugin version, so Claude Code sees a new version and fetches it. An unchanged version is treated as cached and skipped, which is why every change to the skill ships with a version bump. - **`skills` CLI**: re-run `npx skills add sergioazoc/context-architecture`. It overwrites the installed copy from the repo. - **Manual install (`curl`)**: re-run the same `curl ... -o ` you installed with; it overwrites the file. Claude Code picks up an edited `~/.claude/skills/...` file within the session, no restart. ## Where to go next - The [specification](https://context-architecture.dev): the rule, the loop, the kinds of mechanism, and the nine principles. - The [guide](https://context-architecture.dev/guide): the same work, done by hand, step by step. - The [glossary](https://context-architecture.dev/glossary): the terms the skill uses, defined. # Context Architecture vs. context engineering vs. harness engineering Los términos se confunden fácil porque todos tocan agentes de IA y código. No son competidores. Operan sobre objetos distintos, en capas distintas. La distinción se traza mejor con una sola pregunta: ¿qué diseña cada uno? ## Las tres disciplinas | Disciplina | Qué diseña | Capa | Pregunta que responde | | ------------------------ | -------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------- | | Context engineering | El contenido de la ventana de contexto | Runtime | ¿Qué ve el modelo ahora mismo? | | Harness engineering | El entorno de ejecución del agente | Infraestructura / operación | ¿Cómo opera el agente de forma segura y se autocorrige? | | **Context Architecture** | **El codebase mismo** | **Arquitectura de software (diseño)** | **¿Cómo se estructura el sistema para que personas y agentes lo entiendan?** | :diagram-layers ## El codebase como entrada vs. el codebase como objeto Las otras disciplinas tratan al codebase como una *entrada*. El harness lo lee. Context engineering lo comprime en una ventana. El agente lo navega. En todos los casos el codebase es un dato dado, algo que se consume. Context Architecture trata al codebase como el *objeto de diseño*. Pregunta cómo debería estructurarse el repo en primer lugar, antes de que algún agente lo lea. Y hay una relación causal entre los dos. Un codebase con buena Context Architecture le baja el trabajo a toda otra capa: menos que comprimir en runtime, menos guardrails correctivos en el harness, menos errores que parchar entre sesiones. La estructura bien hecha en tiempo de diseño rinde en todo lo que viene aguas abajo. ## Una analogía Harness engineering diseña el vehículo y sus controles de seguridad. Context engineering decide qué mapa cargar en cada viaje. Context Architecture es el urbanismo de la ciudad misma: calles con nombres claros y barrios con lógica interna dejan que cualquier conductor, persona o agente, navegue sin un GPS sofisticado. Una ciudad bien planificada no es una función que le atornillas a una mala. Es el sustrato que abarata cada trayecto por ella. Esa es la relación de Context Architecture con las capas de arriba. # Glosario: Context Architecture y los términos adyacentes Los términos en torno a los agentes de IA y el código se usan de forma laxa y se confunden. Este glosario le da a cada uno una definición corta y autocontenida, y dice cómo se relaciona con Context Architecture. Para el tratamiento completo de las tres disciplinas, ver la [comparación](https://context-architecture.dev/es/comparacion). ## Context Architecture Una arquitectura de software para la era de los agentes de IA: estructura un repositorio para que todo lo que afirma sobre sí mismo, su estructura, su comportamiento y quién puede cambiarlo, sea legible para el agente que escribe el código y para las personas que responden por él, y esté atado a un mecanismo que falla cuando esa afirmación deja de ser cierta. Trata el repositorio mismo (su árbol de archivos, fronteras, convenciones y contexto embebido) como un artefacto diseñado, no como un accidente de su crecimiento. Es la contraparte estructural de context engineering y harness engineering. Introducida por Sergio Azócar en octubre de 2025. ## Context engineering La disciplina de runtime que decide qué entra a la ventana de contexto del modelo en cada paso: qué archivos, instrucciones y resultados de herramientas se cargan. Diseña los contenidos de la ventana. Context Architecture diseña aquello que la ventana mira, el codebase. Una mejor Context Architecture significa que hay menos que comprimir en runtime. ## Harness engineering La disciplina operacional que diseña el entorno donde corre un agente: el bucle de ejecución, las herramientas que puede invocar y los guardrails que lo mantienen seguro y le permiten autocorregirse. Diseña el entorno de operación del agente. Context Architecture diseña el codebase sobre el que ese entorno opera. Una mejor Context Architecture significa menos guardrails correctivos en el harness. ## AGENTS.md Un archivo de contexto embebido ubicado en una frontera con significado dentro de un repositorio, que contiene solo lo que no se puede aprender leyendo el código: la fuente de verdad, los invariantes, la deuda técnica aceptada y la razón que un spec dejó atrás. Como está junto al código, se revisa en el mismo pull request, envejece al mismo ritmo y lo encuentra el mismo agente que está por editarlo. `CLAUDE.md` es el equivalente específico de herramienta que leen algunos agentes. En Context Architecture, un `AGENTS.md` es el artefacto del segundo principio (El contexto vive con el código), y cada afirmación que hace debería estar ligada a un mecanismo. ## Spec-driven development Escribir la intención como una especificación antes de que el código exista: el spec define el qué, no el cómo, con criterios de aceptación contra los que se verifica la implementación. En Context Architecture (sexto principio, La intención se convierte en mecanismo), el spec es andamiaje de tiempo de diseño, no un artefacto durable. Una vez que sus criterios de aceptación se vuelven tests, sus contratos se vuelven tipos y sus convenciones se vuelven lint, cumplió su función y se elimina, para que no pueda derivar. Se conserva solo cuando sigue siendo generativo, alimentando generación de código o un bucle spec-driven. ## Context-rot El deterioro silencioso de la documentación a medida que el código que describe cambia: un doc que cita un archivo borrado, nombra un módulo renombrado o contradice el comportamiento actual, mientras todavía se lee como autoritativo. Un lector con confianza lo obedece, así que el contexto podrido es peor que no tener ninguno. La regla en el corazón de Context Architecture existe para prevenirlo: toda afirmación que un repositorio hace sobre sí mismo debe estar ligada a un mecanismo que falla cuando esa afirmación deja de ser verdad. ## Hacia dónde seguir - La [especificación](https://context-architecture.dev/es): la regla, el espectro de autonomía, los mecanismos y los nueve principios. - La [comparación](https://context-architecture.dev/es/comparacion): Context Architecture vs. context engineering vs. harness engineering. - La [guía](https://context-architecture.dev/es/guia): cómo aplicarla a un codebase existente. # Cómo aplicar Context Architecture La [especificación](https://context-architecture.dev/es) dice qué es Context Architecture y por qué. Esta página es la parte que haces con las manos. Aplica en dos situaciones, y eliges tu camino según en cuál estás. Estás arrancando un repositorio nuevo. Lo quieres legible de nacimiento: la estructura dice qué hace el sistema, y cada afirmación que hace sobre sí mismo queda atada a un mecanismo desde el primer commit. Nada se ha desviado todavía, así que el trabajo es evitar que la deriva empiece. Salta a [arrancar un repo legible](https://context-architecture.dev/#path-a-arrancar-un-repo-legible). Tienes un repositorio que ya creció. Partió limpio y creció tres años. Las convenciones se separaron. Los docs dejaron de calzar con el código. Los nombres de las carpetas te dicen qué framework armó la cosa, no qué hace la cosa. Pásaselo a un lector sin memoria, alguien en su primer día o un agente arrancado en frío, y pídele un cambio: no puede saber qué significa nada, dónde va el cambio, ni cuál de dos patrones que conviven es el actual. Nadie lo diseñó para que se pudiera leer. Salta a [reordenar un repo que creció](https://context-architecture.dev/#path-b-reordenar-un-repo-que-crecio). Ambos caminos convergen en el mismo estado final y el mismo loop. La diferencia es solo el punto de partida y el costo. Nacer legible es más barato, pagas a medida que avanzas. Reordenar es más caro, pagas lo que ya se acumuló, en pasos. ## El loop, en cualquiera de los dos casos Trabajar con un agente es un flujo continuo de cambios de código. Context Architecture vive dentro de ese flujo, no aparte. Cada cambio hace dos cosas: 1. **Escribir la afirmación.** Cuando un cambio introduce o modifica algo que el repo sostiene sobre sí mismo, una fuente de verdad, una invariante, una convención, escribes esa afirmación donde corresponde. 2. **Verificarla.** Atas esa afirmación a un mecanismo que falla cuando deja de ser cierta, en el mismo cambio. Repite en cada cambio. Un repo nuevo corre este loop desde el primer commit. Un repo existente también lo corre, más un backlog de afirmaciones que nunca se ataron, que vas resolviendo en pasos. Esa es toda la diferencia entre los dos caminos. Por eso el contexto crece con el sistema en lugar de quedarse atrás. No es un montaje que haces una vez, es una propiedad que se mantiene cambio a cambio. Cuando un cambio agrega una afirmación y la deja suelta, la revisión, de una persona o de un agente, lo detecta y exige atarla antes de aceptar el cambio. ## El único lector para el que diseñar ::callout{color="neutral"} Asume un lector que no guarda nada entre sesiones y solo sabe lo que el repo dice en voz alta. Un agente de IA es exactamente ese lector. Alguien recién llegado se le acerca. La pregunta debajo de todo es una sola: cuánto demora ese lector en hacer un cambio correcto. :: ## Antes de empezar: ¿vale la pena? Tiene un costo real. La estructura inicial, los checks que son código que tienes que mantener en verde, y un pequeño impuesto en cada cambio para que cada afirmación quede atada a un mecanismo. Se paga en proporción a cuánto trabajo de agentes o de varias personas absorbe el repo. Vale la pena en un codebase que aguanta refactors, migraciones, features con spec, contribuciones de agentes. No vale la pena en un prototipo desechable ni en un problema que todavía no entiendes. Ahí el impuesto cuesta más de lo que devuelve, y saltártelo es lo correcto. Decirlo en voz alta es parte de la disciplina. Esto vale para los dos caminos. Un repo nuevo que sabes que es desechable tampoco necesita la disciplina. ## Path A: arrancar un repo legible Un proyecto nuevo parte con la estructura que le da su framework. Esa estructura nombra el framework, no el producto, y la deriva empieza el día en que la segunda persona hace commit. Arrancar legible significa que no heredas ese default para después pelearte con él. Construyes en el orden en que caen los principios, y cada pieza llega con su mecanismo: 1. **Distribuye el primer nivel por dominio, no por capa de framework.** `billing/`, `onboarding/`, `payments/`, no `controllers/`, `services/`, `utils/`. El framework vive un nivel más abajo, dentro del dominio al que sirve. Hacerlo el día uno no cuesta nada; hacerlo después de tres años es el movimiento más caro que hay. 2. **Nombra cada frontera por lo que posee.** Nada de `utils/`, `common/`, `helpers/` como cajón de sastre por defecto. Un `shared/` chico para código genuinamente genérico y sin dependencias está bien, y se mantiene chico. El mecanismo: una regla de lint que da error cuando un archivo queda en una carpeta que no corresponde a su dominio, y una regla de imports que rompe la compilación cuando un módulo cruza una frontera que no debería. 3. **Pon un `AGENTS.md` raíz desde el primer commit**, y uno en cada frontera a medida que la creas. Contiene solo lo que el código no puede decir por sí mismo: la fuente de verdad, los invariantes, la deuda técnica que tomaste a propósito. El mecanismo: una prueba que falla si un `AGENTS.md` cita una ruta que ya no existe. 4. **Codifica cada convención en el momento en que la decides**, en vez de escribirla en un doc y confiar. La primera vez que dejarías un comentario de review, hazlo una regla de lint o un tipo en su lugar. Una convención que un agente no puede leer es una convención que va a romper. 5. **Ata el comportamiento a una prueba, no a una frase.** La primera vez que escribes "esta operación responde dentro de cierto tiempo" o "este formato no se puede romper para quienes ya lo usan", esa línea llega con la prueba automatizada que se pone en rojo cuando deja de sostenerse. 6. **Genera la lista de capacidades, no la mantengas a mano.** Desde el primer script, mantén scripts y comandos en lugares predecibles y nombrados y genera la lista a partir de esas rutas, con una prueba que falla si una capacidad real no aparece en ella. 7. **Ata la propia superficie de verificación.** El conjunto de pruebas y reglas es también una afirmación. Protégelo para que un cambio no pueda debilitar ni borrar un check para colarse. Hecho así, los cinco modos de falla de abajo nunca alcanzan a acumularse. No estás deshaciendo la deriva, te estás negando a empezarla. Cuando terminas el montaje, ya estás corriendo [el loop](https://context-architecture.dev/#el-loop-en-cualquiera-de-los-dos-casos): cada cambio nuevo escribe sus afirmaciones y las ata en el mismo cambio. ## Path B: reordenar un repo que creció No estás construyendo una ciudad nueva, le estás poniendo nombres a las calles de una que ya se desparramó. Hazlo de a poco. No detienes todo para reorganizar de una. Aterrizas un cambio acotado y reversible a la vez, y cada uno llega con el mecanismo que mantiene honesta su afirmación. Nada de reescribir todo de golpe. El orden va de lo más barato y seguro a lo más caro: 1. Lee el repo como un lector en frío, y nombra los modos de falla con los que choques. 2. Arregla los docs que mienten. 3. Pon `AGENTS.md` en las fronteras de arriba. 4. Convierte el comentario que más repites en review en una regla de lint. 5. Desarma una carpeta cajón de sastre. 6. Haz que las capacidades se encuentren. 7. Avanza hacia una estructura por dominio, al final, y solo si se gana el costo de mover todo. No hay un paso final aparte para "encender" el loop. Una vez que un cambio escribe sus afirmaciones y las ata, ya estás corriendo [el loop](https://context-architecture.dev/#el-loop-en-cualquiera-de-los-dos-casos). Los pasos de abajo son el backlog de afirmaciones que el repo nunca ató; el loop es lo que evita que una nueva quede suelta de nuevo. El resto de este camino es un paso por sección, y después un ejemplo completo. ### Paso 1: auditar el repo como un lector en frío Abre el repo como si nunca lo hubieras visto y no recordaras nada. Lee el árbol de primer nivel, luego las fronteras, luego un puñado de archivos hoja. En cada nivel, una pregunta: ¿podría hacer un cambio correcto acá sin preguntarle a nadie? Cada "no" es un defecto que acabas de encontrar. Los defectos vienen en cinco formas. Son señales de diagnóstico, los síntomas que buscas cuando un repo calla sobre sí mismo, no una ley fija. Un modelo mejor baja la frecuencia de cada uno, pero no los elimina donde el repo no dice nada en voz alta: sin una fuente de verdad que encontrar, hasta un modelo fuerte reimplementa; con dos convenciones vivas y nada que diga cuál es la actual, igual tiene que adivinar. 1. **Reimplementación.** La fuente de verdad no se podía encontrar, así que el lector reconstruye lo que ya existe. 2. **Estructura inventada.** No se impuso ninguna, así que el lector impone la suya. 3. **Obediencia a docs falsos.** Cita archivos borrados o contradice el código actual, con total confianza. 4. **Propagación de patrón obsoleto.** Copia el patrón más ruidoso aunque ese patrón esté muerto. 5. **Cara o sello con la ambigüedad.** Dos convenciones conviven, así que usa la que leyó primero. Anota, por principio, un veredicto y la evidencia. Hazlo a mano, o carga el [skill de Context Architecture](https://context-architecture.dev/es/skill) en tu agente y deja que escriba el informe. **Cómo se ve esto.** En un servicio de pagos, la primera pasada encuentra la lógica de reembolsos repartida en tres carpetas (una reimplementación esperando para ocurrir), un `README` que apunta a un script de deploy borrado hace meses (docs falsos) y dos helpers de fecha con firmas distintas (un cara o sello). Tres modos de falla nombrados antes de tocar una línea. ### Paso 2: arreglar el context-rot primero Parte por hacer que los docs dejen de mentir. Un doc que cita un archivo borrado o contradice el código es peor que no tener doc, porque un lector con confianza hace lo que dice. Encuéntralo a mano o con un script: saca cada ruta de archivo, comando, símbolo y enlace de tu `README`, tus archivos `AGENTS.md` y `CLAUDE.md`, y tus documentos de diseño, y verifica que cada uno siga existiendo o siga corriendo. Arregla cada mentira contra lo que el código realmente hace hoy. Después haz que el rot sea imposible de traer de vuelta. Agrega un test que afirme que cada ruta que los docs citan sigue existiendo en disco. Ahora "este doc es preciso" es una afirmación con un mecanismo detrás, en vez de un deseo. **Cómo se ve esto.** El `README` documenta un `deploy.sh` que se borró hace un año. Sacas la referencia muerta, escribes el comando real y agregas ese test de rutas. La próxima vez que alguien mueva un archivo por debajo de un doc, la suite se pone roja en el mismo cambio, no en producción seis semanas después. ### Paso 3: poner AGENTS.md en las fronteras de arriba El contexto va junto al código que describe, en cada frontera que es dueña de algo. Puesto ahí, envejece al mismo ritmo que el código y lo lee el mismo agente que está por editarlo. Empieza por la raíz y los dos o tres directorios de más tráfico. Ahí cada `AGENTS.md` compra la mayor legibilidad. Escribe solo lo que no puedes sacar leyendo el código: la fuente de verdad, los invariantes, la deuda técnica que aceptaste a propósito, y el razonamiento que un spec dejó atrás. Mantén cada uno corto. ```markdown # AGENTS.md (billing) Dueño de la facturación, los reembolsos y el calendario de cobranza. ## Fuente de verdad Los precios vienen del paquete `pricing-engine`, nunca hardcodeados acá. ## Invariantes - Un reembolso nunca excede el monto capturado. Lo hace cumplir `refunds/guard.test.ts`. - Todo el dinero es enteros en centavos, sin floats. Lo hace cumplir la regla lint `no-float-money`. ## Deuda técnica aceptada La ruta legacy `chargeV1` se queda hasta la migración 2026-Q3. No la extiendas. ``` Mira los invariantes: cada uno nombra el mecanismo que lo hace cumplir. Ese es todo el punto. Un invariante sin nada detrás es solo una línea nueva que se puede pudrir. Si el mecanismo todavía no existe, escríbelo en el mismo cambio, o redacta la línea como un hueco conocido, no como una garantía. ### Paso 4: codificar la convención más repetida Toma el comentario que más dejas en review, el que vive solo en la cabeza de tu equipo, y ponlo en la cadena de herramientas. Una convención que un agente no puede leer es una convención que va a romper, siempre. Este es el movimiento en el que se apoyan los demás pasos. Cuando una afirmación tiene que sostenerse, así se sostiene: una regla de lint que enuncia la convención y falla en el mismo lugar, o un tipo que hace que lo incorrecto no compile. **Cómo se ve esto.** El comentario que más dejas es "importa desde la raíz del paquete, no rutas profundas". Hoy vive en la cabeza de quienes revisan, así que un agente lo rompe en su primer commit. ```text # antes: una convención que vive en la cabeza de quienes revisan "siempre importar desde la raíz del paquete, nunca rutas profundas" # después: la convención, escrita y exigida .oxlintrc.json # una regla no-restricted-imports que falla la ruta profunda en CI ``` Una vez que la regla está en el linter, la ruta profunda falla al toque, con un mensaje que cita la regla, no a quien revisó y justo estaba prestando atención ese día. ### Paso 5: nombrar una frontera de cajón de sastre `utils/`, `common/`, `helpers/`, `core/`, `lib/`. Acá es donde la responsabilidad va a morir. Nada en el nombre frena al código no relacionado, así que la carpeta crece para siempre. Elige la peor y divídela en carpetas cuyos nombres digan, cada uno, de qué son dueñas. ```text # antes src/utils/ # 40 archivos no relacionados # después src/pricing/ # la matemática de precios que estaba escondida en utils src/auth-session/ # los helpers de sesión que estaban escondidos en utils src/shared/ # lo que es genuinamente genérico, chico y sin dependencias ``` El nombre está haciendo el trabajo. Una carpeta llamada `pricing` resiste el código que no es sobre pricing, porque deja de calzar. Si no puedes nombrar una frontera con precisión, la frontera está mal, y `shared` no es la respuesta. Un `shared/` chiquito para un formateador de fechas o un tipo result está bien. La deuda es echar mano del nombre genérico para esquivar la pregunta de dónde va algo. ### Paso 6: hacer las capacidades descubribles Una capacidad que un agente no puede encontrar es, para ese agente, una capacidad que no existe. Simplemente la rehace, o la salta. Mueve tus scripts, generadores y comandos a lugares predecibles y nombrados, y nómbralos por lo que hacen: scripts de `package.json`, un directorio `scripts/` o `skills/`, comandos que de verdad escribiste. Mejor todavía, genera la lista de capacidades a partir de esas rutas convencionales en vez de mantenerla a mano, y testea que la lista esté completa. Una lista mantenida a mano es una afirmación más esperando para pudrirse. **Cómo se ve esto.** Tres scripts de deploy y de seed viven en el directorio personal de un ingeniero y un hilo de Slack que nadie encuentra. Los mueves a `scripts/` con nombres que dicen qué hacen y los listas en `package.json`. El siguiente agente los encuentra donde mira primero, en vez de escribir un cuarto. ### Paso 7: avanzar hacia una estructura por dominio (al final) El primer nivel debería decir qué hace el sistema, no qué framework lo armó: `billing/`, `onboarding/`, `payments/`, no `controllers/`, `services/`, `utils/`. El framework vive un nivel más abajo, dentro del dominio al que sirve. Este es el movimiento caro y el más propenso a romper imports, así que va al final y va en tajadas. A menudo un movimiento parcial más un `AGENTS.md` en la raíz que explica la estructura hacia la que migras compra más legibilidad, por archivo movido, que reorganizar todo de una. ```text # antes: organizado por capa técnica src/ controllers/ services/ models/ utils/ # después: organizado por dominio, el framework un nivel más abajo src/ billing/ controllers/ # el framework, dentro del dominio al que sirve services/ models/ onboarding/ payments/ ``` Evita que se devuelva con una regla de lint que impide que el código de dominio se filtre a una carpeta de capa, y mantén la estructura objetivo en el `AGENTS.md` raíz para que un lector que cae a mitad de la migración sepa hacia dónde es adelante. ## Un ejemplo completo, de principio a fin Esto recorre el Path B, el más difícil. Un servicio que empezó como una app de un framework y creció tres años. El árbol grita el framework, no el producto, y el único doc es un `README` que está medio equivocado. ```text # antes src/ controllers/ # 22 archivos, dominios mezclados services/ # 18 archivos, dominios mezclados models/ utils/ # el cajón de sastre helpers/ # un segundo cajón de sastre README.md # apunta a un script de deploy borrado el año pasado ``` Pídele a un agente "agregar un flujo de reembolso parcial" acá y míralo chocar con tres de los cinco modos de falla en una sola tarea: no encuentra dónde viven los reembolsos (repartidos entre `controllers/`, `services/`, `models/`), rehace matemática de dinero que ya está en `utils/`, y sigue el `README` hacia un script de deploy que ya no está. El arreglo, en el orden de arriba, sin un solo commit de golpe: 1. **Context-rot.** Saca la referencia muerta al deploy del `README`, escribe el comando real, agrega un test de que cada ruta que el `README` y los `AGENTS.md` citan sigue existiendo. 2. **Contexto embebido.** Un `AGENTS.md` raíz (qué posee el servicio, la estructura hacia la que migra) y uno en el área de más tráfico. 3. **Codificar.** El comentario de review más repetido era "el dinero es enteros en centavos". Eso pasa a ser una regla lint `no-float-money`. 4. **Nombrar.** Divide `utils/` y `helpers/`: la matemática de dinero pasa a `money/`, el código de sesión a `auth-session/`, el resto genuinamente genérico se queda en un `shared/` chico. 5. **Descubrible.** Los scripts ad-hoc se mueven a `scripts/` con nombres reales, listados en `package.json`. 6. **Por dominio, en tajadas.** Mueve `refunds` primero: un `billing/refunds/` que mantiene juntos su controller, su service y su model. El siguiente agente que pregunte por reembolsos los encuentra en un solo lugar. ```text # después src/ billing/ AGENTS.md # invariantes y la fuente de verdad de billing refunds/ # controller + service + model, juntos invoices/ auth-session/ money/ # la matemática que estaba enterrada en utils, ahora nombrada y exigida shared/ # chico, genérico, sin dependencias scripts/ # nombrados, listados en package.json AGENTS.md # las reglas de la casa, y la estructura hacia la que se migra README.md # preciso, y un test lo mantiene así ``` Ahora la misma tarea aterriza en `billing/refunds/`, contra un `AGENTS.md` que enuncia el invariante del reembolso, reutilizando el paquete `money/` al que la regla lint ya apunta. Cada afirmación que el repo hace está atada a un mecanismo, y de aquí en adelante el loop la mantiene así: el siguiente cambio que agrega una afirmación la ata en el mismo cambio. Los modos de falla no tienen dónde ocurrir. ## Correrlo con el skill El paso 1 y casi todos los movimientos de arriba son cosas que un agente puede correr. El [skill de Context Architecture](https://context-architecture.dev/es/skill) es un solo archivo que cargas en tu agente: lee el repo como un lector en frío, encuentra los docs que mienten y te devuelve el backlog en el orden de arriba. Apúntalo a tu repositorio y empieza por lo que marca primero. ## Hacia dónde seguir - La [especificación](https://context-architecture.dev/es): la regla, el espectro de autonomía, los tipos de mecanismo y los nueve principios completos. - La [comparación](https://context-architecture.dev/es/comparacion) con context engineering y harness engineering: qué capa diseña cada una, y por qué esta se sitúa debajo de ellas en tiempo de diseño. - El [skill](https://context-architecture.dev/es/skill): para correr el trabajo con tu propio agente. - El [glosario](https://context-architecture.dev/es/glosario): los términos que se usan en la especificación, definidos. # Context Architecture ## La regla Una arquitectura de software para agentes se reduce a una regla. ::rule Toda afirmación que un repositorio hace sobre sí mismo debe estar ligada a un mecanismo que falla cuando esa afirmación deja de ser verdad. :: Esa es toda la arquitectura. Lo demás es cómo se aplica. La regla se evalúa sobre cualquier repositorio, afirmación por afirmación. Toma cada cosa que el repositorio sostiene sobre sí mismo (dónde vive la fuente de verdad, cuál es el patrón correcto, qué no se debe tocar) y pregunta si hay un compilador, una regla de linter, una prueba automatizada o un paso de revisión que se rompe cuando eso deja de ser cierto. Si no lo hay, es prosa, y la prosa se desactualiza en silencio. Una afirmación es cualquier cosa que el repositorio sostiene sobre sí mismo, no solo la forma de sus carpetas. "Los precios se calculan en este módulo y en ningún otro" es una afirmación. "Esta operación responde dentro de cierto tiempo" es una afirmación. "Este formato de datos no se rompe para quienes ya lo usan" es una afirmación. Todas son del mismo tipo: algo que el repositorio promete, y que en algún momento puede dejar de ser cierto. El mecanismo tiene que fallar de verdad, no solo existir. Una prueba de rendimiento que nunca ejercita la parte lenta no cumple la regla, la incumple. O la afirmación está atada a algo que se pone en rojo cuando se rompe, o no lo está. La regla se aplica a sí misma. El conjunto de pruebas y reglas que verifican el repositorio es, a su vez, un conjunto de afirmaciones sobre el repositorio, así que también está atado a un mecanismo que falla si se debilita. La arquitectura tiene que sostenerse con o sin una persona revisando el código. Cuando una persona revisa, los mecanismos hacen la revisión que esa persona haría a mano. Cuando no hay persona, los mecanismos son el revisor. ## El problema Durante años la arquitectura optimizaba una cosa: cuánto tardaba un ingeniero nuevo en entender el código. El lector cambió. Hoy buena parte del código que llega a producción lo lee y lo escribe un agente. Escribir código dejó de ser el cuello de botella. Los modelos escriben bien y se revisan a sí mismos cada vez mejor. El cuello se movió a verificar que un volumen creciente de cambios no rompe nada, a la velocidad a la que el agente los produce. Una tasa de error chica, multiplicada por ese volumen y esa velocidad, sin un mecanismo que falle cuando una afirmación se viola, es ruptura silenciosa a escala. Toma dos formas. Con una persona revisando, la verificación no escala: el código se genera más rápido de lo que se puede leer, y termina aprobando lo que no alcanza a revisar. Sin una persona, un cambio que parece correcto se integra, porque nada falló cuando se violó una afirmación que solo vivía en prosa. El trabajo de la arquitectura no es que el agente se equivoque menos. De eso se encarga el modelo, y cada vez mejor. El trabajo es que cada afirmación violada falle de inmediato, en el lugar donde se rompió, en vez de integrarse en silencio. Por eso el problema crece con mejores modelos en vez de desaparecer: cuanto más rápido y más autónomo el agente, más indispensable que el repositorio se verifique solo. > Diseña para un lector que no recuerda nada entre sesiones y solo sabe lo que el repositorio dice en voz alta. Un agente lo cumple exacto. Una persona nueva lo aproxima. ## El espectro de autonomía Context Architecture funciona con o sin una persona en el loop. Hoy lo normal es alguien orquestando al agente; cada vez más trabajo pasa a agentes corriendo solos. La arquitectura tiene que servir todo el rango. | Nivel | Quién revisa | Qué se rompe sin disciplina del repositorio | | ---------- | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | Inline | una persona aprueba cada edición | el agente reimplementa cosas que ya existen y la persona quema tiempo corrigiendo lo que las herramientas pudieron atrapar | | Async | una persona revisa el cambio antes de integrarlo | la revisión no escala; el control de integración existe pero no exige nada, basta un clic para pasar un cambio | | Autónomo | una persona define las reglas, no mira cada cambio | si faltan los mecanismos, la definición de "listo" es hueca: el agente da por terminado un cambio que pasa pero está mal | | Orquestado | nadie en el medio | el error se multiplica a velocidad de máquina; lo único que arbitra son los mecanismos del repositorio | Lo que cambia a través del espectro es quién consume la verificación, no la verificación. El mismo `AGENTS.md` y los mismos mecanismos sirven en una sesión interactiva, en un cambio que se revisa aparte y en un agente corriendo solo. Cuando hay una persona, los mecanismos absorben la revisión rutinaria, así la persona gasta su atención en lo que requiere criterio, no en re-chequear una convención. Cuando no hay persona, los mecanismos son el revisor. ## Cómo se aplica Trabajar con un agente es un flujo continuo de cambios de código. La regla vive dentro de ese flujo, no aparte. Cada vez que un cambio introduce o modifica algo que el repositorio sostiene sobre sí mismo (una nueva fuente de verdad, una invariante, una convención), ese algo queda atado a un mecanismo en el mismo cambio. Y cada cambio que toca código existente se encuentra con los mecanismos que ya están ahí: si viola una afirmación, algo se pone en rojo antes de llegar a producción. Por eso el contexto del repositorio crece con el sistema en lugar de quedarse atrás. No es un montaje que haces una vez, es una propiedad que se mantiene cambio a cambio. Cuando un cambio agrega una afirmación nueva y la deja suelta, la revisión, sea de una persona o de un agente, lo detecta y exige atarla antes de aceptar el cambio. Atar una afirmación es conectarla a algo que falla cuando deja de ser cierta. Context Architecture nombra los tipos de mecanismo, no la herramienta: - **El compilador** atrapa lo que se puede expresar en tipos: reintroducir una importación prohibida rompe la compilación. - **El linter** atrapa problemas de estructura y de convención: un archivo en la carpeta equivocada falla el lint y cita la regla que incumple. - **Las pruebas automatizadas** atrapan documentación que miente y comportamiento que se sale de lo esperado: un `AGENTS.md` que menciona un archivo borrado pone las pruebas en rojo. - **La revisión**, de una persona o de un agente, atrapa lo que las otras no ven, el sentido: en cada cambio pregunta si quedó algún documento diciendo algo falso, y exige corregirlo en el mismo cambio. El reparto con la infraestructura donde corre el agente es claro: Context Architecture decide qué se verifica y garantiza que el mecanismo existe y falla. La infraestructura lo ejecuta. Atar la afirmación es de la arquitectura; correr ese mecanismo en cada cambio es del entorno. ## Los principios Cada principio es una propiedad que se puede comprobar, no una aspiración. O es cierta de tu repositorio y está atada a un mecanismo, o no lo está. Si no se puede atar a algo que falla, no es un principio. ### Que el repositorio diga lo que es **01 · La estructura grita la intención.** El árbol de archivos dice qué hace el sistema, no qué framework lo construyó. Una carpeta `billing/` nombra una responsabilidad del negocio; una carpeta `controllers/` nombra un detalle técnico que podría ser de cualquier sistema. El framework vive un nivel más abajo, dentro del dominio que sirve. Así un lector ubica dónde va un cambio antes de leer una línea. *Mecanismo: una regla de linter que da error cuando un archivo queda en una carpeta que no corresponde a su dominio.* :diagram-tree **02 · El contexto vive con el código.** El contexto vive pegado al código que describe, en cada frontera importante, no en una wiki aparte que se desactualiza. Contiene solo lo que el código no puede decir por sí mismo: dónde está la fuente de verdad, qué invariantes hay que respetar, qué deuda técnica se aceptó a propósito, qué límites de comportamiento sostiene esa parte. Como está al lado del código, envejece a su ritmo y lo encuentra el mismo agente que va a editarlo. *Mecanismo: una prueba que falla si un `AGENTS.md` menciona un archivo que ya no existe.* **03 · Las fronteras son explícitas y tienen nombre.** Cada módulo y paquete se nombra por la responsabilidad que tiene. Carpetas como `utils/`, `common/` o `helpers/` acumulan cualquier cosa, porque el nombre no descarta nada. El código genuinamente compartido y sin dominio existe, y tiene lugar: un formateador de fechas, un tipo de resultado, un hook de interfaz reutilizable. Va en un `shared/` pequeño, sin dependencias hacia ningún dominio, y se mantiene chico. La deuda no es tener cosas compartidas, es usar el nombre genérico para no decidir dónde va algo que sí tiene dueño. Si no puedes nombrar una frontera con precisión, suele ser señal de que la frontera está mal trazada, no de que necesites otra carpeta genérica. *Mecanismo: una regla que prohíbe que un módulo importe desde otra frontera por caminos no permitidos, y rompe la compilación cuando ocurre.* **04 · El repositorio es legible a cualquier escala.** La legibilidad no es solo del primer nivel, llega hasta el cuerpo de cada función. Puedes tener una raíz impecable, `billing/`, `payments/`, y tres carpetas más abajo un archivo `helpers.ts` con una función `process(data)` que no dice qué procesa ni qué devuelve. Ahí la legibilidad se cae. La misma disciplina que te hizo nombrar `billing/` en la raíz tiene que nombrar `applyLateFee(invoice)` en la hoja, y llamar `invoice` a lo que hoy es `data`. *Mecanismo: reglas de linter sobre nombres y límites de complejidad.* **05 · Las capacidades se pueden descubrir.** Las herramientas, scripts y comandos del proyecto viven en lugares predecibles y con nombres que dicen lo que hacen: los scripts de `package.json`, una carpeta `scripts/`, una carpeta de skills. Una capacidad que existe pero que un agente no encuentra, para ese agente no existe: la vuelve a implementar desde cero. La lista de capacidades no se escribe a mano, se genera a partir de esos lugares predecibles. Una lista escrita a mano es una afirmación más que se desactualiza: alguien agrega un script y olvida anotarlo. Una lista generada a partir de las carpetas convencionales no puede dejar fuera algo que está ahí, y si queda obsoleta, una prueba lo detecta y se pone en rojo. *Mecanismo: la lista generada desde las rutas convencionales, y una prueba que falla si una capacidad real no aparece en ella.* ### Atar cada afirmación a un mecanismo **06 · La intención se convierte en mecanismo.** La intención se escribe como spec antes del código, luego se convierte en el código y en las pruebas y reglas que lo hacen cumplir, y la spec se borra cuando su contenido ya vive ahí. Lo que perdura es la intención y su verificación, no el código que la cumple: mientras las pruebas cerquen el comportamiento, ese código se puede volver a generar. Una spec se conserva solo si sigue generando algo (código, configuración); si no, se borra, para que no quede un segundo relato que se desactualiza. *Mecanismo: las pruebas, los tipos y las reglas en que la spec se convirtió.* **07 · Las convenciones se codifican, no se sobreentienden.** Una convención que vive solo en la cabeza de la gente es invisible para un agente, y la va a romper. Sácala de la cultura y ponla en las herramientas que revisan el código: reglas de linter, restricciones de tipos, validaciones automáticas en CI que enuncian la regla y la hacen cumplir en el mismo lugar. *Mecanismo: las reglas de linter y las restricciones de tipos.* **08 · El comportamiento se verifica, no se declara.** Toda afirmación sobre cómo se comporta el sistema (cuánto puede tardar una operación, qué datos no deben cruzar cierto límite, qué formato no se puede romper para quienes ya lo usan) está atada a una prueba automatizada que vive en el repositorio y se pone en rojo cuando el comportamiento se sale de lo prometido. Un límite de tiempo escrito en un documento se desactualiza; el mismo límite atado a una prueba que falla al excederlo es arquitectura. La prueba vive en el repositorio y corre antes de integrar el cambio. Si el sistema en producción además dispara una alerta cuando algo se degrada, eso ya es trabajo del entorno donde corre, no de la arquitectura. *Mecanismo: una prueba automatizada de comportamiento (rendimiento, contrato de datos, seguridad) que vive en el repositorio y falla cuando el comportamiento se desvía.* **09 · La superficie de verificación también está atada.** El conjunto de pruebas y reglas que verifican el repositorio es, a su vez, un conjunto de afirmaciones sobre el repositorio, así que también está atado. Un agente puede reescribir el código libremente, pero no puede debilitar ni borrar una prueba, una regla o una validación para que un cambio pase. Sin una persona revisando, este es el principio que más importa: la forma más barata de hacer que una validación pase es eliminarla. *Mecanismo: una validación que se pone en rojo si el conjunto de pruebas y reglas cambia sin la autorización que el repositorio definió.* ## Lo que Context Architecture no hace Una arquitectura honesta dice qué no es. No es un sistema de aislamiento ni de permisos. El entorno aislado donde corre el agente, las conexiones de red que entran y salen, las credenciales y la identidad del agente son cosa de la infraestructura, no de la arquitectura del repositorio. No es la maquinaria que ejecuta los controles. Las validaciones automáticas, la protección de ramas, los revisores obligatorios ya existen y se aplican igual sobre el cambio de un agente. Context Architecture decide qué deben comprobar, la infraestructura los corre. No es cumplimiento normativo. Es agnóstica a las regulaciones. Que una empresa necesite la firma de una persona por una norma es decisión y problema de la empresa. No impone herramientas. Nombra los tipos de mecanismo, el repositorio elige el producto. `oxlint` o `eslint`, da igual. No hace al agente más inteligente ni arregla sus alucinaciones. Hace que la verdad del repositorio se pueda comprobar de forma automática, para que el error del agente falle de inmediato y donde ocurrió, en vez de integrarse en silencio. ## Límites y costo No aplica en todos lados. Aplica a repositorios que absorben trabajo de agentes o de varias personas: refactors a escala, migraciones, features con una spec clara. Aplica desde el primer commit (un repositorio puede nacer legible) y también sobre uno que creció sin diseño, que se reestructura en pasos, nunca de un golpe. No lo apliques al primer prototipo de algo que todavía no entiendes, ni a un problema mal definido. Estructurar es una inversión que paga en proporción al trabajo que el repositorio absorbe. En un proyecto desechable, el costo supera al retorno. Hay un costo: estructurar por adelantado, mantener las pruebas y reglas que son código y hay que cuidar, una disciplina extra en cada cambio. Pero ese trabajo es mecánico, bien especificado y repetitivo, que es justo lo que un agente hace bien. La persona escribe la intención y firma lo que decide firmar, el agente mantiene los mecanismos. Context Architecture garantiza que una afirmación está atada a algo que falla, no que la afirmación sea la correcta ni que el mecanismo sea suficiente. Saber qué hay que afirmar sigue siendo criterio humano, el único recurso escaso que esta arquitectura no fabrica. Por eso el conjunto de verificaciones es la parte que más se revisa, no la que más se delega. # El skill de Context Architecture, aplícalo con tu agente El skill es la especificación, convertida en algo que tu agente corre. Un archivo Markdown. Lo cargas, lo apuntas a un repo, y lee el código como un lector sin memoria, lo audita contra los [nueve principios](https://context-architecture.dev/es) y encuentra las afirmaciones que el repositorio hace sobre sí mismo que no están atadas a un mecanismo que falla cuando dejan de ser ciertas. Después te devuelve el backlog en el orden que arma la [guía](https://context-architecture.dev/es/guia). Sin servidor, sin dependencia, sin herramientas especiales. Es un archivo que tu agente lee, que es el principio 05 (Las capacidades son descubribles) aplicado al skill mismo. ## Qué hace - **Audita** el repo contra los nueve principios y escribe un informe con un veredicto y la evidencia que lo respalda, uno por principio: qué afirmaciones están atadas a un mecanismo y cuáles son solo prosa. - **Encuentra afirmaciones sueltas**: docs que citan archivos borrados, nombran módulos renombrados o contradicen el código, y convenciones que viven solo en prosa sin nada que falle cuando se rompen. - **Propone un backlog**: cambios del tamaño de un PR ordenados por impacto, cada uno emparejado con el mecanismo (compilador, linter, prueba automatizada, revisión) que falla cuando su afirmación deja de ser cierta. - **Redacta archivos `AGENTS.md`** en las fronteras, con solo lo que no puedes sacar del código. Aplica desde el primer commit, así un repo puede nacer legible, y también sobre un repo que creció sin diseño, reestructurado en pasos. Hace la misma auditoría en ambos casos. ## Instalarlo Un comando cubre la mayoría de las herramientas. El [CLI `skills`](https://skills.sh){rel=""nofollow""} lee el skill desde el repo y lo deja en el agente que tengas: ```bash npx skills add sergioazoc/context-architecture ``` Te pregunta en qué herramienta instalarlo. Pasa `-a ` para elegir una (por ejemplo `-a claude-code`), `-g` para instalarlo en todos tus proyectos, y `-y` para saltarte las preguntas. Las secciones por herramienta de abajo cubren el camino manual, por si prefieres dejar el archivo tú mismo o tu herramienta no está en su lista. ### Claude Code ```bash npx skills add sergioazoc/context-architecture -a claude-code -g ``` A mano, sin Node: guarda el archivo en una carpeta con el nombre del skill, luego reinicia Claude Code. El nombre de la carpeta es lo que escribes como el comando `/context-architecture`, así que déjalo exactamente así. ```bash mkdir -p ~/.claude/skills/context-architecture curl -fsSL https://context-architecture.dev/skill.md -o ~/.claude/skills/context-architecture/SKILL.md ``` Quita el `~/.claude` para una instalación personal; usa `.claude/skills/context-architecture/SKILL.md` para acotarlo a un solo proyecto. ### Cursor Guárdalo como una regla de proyecto. La extensión `.mdc` importa, un `.md` plano en esa carpeta se ignora: ```bash mkdir -p .cursor/rules curl -fsSL https://context-architecture.dev/skill.md -o .cursor/rules/context-architecture.mdc ``` El `description` del frontmatter le dice a Cursor que traiga la regla cuando es relevante. ### GitHub Copilot (VS Code) VS Code lee Agent Skills de forma nativa, el mismo formato `SKILL.md`. La carpeta debe llamarse como el skill, o Copilot no lo carga: ```bash mkdir -p .github/skills/context-architecture curl -fsSL https://context-architecture.dev/skill.md -o .github/skills/context-architecture/SKILL.md ``` En JetBrains, o en un Copilot viejo sin skills, pega el archivo en `.github/copilot-instructions.md`. ### OpenAI Codex ```bash mkdir -p ~/.agents/skills/context-architecture curl -fsSL https://context-architecture.dev/skill.md -o ~/.agents/skills/context-architecture/SKILL.md ``` Usa un `.agents/skills/context-architecture/SKILL.md` local para acotarlo a un repo. Reinicia Codex si no toma el skill. ### Otras herramientas La misma idea: el archivo va donde la herramienta lee sus reglas. - **Windsurf**: `.windsurf/rules/context-architecture.md`. Si Windsurf se queja por el tamaño, apúntalo al archivo en vez de pegar todo. - **Cline**: `.clinerules/context-architecture.md`. - **Zed**: agrégalo a tu `AGENTS.md`, que Zed lee. Un archivo `.rules` suelto puede tapar uno existente, así que agregarlo al `AGENTS.md` es más seguro. - **Aider**: guárdalo como `CONVENTIONS.md`, luego corre `aider --read CONVENTIONS.md`. ### Cualquier otro agente Toma el archivo en crudo y pégalo en las instrucciones de tu herramienta, o apúntala a él: ```bash curl -fsSL https://context-architecture.dev/skill.md ``` Es autocontenido. Reenuncia la regla y los nueve principios, así que funciona sin vuelta a este sitio. ## Usarlo Carga el skill y apunta tu agente a un repo: > Aplica el skill de Context Architecture a este repositorio. Escribe primero la auditoría, solo lectura, después el backlog ordenado. Trabájalo un cambio a la vez, cada uno aterrizando con el mecanismo que falla cuando su afirmación deja de ser cierta. Empieza donde te diga: las afirmaciones que son solo prosa, y los `AGENTS.md` de las fronteras de arriba. Ahí es donde más recuperas por edición. ## Mantenerlo al día Las actualizaciones viajan por la rama por defecto: un cambio le llega a alguien solo cuando se mergea a `main` y se vuelve a deployar el sitio. Después, cómo lo bajas depende de cómo lo instalaste. - **Plugin de Claude Code** (`/plugin marketplace add`): corre `/plugin marketplace update context-architecture`. Cada release sube la versión del plugin, así Claude Code ve una versión nueva y la baja. Una versión sin cambios la trata como cacheada y la salta, por eso cada cambio en el skill viaja con un bump de versión. - **CLI `skills`**: vuelve a correr `npx skills add sergioazoc/context-architecture`. Sobreescribe la copia instalada desde el repo. - **Instalación manual (`curl`)**: vuelve a correr el mismo `curl ... -o ` con el que instalaste; sobreescribe el archivo. Claude Code toma un archivo `~/.claude/skills/...` editado dentro de la sesión, sin reiniciar. ## Hacia dónde seguir - La [especificación](https://context-architecture.dev/es): la regla, el loop, los tipos de mecanismo y los nueve principios. - La [guía](https://context-architecture.dev/es/guia): el mismo trabajo, hecho a mano, paso a paso. - El [glosario](https://context-architecture.dev/es/glosario): los términos que usa el skill, definidos.