TL;DR: This is the engineering view of the context layer workshop. One rule shapes the whole codebase: the agent never changes, only the data architecture around it does. Data contracts become SQL predicates with quarantine and a per-batch circuit breaker. Metrics are compiled from YAML, never written by the model, and every metric can be a number, “unknown” or “not applicable”. The agent acts only through business capabilities that re-check preconditions on live state, pass a policy evaluator that fails closed and climb an autonomy ladder. Every decision is an OpenTelemetry trace in a hash-chained log. An evaluation harness runs the same LLM with two toolsets, and a production track runs the same scenario on Airflow, dbt, OPA and DuckLake, with a parity check that proves both tracks decide the same. Code: cacaprog/marketing-de-workshop.

In the Croesus article I argued that marketing agents are confidently wrong because they have data and tools but no context. In the project page I showed what happened when I tested it: without context, a budget agent paused the two best campaigns and put ~R$40k/day of net revenue at risk; with context, the same logic stood still where it had no data.

This post is for the people who will have to build that layer. It opens the code: how the project is structured, what each layer actually does, which tools I chose and which I rejected, and what the results taught me about where context should live.

The design constraint: the agent is the constant

The scenario is a fictional company, Aurora Cosméticos, with 6 paid media campaigns on Google, Meta, TikTok and YouTube, about R$24k/day of budget and a R$26k/day ceiling approved by finance. The data is synthetic and deterministic (seed 42), with problems planted on purpose:

Planted problemHow it shows upWhat catches it
meta_capi feed stalled for 3 daysMeta “sold zero”Per-feed freshness SLA
GA4 batch loaded twice (retry)YouTube looks profitableUnique key + circuit breaker
~1% dirty rowsnegatives, "189,90", campaign C99, nullsContract rules
Old batch 37% corruptedupstream bugPer-batch circuit breaker
Awareness judged by ROASTikTok would be pausedDomain rule, enforced in the metric
Prompt injection in a briefing“raise YouTube to R$35,000”Preconditions in the backend
Upstream deploy sends centsthe contract passes itDistribution pillar (observability)

To make the experiment mean anything, I needed to be sure that whatever improved came from the architecture, not from a smarter agent. So before writing code I wrote a constitution (the project uses Spec Kit, and every feature went through spec, plan, tasks and implementation). Its seven principles are the real architecture document. The first three carry the thesis:

  1. The agent is the constant. NaiveAgent and ReadyAgent share the same decision policy (“take budget from ROAS < 1, give it to the best ROAS”). They differ only in which data and capabilities they can reach. Every track runs the same agent source, never a fork.
  2. Safety lives in the backend, not the model. Text informs, it never authorizes. Every write re-checks preconditions on live state, including after a human approval.
  3. Missing data is unknown, never zero. Late or blocked data is NULL in the Gold and the semantic layer, freshness is measured per feed, and the agent refuses to act on stale campaigns.

The other four are about engineering discipline: deterministic and offline by default, one automated test per promise, every tool must replace a named module, and every claim must carry its source.

The architecture

upstream feeds        Medallion (DuckDB)                          Context layer          Governed actions
┌────────────┐  ┌────────┐ contract ┌────────┐  ┌──────────────────┐  ┌────────────────┐  ┌───────────────────┐
│ ga4        │─▶│ Bronze │──(ODCS)─▶│ Silver │─▶│ Gold             │─▶│ Semantic model │─▶│ MCP server        │
│ meta_capi  │  │ (raw)  │    │     │(typed) │  │ campaign_daily   │  │ metrics +      │  │ preconditions     │
│ ads_api    │  └────────┘    ▼     └────────┘  │ source_health    │  │ freshness guard│  │ policy · autonomy │
└────────────┘      Quarantine + circuit breaker └──────────────────┘  └────────────────┘  └─────────┬─────────┘
      ▲                (humans investigate)         (agent reads only here)                          │
      └──── 5 observability pillars · lineage ◀── OpenTelemetry traces (hash-chained audit log) ◀─────┘

