AGENTS.md — the content plane (content/)¶
What holds inside the content plane on top of the root AGENTS.md: what done means, the invariants, and the conventions for its Django apps.
Guidance for AI coding agents working in content/, the Django + Wagtail content plane. The repository-wide rules — the plane boundary, the agent safety rules, the workflow — are in the root AGENTS.md; this file adds what holds inside this project. README.md maps the apps; ADR 0001 says why they exist.
"Done" for a change here means python -m pytest -q (with -m "not slow" as the fast loop) and python manage.py makemigrations --check --dry-run pass, ruff check . && ruff format --check . are clean, python manage.py run_evals --all --recorded passes, and the three committed schemas are current: schemas/graphql/schema.graphql (manage.py graphql_schema --out …), schemas/content/ai-schema.json (manage.py wagtail_ai_schema --out …) and schemas/openapi/openapi.json (manage.py spectacular --format openapi-json --urlconf ops.openapi --fail-on-warn --file …). CI runs the suite on SQLite and on Postgres with pgvector (content.yml), spread over the runner's cores with pytest-xdist (-n auto); the suite must pass both ways, in one process and in parallel.
Invariants¶
- Every content change goes through the registry or the accept flow. A tool is the only way an agent touches content (
agents/registry.py), andsuggestions.services.acceptis the only way a suggestion becomes a revision. Both callcms.services.save_draft/publish, which run in one transaction. Never add a second path that writes pages for an agent, and never call a tool function directly from a surface — callregistry.call. - The studio's endpoints serve people, through the same services.
api/pages.py,api/review.pyandapi/session.pyrefuse agent principals (IsPerson), check Wagtail page permissions incms.servicesandsuggestions.services, and never publish except from the publish and schedule endpoints: a save, an accepted suggestion and a revert are each a draft revision. A save must name the revision it was edited from (nullonly for a page without one) and is refused (409) when a newer one exists, and so must a publish or a schedule name the revision the person reviewed —cms.services.publish_nowandschedulecheck it under the page row's lock, so what someone else saved in between never goes live unseen (#61); the newsroom's release and an agent's tool, which act on whatever is latest by design, name none; a block the person did not change is stored as it was, never re-cleaned, and two blocks never share an id. A shape the studio reads is a serializer inapi/serializers.py, so the OpenAPI document andweb/packages/api's generated client follow it (cd web && npm run genafter regenerating the document). - Finding a page is not opening it. A person finds the pages Wagtail's explorer would show them (
cms.services.visible_pages: those they hold a permission on, the ancestors that lead there, platform page types only); opening one — its draft, fields, blocks, revisions — needs the right to edit or publish it, as Wagtail's own draft view does, and anything else is a 404. - Every page writer starts with
cms.services.writable. It takes the page row's lock for the transaction, so two writers that start from the same revision run one after the other (a second save is then stale; a second accept builds on the first's revision), and it refuses a page a Wagtail lock keeps from the person — another person's, a workflow task's, or a scheduled publish's — withPageLocked(409resource.locked). Cancelling a schedule is the one change a scheduled page's lock allows. - One scope per model.
Suggestion.objects.visible_to(user, site=None)andAgentRun.objects.visible_to(user)are how every view, resolver and service reads those rows (a reviewer may open the run behind what they may decide); a refusal never names what the person cannot see — a 404 for an invisible row, andPermissionDeniedmessages without the target's title. - Rich text travels in Wagtail's database format (
<a linktype="page" id="…">), the form every reader of a page gets;suggestions.services.clean_blockexpands it to the editor's form before the whitelist, so a link or embed the block's features allow keeps its target. - Tools declare an effect and run as an agent user.
read,propose,write,publish; the registry checks the narrower of the agent's and the page's policy, the agent's tools list (and the token's), the principal (agent:<slug>, active, never staff or superuser), Wagtail permissions as that user — and, when the call acts for a person (ToolContext.on_behalf_of: a run whose prompt and tools a person chose), that person's edit right on the page too — and the rate. A review agent never gets apublishtool. A new tool needs an input schema withadditionalProperties: false(obj()), and the cheapest effect that is true. - Agents start at
suggest; promotion is earned. A definition goes live only throughAgentDefinition.publish(), which runs the eval gate; raising the policy also needs the accept rate. Change an agent by editingagents/definitions/<slug>.yaml, never by settingliveorpolicyon a row. - One way to reach a model. Only
ai/providers/imports a provider SDK (anthropic,openai,litellm,claude_agent_sdk), each inside its adapter; everything else asks the registry (ai.providers.get), andtests/ai/test_providers.pyfails on an import anywhere else. Every AI generation a person asks for is a run of theassistantagent throughai/services.py— never a provider call inside a request — and the worker re-checks what the run uses (the rows, against its starter; the provider, enabled and in budget), since a run can start from more than one surface. - Tests never call a model. Use
FakeLLMin unit tests and recordings (agents/recordings/, placeholders instead of ids) for eval scenarios. A prompt change makes its recordings stale on purpose: re-record, don't loosen the digest check. - One revision per accepted outcome. Accept a run's suggestions together; a tool that writes (
content.draft_revision) writes one revision for all its ops. Intermediate work lives inAgentSteprows, not in revisions. - An event is emitted in the transaction that made the change.
outbox.services.emitrefuses otherwise. A new event type is a schema inschemas/events/(and an example) first, with contract tests on both planes; a breaking change is a new version. - A story's page goes live only through the newsroom, by any route. Its Wagtail workflow (
newsroom.StageTask: editing, then copy) publishes nothing when approved (WAGTAIL_FINISH_WORKFLOW_ACTION);newsroom.services.releasepublishes or schedules throughcms.servicesunder the person's publish permission, andcorrectonly adds to the page's log. Every other way a page goes live — Write's Publish and Schedule, the Wagtail admin, an agent'scontent.publish, an importer, the scheduled publish — is held tonewsroom.services.publish_refusalby thepage_publishedreceiver (newsroom/workflow.py): a story still being made, or one under embargo, is refused (409story.in_workflow/story.embargoed) and the publish rolled back with its transaction — so a new publish path must run in one. A story's status is moved bynewsroom.servicesand Wagtail's own signals, never set on the row by hand. - Agent review is never a workflow's last task. Approving the last task publishes the page as the approver, and an agent never publishes;
AgentReviewTaskrejects with that reason when it is last. - Order-preserving JSON where order is content.
BasePage.front_matteris anOrderedJSONFieldbecause Postgresjsonbsorts keys; use it for any JSON whose key order a person wrote. - The Jekyll bridge is exact. An unchanged page exports its stored source byte for byte (a page that is not live gains only
published: false, unless its file already keeps itself out of the build:sites.catalog.held_back); a changed page renders typed fields over its original front matter (dates stay the original string unless the date changed). "Unchanged" isImportedSource.unchanged, never a bare hash comparison: a page whose file a person edits (file_editor_fields: itsfile_pathand rawfront_matter,cms/files.py) also keeps its file's path and front-matter key order, which the content hash cannot see. Raw front matter never sets a key a typed field writes (front_matter_fields); a key the exporter starts writing from a field goes there in the same change. An importer never overwrites what was changed here — a page an editor changed in Wagtail, an AI row a person changed or deleted (importers.models.ImportedRecord) —--forceaside.test_the_real_sites_round_trip_byte_for_byteholds every site in this repository to that. - One Jekyll reader, one writer into a checkout. Which files of a site are content is
sites/catalog.py's answer (Jekyll 4.4's reader rules, held to Jekyll's own lists bytests/sites/test_catalog.py); never add a second walk. A site's checkout is written only by its write-back job throughsites/writer.py— plain paths, no symlink at any component, an atomic replace that re-checks the bytes — and only while each file still has the digest the platform last read or wrote (ManagedSite.digests): a file changed by hand since is a conflict, never overwritten, and an unchanged write-back writes nothing. A changed page is rendered over its original file by line surgery (sites/frontmatter.py).catalog.py,frontmatter.py,writer.pyanddoctor.pyimport nothing from Django, sopython -m sites.doctorruns where the platform does not. - A book's
library/<slug>/is generated (books/files.py). A book and its chapters render their files over theImportedSourcethey were read from — a YAML key rewritten only when its value changed, a chapter body kept while its blocks are the ones it was read as — so an unchanged book exports byte for byte (roundtrip_booksholdspackages/books/libraryto it).books.LibraryFilerecords what the platform last read or wrote in each directory, and neither side loses the other's change:export_bookskeeps a file changed by hand since (a conflict), andimport_booksnever overwrites a page changed here since, never publishes over a draft, and never brings back a page deleted here —--forceaside. Validation, statistics, manuscripts and a book task's context are computed from the rendered files, so the platform says what bookshelf said (tests/books/golden/bookshelf.json); a book task is a run of thebooksagent whose writing arrives as suggestions. - Content leaves for a channel only through
distribution.services(distribution/README.md): a post a person approved, to a channel a person armed, of a kind the deployment armed (ZER0_*_PUBLISH), every gate (distribution/gates.py) checked when it is asked for and again by the worker that sends it. The ledger is keyed by canonical URL and written in the extension's byte format (distribution/ledger.py); a write that may have landed is ledgeredunconfirmedbefore its error goes up, and nothing sends that key again until a person records or forces it. Every LinkedIn call is a declaredPlanentry whosereturnssays "own"; a WordPress address goes throughresearch/fetch.py's guard; credentials areai/crypto.py-encrypted and never returned. - Vectors live in
graph.Embedding, never on a page row (a revision would copy them), keyed by model and content hash. - Research reaches the web only through
research/fetch.py, and only in a worker. Its guard refuses any address that is not public and pins the connection to the address it checked, follows redirects by hand, honours robots.txt and caps size and time; never fetch a URL a person or a feed gave with a client of your own, and never inside a request. A run kind an app adds to theassistantagent (ai.handlers.register) generates throughai.handlers.generate, re-checks its rows withowned/used, like the AI layer's own, and proposes only throughregistry.call(research's fact-check:content.propose_edit, the one propose toolassistant.yamllists and no assistant may). - An automation acts as its owner and never publishes (
automations/). Each action calls the service a person's own request calls, as the automation's owner, and what it uses is asked again when the run executes; no action publishes (a newsroom story moves only to a stage that publishes nothing, an agent that lists a publishing tool is refused), and an automation's own work never fires another (started_by_eventcarriesautomation-run:<id>). A new trigger or action kind is a schema inautomations/spec.pyfirst; a webhook it notifies is reached through the research fetcher (fetch.post: its guard and its one deadline), in the worker; its runs — what it heard as its owner — are its owner's and staff's, never everyone's it is shared with; a new automation is paused. - The ABC lexicons are here:
agents/data/abc_lexicons/*.ymlare the only copies since the Rails generator they were vendored from was deleted (ADR 0008); edit them here. The ABC art-style catalog is not:books/data/abc_art_styles.ymlis a vendored copy of the image generator's (workspace.yml) — change the source and runbin/zer0 vendor --write. - Every non-2xx is the envelope. A REST view raises
ops.errors.ApiError(orInvalid,Forbidden,NotFound,Conflict,Locked,Unavailable) or a DRF exception and never returnsResponse({"error": …}); a GraphQL resolver raisesGraphQLErrorfor an error the client should read; MCP keeps JSON-RPC errors./healthztouches nothing — a probe view isnon_atomic_requestsand never reads the database; what needs a dependency belongs in/readyz's checks (ops/README.md). - The web role serves on threads. gunicorn reads
gunicorn.conf.py(gthread workers): a run's event stream holds its request for minutes, and a sync worker is killed at its timeout mid-stream. A stream opens with a comment frame and sends one when quiet. - Nothing logs a secret. Log through
logging(the handler redacts token shapes — an agent'szer0_…, a person'szer0u_…, the fleet's — andAuthorizationvalues); never print a token, and never put one in an exception message that a500could carry — the envelope hides the message, the log does not. Django's error reports (ops.logging.ExceptionReporterFilter, on in development too) and Sentry's events (ops.sentry) redact the same shapes in every frame's variables; mark a local that holds a credential@sensitive_variables. - Authenticating writes nothing in the request. Both bearer tokens are
accounts.tokens.HashedToken: a hash, a raw token shown once, and a use recorded at most every five minutes after the request commits — a write insideATOMIC_REQUESTSlocked the database for every parallel request a client sends. A person's token is issued, listed and revoked throughaccounts.services(90 days by default; a superuser's only on purpose; never issued by another token), and one without thewritescope is refused on anything but a read before the view (accounts.auth, and mutations inapi/views.py). The session list records a session when it starts, never on every request (USERSESSIONS_TRACK_ACTIVITYstays off). - Signing in is django-allauth's, and only allauth's. Every way into a session — a password, a code, an IdP, GitHub, a passkey, a second factor — is allauth's headless API (
/_allauth/), configured in settings andaccounts/adapter.py; never write a login view, and never calldjango.contrib.auth.loginfrom one. The admins' own forms send a signed-out person to the studio's sign-in (accounts/views.py), so nothing signs in around a second factor; an agent principal is refused at every route (AccountAdapter). Tests reach no IdP: they replaytests/accounts/fixtures/fake_idp.json.
Conventions¶
- Every module opens with a docstring saying what it is and why it exists; every app has the README its code points to.
- Ruff is the linter and formatter (
pyproject.toml); no blindexceptwithout a comment saying why, no# type: ignore. - Migrations are generated (
makemigrations), never hand-written, except the pgvector extension step ingraph/migrations/0001_initial.py. - A test passes alone, in any order and on any pytest-xdist worker (
content.ymlruns the suite with-n auto): it never counts on another test's rows, cache or files, and writes its files under its owntmp_path. Atransaction=Truetest flushes its worker's database, so pytest-django runs it after every test that needs the migrated rows — an order only xdist's in-orderloadscheduling keeps, which is why CI never usesworksteal.