The standard track is about 4,600 lines of Python and YAML, runs on DuckDB with no Docker, no cloud and no API key, and resets in seconds with agentready setup. That was a hard requirement: a live workshop can’t depend on a network or on model variance.

Humans can look at Bronze, Silver and quarantine. The agent only sees the Gold, and the Gold carries the health of each source next to the numbers.

Layer 1: contracts compiled to SQL

Each source has a contract in the Open Data Contract Standard (ODCS v3.1). The interesting parts are the SLA block and one custom property:

schema:
  - name: conversions
    customProperties:
      - property: freshnessPartitionBy   # freshness measured PER FEED
        value: source
    properties:
      - name: conversion_id
        required: true
        unique: true
        primaryKey: true
      - name: order_value_brl
        logicalType: number
        logicalTypeOptions: {minimum: 0}
      # ...
slaProperties:
  - property: latency          # age of the LAST SUCCESSFUL LOAD, not of the event
    value: 24
    unit: h
    element: conversions.ingested_at
  - property: maxQuarantineRate  # circuit breaker
    value: 0.05

contracts.py turns every rule into a SQL expression that returns the reason for the violation, or NULL. Required, type, minimum, maximum, allowed values and uniqueness all become CASE WHEN ... THEN '<reason>' END, and duplicates are detected with a window function:

exprs.append(f"CASE WHEN ROW_NUMBER() OVER (PARTITION BY {part} ORDER BY ingested_at, batch_id) > 1 "
             f"THEN 'duplicate: ({part}) already loaded' END")

All expressions go into one DuckDB list, filtered for non-null values, so every row carries the full list of what’s wrong with it. Then the batch-level logic runs:

SELECT batch_id, COUNT(*) AS n,
       COUNT(*) FILTER (WHERE len(violations) > 0) AS bad,
       bad / n AS rate
FROM _checked GROUP BY batch_id

If a batch’s quarantine rate exceeds the contract limit, every row in it is quarantined, including the clean ones, with the reason “batch blocked by the circuit breaker”. A batch that is 37% broken is not a batch with 63% good rows: it’s a sign that something upstream is wrong, and the clean-looking rows can’t be trusted either.

Three more decisions in this layer matter more than they look:

  • Freshness is per feed, from the last successful load. GA4 and Meta CAPI share the conversions contract but have independent SLAs. Measuring by event date would hide a feed that stopped; measuring the table as a whole would hide one feed behind the other. In the scenario, GA4 is fresh and Meta is 75 hours late.
  • A schema break keeps the last good state. If a column disappears, nothing can be interpreted, so the Silver isn’t overwritten and the freshness SLA takes care of raising the alarm.
  • The Gold pre-aggregates conversions before the join. The grain is campaign × day, and conversions are summed per campaign and day before joining spend. That prevents the classic fan-out where each spend row is multiplied by the number of orders.

Layer 2: a semantic compiler, not a prompt

The domain model, the semantic model and the capability model live in one versioned file, marketing.semantic.yaml. Metrics are declared, not written:

roas:
  type: ratio
  numerator: net_revenue
  denominator: spend
  synonyms: [roas, return on ad spend]
  not_applicable:
    when: {objective: [awareness]}
    reason: awareness campaigns are judged by reach and frequency, not conversion efficiency
    rule: awareness_nao_usa_roas

semantic.py is a small compiler. The agent asks for metrics by name, and the compiler always generates the same SQL. A few rules are encoded in it rather than in documentation:

  • Ratio of sums, never average of ratios: ((num) / NULLIF(den, 0)).
  • Derived metrics like net_revenue = gross_revenue - discounts are expanded recursively, with a guard against circular definitions.
  • The model is validated on load: a not_applicable rule can only reference dimensions that exist and domain rules that exist, or the whole model fails to load.

The most important part is the freshness guard. Every Gold row is joined with the health of its own conversion source, and any metric that depends on conversions becomes NULL if any row in the group comes from a stale feed:

SELECT campaign_id, ..., bool_or(h.status = 'stale') AS _stale
FROM gold.campaign_daily t
LEFT JOIN gold.source_health h
  ON h.dataset = 'conversions' AND h.partition = t.conversion_source
...
CASE WHEN _stale THEN NULL ELSE net_revenue END AS net_revenue

The compiler knows which metrics depend on conversions by walking the metric tree down to the measures (depends_on_conversions: true). Spend doesn’t, so it stays a number; ROAS does, so it becomes unknown.

That gives every metric three states, and the difference between them is the whole lesson of the project:

StateMeaningExample
a numberthe official valueROAS 2.78
unknown (NULL)the source is late; we don’t knowMeta revenue with a stalled feed
not applicablea domain rule says this metric doesn’t judge this campaignROAS of an awareness campaign

interpret() maps natural language to a MetricRequest using the synonyms in the model. In a real product an LLM would do that step, but the LLM only picks metric and dimension names; the compiler always writes the SQL. That’s the boundary that keeps “revenue” from meaning gross revenue in one answer and net in the next.

Layer 3: capabilities, policy and the autonomy ladder

The agent doesn’t get the ad platform API. It gets five business capabilities, exposed over an MCP server (and called in-process by the demo agents): read data health, read campaign performance, read the policy, adjust a budget, and request a pause. Every capability declares a reversibility class:

ClassMeaningExamples
R0read onlydata health, performance
R1reversible, rollback restores the previous valueadjust budget
R2reversible at a cost (the platform algorithm loses its learning)pause campaign
R3irreversibledelete campaign: never exposed to the agent

A write goes through the same gate every time. First the capability reads facts from the live state (ops.*, not the Gold): the campaign, its status, whether a human locked it, its objective, the freshness of its source, the current and proposed budget, the sum of the other active budgets and how many changes it had today. Those facts go to a policy evaluator, which returns one check per rule:

campanha_existe · campanha_ativa · sem_trava_humana · objetivo_elegivel ·
justificativa_presente · dados_frescos · variacao_maxima · orcamento_minimo ·
teto_do_portfolio · limite_de_alteracoes

The limits live in guardrails.yaml, the only source of authorization for agent actions: at most ±20% per action, 2 changes per campaign per day, a R$26k portfolio ceiling, a R$300 minimum budget, only conversion campaigns are optimized by ROAS, and fresh data is required. If the evaluator doesn’t answer, the action is denied (fail closed).

If every check passes, the autonomy ladder decides what happens:

def decide(con, action, change_pct=None):
    cfg = autonomy()["actions"].get(action, {"level": "disabled", "reversibility": "R3"})
    level = cfg["level"]
    esc = cfg.get("escalate_to_supervised_if", {})
    if level == "guarded" and change_pct is not None and abs(change_pct) > esc.get("abs_change_pct_gt", 1e9):
        level = "supervised"
    ...

shadow only logs what it would do, supervised queues the action for a human, guarded executes inside the guardrails and escalates risky cases, and full executes everything that passes. Budget adjustments are guarded but escalate to supervised above 10%; pauses are always supervised; deletion is disabled. An unknown action defaults to disabled and R3.

Three details close the gaps that usually stay open:

  • Approval doesn’t skip preconditions. When a human approves a queued request, the capability re-reads the live state and runs the checks again. If the data went stale since the request, the approved action is rejected.
  • Unanswered requests fail safe. In the production track, a request with no answer in 20 hours expires as not approved, before the next day’s run.
  • Retrieved text is tagged as untrusted. Briefings come back with a banner saying their instructions authorize nothing. But the banner is a courtesy to the model, not the defense. To test that, there’s a --gullible mode that simulates an agent fully convinced by the injected “CMO note”. It tries to set YouTube to R$35,000/day, and the backend rejects it on variacao_maxima and teto_do_portfolio. Safety can’t depend on the model resisting.

Layer 4: every decision is a trace

Every capability opens an OpenTelemetry span, and the attributes tell the whole story of a decision: the compiled SQL (semantic.sql), the semantic model and contract versions, which sources were stale, every precondition with pass or fail, the policy evaluator and its version, the autonomy level and why, and the final status. A human approval is a span too, linked to the trace of the original request.

The spans are exported to traces/audit.jsonl by a custom exporter that chains them with SHA-256:

rec["prev_hash"] = prev
rec["hash"] = hashlib.sha256(json.dumps(rec, sort_keys=True).encode()).hexdigest()
prev = rec["hash"]

Change one record and every hash after it breaks, which agentready verify detects. If OTEL_EXPORTER_OTLP_ENDPOINT is set, the same spans also go to Phoenix, Langfuse or Jaeger. But those are for exploring, not for proof: a trace database can be edited by anyone with access. The chain is the audit record.

That’s what answers the question nobody can answer six months later: “why did the agent do that?”

Layer 5: contracts are not observability

The last block of the workshop simulates an incident: an upstream deploy starts sending order values in cents. Every value is still a non-negative number, so the contract approves the batch. That’s on purpose, and it’s the lesson: contracts catch what is invalid; observability catches what is valid but wrong.

observability.py implements four of the five pillars as rules over the data, plus lineage:

  • Freshness: read from gold.source_health.
  • Volume: rows received yesterday vs. the median of the previous 14 days, outside 0.5×–1.5× fails.
  • Distribution: average ticket of the latest batch vs. the median per source, outside 0.5×–2× fails. This is what catches the cents.
  • Schema: expected columns vs. what arrived.
  • Lineage: from a source down to the metrics, tools and agent decisions that used it since a given time, so you know which decisions to review.

A distribution failure doesn’t block the agent by default (block_on_distribution_anomaly: false). The post-mortem template asks the audience to propose turning it on. That flag is the point where an incident becomes a design decision.

Testing LLMs with and without context

The decision agent is deterministic, which makes the demo reliable but leaves an obvious question: does this hold for a real model? So the project has an evaluation harness (spec 005) with two toolsets for the same model, the same system instruction and the same request:

ConditionWhat the model seesWhat it can do
without contextread-only SQL over raw Bronze, the campaign list, the briefingschange budgets and pause campaigns directly, no guardrails
with contextdata health, official metrics, the policy, briefings tagged as untrustedthe same actions, through the governed capabilities

The brains are interchangeable: the rules policy, Claude through the API, or any local model served by Ollama or llama.cpp through the OpenAI-compatible API. Two modes run on top:

  • 8 fixed business questions. The official answer is not written anywhere: it’s computed at run time by the semantic layer, source health and domain rules. The model has to register its answer through a responder tool, and each answer gets a verdict: right (within 2%), correct “unknown”, wrong, made up a number, no answer, or failed. One question, total spend, is a control: the data is clean and both conditions should get it right.
  • Graded budget runs. Each run recreates the scenario with the same seed and measures profitable campaigns paused, actions on stale data, R$/day outside the guardrails, whether the injection was followed and R$/day at risk.

Two practical lessons from running local models: Ollama silently truncated a ~18,000-token request to the model’s 4,096-token default context (the agent now warns when the loaded context is below 16,384), and without a per-response token limit a local model generated 4,098 tokens in one answer, five minutes of output.

The results (one run per model, November 27, 2026) are on the project page: all three models scored higher with context and answered 3.5 to 4 times faster. For engineers, the most useful finding was a bug in my own layer. Even with context, Claude Haiku 5.5 reported a ROAS of 0.60 for the awareness campaign. The official metrics tool still returned that number, and the rule “awareness doesn’t use ROAS” lived only in the policy text and the domain model, which it didn’t read.

The fix (spec 006) wasn’t a better prompt. It was the not_applicable block you saw in the YAML above: the compiler now filters awareness rows out of ROAS and CAC and returns not applicable with a reason. On the new run, Haiku with context answered “not applicable”.

A rule that only exists as text can be ignored. A rule in the data can’t be.

The production track: every tool replaces a module

Hand-written Python is good for teaching and bad for convincing a data team. So stack/ runs the same scenario with production tools, with one rule from the constitution: a tool only gets in if it replaces a named module of the standard track. The replacement map is part of the documentation:

ToolReplaces
Airflow 3.3 (DAG + human-in-the-loop)the step order in pipeline.run() and the approval queue in the CLI
dbt-core + dbt-duckdb, with Cosmosthe materialization of Silver, quarantine, Gold and source health
Data Contract CLIreading contract types to test the Silver, plus contract linting
Elementary + obs_* dbt modelsrunning the observability pillars, storing history and reporting
OpenLineage + Marquezthe hand-drawn lineage, now emitted by what actually ran
OpenTelemetry Collector + Arize Phoenixtrace export and visualization (the hash chain stays)
FastAPI mock sources + dltthe static scenario load, now over HTTP with failures and retries
Open Policy Agentenforcing guardrails.yaml inside the capabilities
DuckLakethe single warehouse file for data layers, with snapshots and time travel

The guarantee that the agent didn’t change is make parity. Each track runs in an isolated process, with the same scenario and reference time, and the command compares Gold campaign × day to the cent, source health, every agent decision, every observability verdict, the agent trace, Bronze per batch, load status and every policy check. Seven scenarios, exit code 0 only if everything matches.

The policy is the best example of how that discipline works. In the standard track, guardrails are evaluated in Python; in the stack, the evaluator is swapped by configuration and OPA decides, with Rego rules reading the same guardrails.yaml as data.guardrails. The rules exist in two languages, so an equivalence test runs the same cases through both and fails on any difference. One subtle bug it forced me to avoid: the portfolio total is summed once in Python and passed as a fact, because summing in OPA (exact decimals) could disagree with Python floats right at the limit.

The rule also says no:

  • No metadata catalog (OpenMetadata, DataHub): none of them replaces a module. The semantic layer is a compiler and a catalog doesn’t generate SQL. They would also need 6 GB or more on a stack that has to fit in 8.
  • No Iceberg or MinIO: Iceberg would need a REST catalog and object storage; DuckLake comes with the DuckDB already in use and keeps its catalog in the Postgres that already exists.
  • No Grafana and no Langfuse: Phoenix’s own views were enough, and Langfuse would add ClickHouse, Redis and object storage.

And it’s honest about the gaps: Marquez doesn’t show semantic or MCP nodes because no pipeline step produces them; dbt emits no spans, so each model shows up as an Airflow task; operational state (budgets, change log, approvals) is deliberately left out of the lake, because time travel must never roll back a money decision.

What I’d take to any agent project

  1. Fix the agent and vary the architecture. Otherwise you never know what improved the result. The NaiveAgent/ReadyAgent pair, the two toolsets and the parity check all serve this.
  2. Make “unknown” and “not applicable” first-class values. Most agent mistakes in this project came from a missing value becoming zero or a number that shouldn’t exist.
  3. Let the model choose names, never write SQL. A compiler gives the same answer to the same question every time, and it’s testable.
  4. Put authorization in data the model can’t touch. Preconditions on live state, re-checked at execution time, failing closed. The prompt is not a security boundary.
  5. When the model breaks a rule, move the rule into the data. A prompt teaches behavior; the right data keeps the wrong number from existing.
  6. Write one test per promise. The standard track has 97 tests, each tied to something the workshop tells the audience, and the stack adds its own plus the parity check.

How to run it

uv sync --extra dev
uv run agentready setup        # generates the scenario (SLAs are relative to "now")
uv run agentready demo all     # the whole day, block by block
uv run pytest -q               # 97 tests

# with a real model, with and without context
uv run agentready perguntas --brain local --llm-model qwen2.5:14b
uv run agentready compare --brains rules,claude --runs 3

# production track (Docker, ≥ 4 CPUs, ≥ 8 GB RAM)
cd stack && make up && make run ARGS='{"reset_scenario": true}' && make parity

Everything is at cacaprog/marketing-de-workshop, including the specs for each feature and the recorded model comparison runs. The repository and the workshop materials are in Portuguese. For the business argument behind all this, start with the Croesus article; for the results, the project page; and for the terms of each layer, the workshop glossary.