diff --git a/.changeset/governance-coherence-decisions.md b/.changeset/governance-coherence-decisions.md new file mode 100644 index 0000000000..b86bb338a6 --- /dev/null +++ b/.changeset/governance-coherence-decisions.md @@ -0,0 +1,17 @@ +--- +"adcontextprotocol": minor +--- + +Campaign governance (experimental `governance.campaign`): settle the rules the specification contradicted or left undefined (adcp#8733, PR 2 of 3). These are normative decisions of the Governance working group. No wire field, enum member or `plan_hash` rule changes. This is a change within the 3.3 pre-release. + +- **Budget cut below committed spend.** A `sync_plans` that reduces `budget.total` (or a period `amount`) below the amount already committed is rejected with `VALIDATION_ERROR` and leaves the plan unchanged. Before, the specification said the sync was accepted and flagged on the next check, while the task page said it was rejected. +- **Unapproved seller or undelegated caller on `check_governance`.** A failed `approved_sellers` or `delegations` evaluation for an authenticated caller is returned as a `denied` verdict with a finding and a `check_id`, so the attempt can be audited. This holds in every governance mode. A plan is accessible to its owner principal, to a current delegate, and to a caller that presents a `governance_context` or `consultation_context` issued for that plan. Any other caller receives `PLAN_NOT_FOUND`, the same response as for an unknown `plan_id`, and writes no audit entry. Before, the task page listed `PERMISSION_DENIED` for these cases. `check_governance` still returns `PERMISSION_DENIED` when the caller is unauthenticated or its authenticated identity does not match `caller`. Callers that branch on the error code for the authority cases must also handle the verdict. +- **Human review in every mode.** Audit and advisory mode no longer describe an agent that always returns `approved`: plans with `human_review_required: true` escalate in every mode, and a failed `approved_sellers` or `delegations` evaluation is `denied` in every mode. +- **`plan_id` namespace.** A `plan_id` is unique per owner principal. Two principals may use the same `plan_id`, and a `sync_plans` never reads, changes or reveals another principal's plan. +- **`execute_only`.** A pre-approved action is one whose opaque action binding already holds an approved intent check in the plan's lifecycle. An `execute_only` delegate may act only on such an action, which includes `accept_proposal` for it. The governance agent MUST deny an intent check from an `execute_only` delegate that would create a new binding or increase committed spend. +- **Regions-restricted plans.** An action with no geographic targeting, or with country-level targeting only, is outside a regions-restricted plan: an intent check returns `conditions` naming the region constraint, and an execution check returns `denied`. +- **Unresolvable registry policy ID.** `sync_plans` returns `REFERENCE_NOT_FOUND` when a registry policy ID in `policy_ids` cannot be resolved. +- **Three re-call rule.** "The same action" means re-checks that carry the same `consultation_context`. +- **Explicit `human_review_required: false`.** The `sync_plans` error table states that it is rejected with `VALIDATION_ERROR` on a plan that requires human review. + +Training agent: `sync_plans` now rejects a `budget.total` reduced below committed spend, and `check_governance` returns the `denied` verdict for an authenticated execution caller that is not the audience preserved from the approved intent, and for a buyer-side caller whose delegation has ended. It no longer approves a failed `approved_sellers` or `delegations` evaluation in advisory or audit mode. For a plan that does not exist or that the caller cannot access, `check_governance` now returns the `PLAN_NOT_FOUND` error; it returned a `denied` verdict with a `plan_lookup` finding. diff --git a/docs/governance/campaign/audit-trail.mdx b/docs/governance/campaign/audit-trail.mdx index c1bb46987a..fd7a92546c 100644 --- a/docs/governance/campaign/audit-trail.mdx +++ b/docs/governance/campaign/audit-trail.mdx @@ -176,15 +176,14 @@ Findings are how the audit trail communicates risk. Two patterns worth knowing: ### Security-shaped finding: an unauthorized seller -The plan declares `approved_sellers: ["https://ads.seller-approved.example"]`. A different seller calls `check_governance` and gets denied: +The plan declares `approved_sellers: ["https://ads.seller-approved.example"]`. A different seller calls `check_governance` with an execution check and gets denied: ```json { "$schema": "/schemas/governance/check-governance-response.json", "status": "completed", "check_id": "chk_0ac8d7de", - "check_type": "intent", - "plan_id": "plan_2027_apex_athletic", + "check_type": "execution", "verdict": "denied", "explanation": "Denied: Caller https://ads.seller-rogue.example is not in the plan's approved sellers list.", "categories_evaluated": ["delegation_authority", "seller_compliance"], @@ -230,7 +229,7 @@ The denial is also a coaching moment — the operator sees exactly what to fix. ## The operator's dial: enforce / advisory / audit -`mode` is governance agent configuration. The buyer's policy team sets it on the governance agent itself; it is not a plan field and is not sent in [`sync_plans`](/docs/governance/campaign/tasks/sync_plans). It is the operator's primary lever, and an agent that reports `mode` records the mode in force on each check entry. The same caller, same payload, same finding produces three different outcomes depending on mode. +`mode` is governance agent configuration. The buyer's policy team sets it on the governance agent itself; it is not a plan field and is not sent in [`sync_plans`](/docs/governance/campaign/tasks/sync_plans). It is the operator's primary lever, and an agent that reports `mode` records the mode in force on each check entry. The same caller, same payload and same finding produce three different outcomes depending on mode. The example is a buy that asks for more than the plan's total budget. **`mode: "enforce"`** — the buy is blocked at the governance layer: @@ -242,14 +241,14 @@ The denial is also a coaching moment — the operator sees exactly what to fix. "check_type": "intent", "plan_id": "plan_mode_enforce", "verdict": "denied", - "explanation": "Denied: Caller https://ads.seller-rogue.example is not in the plan's approved sellers list.", - "categories_evaluated": ["delegation_authority", "seller_compliance"], + "explanation": "Denied: Requested budget $150000 exceeds plan total $100000.", + "categories_evaluated": ["delegation_authority", "budget_authority"], "policies_evaluated": [], "findings": [ { - "category_id": "seller_compliance", + "category_id": "budget_authority", "severity": "critical", - "explanation": "Caller https://ads.seller-rogue.example is not in the plan's approved sellers list." + "explanation": "Requested budget $150000 exceeds plan total $100000." } ] } @@ -268,13 +267,13 @@ The denial is also a coaching moment — the operator sees exactly what to fix. "explanation": "Approved with 1 advisory finding(s).", "expires_at": "2027-01-15T15:32:41Z", "governance_context": "eyJhbGciOiJFZERTQSJ9.advisory.signature", - "categories_evaluated": ["delegation_authority", "seller_compliance"], + "categories_evaluated": ["delegation_authority", "budget_authority"], "policies_evaluated": [], "findings": [ { - "category_id": "seller_compliance", + "category_id": "budget_authority", "severity": "critical", - "explanation": "Caller https://ads.seller-rogue.example is not in the plan's approved sellers list." + "explanation": "Requested budget $150000 exceeds plan total $100000." } ] } @@ -293,18 +292,20 @@ The denial is also a coaching moment — the operator sees exactly what to fix. "explanation": "All governance checks passed.", "expires_at": "2027-01-15T15:32:41Z", "governance_context": "eyJhbGciOiJFZERTQSJ9.audit.signature", - "categories_evaluated": ["delegation_authority", "seller_compliance"], + "categories_evaluated": ["delegation_authority", "budget_authority"], "policies_evaluated": [], "findings": [ { - "category_id": "seller_compliance", + "category_id": "budget_authority", "severity": "critical", - "explanation": "Caller https://ads.seller-rogue.example is not in the plan's approved sellers list." + "explanation": "Requested budget $150000 exceeds plan total $100000." } ] } ``` +Two outcomes do not move with the dial. A failed `approved_sellers` or `delegations` evaluation is `denied` in every mode, as in the [unauthorized seller](#security-shaped-finding-an-unauthorized-seller) example above, and plans with `human_review_required: true` escalate in every mode. + The trade-off: | Mode | Velocity | Safety | When to use | diff --git a/docs/governance/campaign/index.mdx b/docs/governance/campaign/index.mdx index f7c9581c2c..0ba472ad0f 100644 --- a/docs/governance/campaign/index.mdx +++ b/docs/governance/campaign/index.mdx @@ -28,7 +28,7 @@ Without a governance layer on the buy side: Campaign Governance fills this gap with three mechanisms: **plans** that define what's allowed (independent of the agent), **seller-side governance checks** that verify purchases independently of the buyer, and a **policy registry** that standardizes compliance rules across governance agents. -Governance supports incremental adoption — organizations configure their governance agent to start in audit mode (log everything, approve everything), move to advisory (flag violations without blocking), and eventually enforce (block on violations). See the [safety model](/docs/governance/campaign/safety-model) for the adoption path. Mode is internal to the governance agent, not a protocol field. +Governance supports incremental adoption — organizations configure their governance agent to start in audit mode (log findings without blocking on them), move to advisory (flag violations without blocking), and eventually enforce (block on violations). See the [safety model](/docs/governance/campaign/safety-model) for the adoption path and for the two outcomes that hold in every mode. Mode is internal to the governance agent, not a protocol field. ### Industry precedent @@ -143,8 +143,8 @@ Governance agents support incremental adoption through their internal mode confi In practice, organizations configure their governance agent to progress through three stages: -1. **Audit** — Log everything, approve everything. The governance agent evaluates fully but always returns `approved` with findings attached. The organization reviews findings to assess false positive rates and calibrate policies. -2. **Advisory** — Approve with prominent findings and recommended corrections. The decision is still unambiguously `approved`; humans review findings post-hoc. +1. **Audit** — Log findings without blocking on them. The governance agent evaluates fully but returns `approved` with findings attached, except in two cases that hold in every mode: plans with `human_review_required: true` escalate, and a failed `approved_sellers` or `delegations` evaluation is `denied`. The organization reviews findings to assess false positive rates and calibrate policies. +2. **Advisory** — Approve with prominent findings and recommended corrections. The decision is still `approved`; humans review findings post-hoc. The same two exceptions apply. 3. **Enforce** — Block on violations. The default for production governance. This works the same way for a single brand buying direct and for a holding company with 35 brands and multiple agency partners. diff --git a/docs/governance/campaign/safety-model.mdx b/docs/governance/campaign/safety-model.mdx index 09dc07d990..aec5511f4d 100644 --- a/docs/governance/campaign/safety-model.mdx +++ b/docs/governance/campaign/safety-model.mdx @@ -59,8 +59,8 @@ Governance agents support three internal operating modes so organizations can bu | Mode | What happens | Risk | |------|-------------|------| -| **Audit** | Log everything, never block. Always returns `approved` with findings attached. | Zero. See what governance would flag without affecting live campaigns. | -| **Advisory** | Return `approved` with prominent findings and recommended corrections. | Minimal. Humans review findings post-hoc and act on them. | +| **Audit** | Log everything. Returns `approved` with findings attached, except in two cases that hold in every mode: plans with `human_review_required: true` escalate, and a failed `approved_sellers` or `delegations` evaluation is `denied`. | Lowest. See what governance would flag. Only the two cases named here affect live campaigns. | +| **Advisory** | Return `approved` with prominent findings and recommended corrections, with the same two exceptions. | Minimal. Humans review findings post-hoc and act on them. | | **Enforce** | Block on violations. Require resolution before proceeding. | Production governance with full protection. | Start in audit mode to evaluate false positive rates and calibrate policies. Move to advisory to test findings with real campaigns. Switch to enforce when confidence is established. The governance agent's audit logs record which mode was active for each check, so post-hoc analysis can distinguish audit-mode approvals from enforce-mode approvals. diff --git a/docs/governance/campaign/specification.mdx b/docs/governance/campaign/specification.mdx index 358dd343d1..c1e327e984 100644 --- a/docs/governance/campaign/specification.mdx +++ b/docs/governance/campaign/specification.mdx @@ -212,7 +212,7 @@ Applicability is resolved from the commercial account, not from token presence. For any task declared with `signed_context`, the service commits only after verifying the approved context. Media-buy tasks may additionally declare `online_execution_check`; those services follow **prepare → check → commit** by computing `planned_delivery` without externally committing it, calling `check_governance`, and committing atomically only after `approved`. Execution checks return `approved` or `denied`. Other roles do not claim online execution checking until AdCP defines a prepared-result contract for that role; they MUST NOT invent `planned_delivery` or `media_buy_id` values. -Identity is role-specific. On the buyer's intent check, `caller` is the authenticated buyer-side principal and is evaluated against `delegations`; `approved_sellers` is evaluated against the target service that becomes the token `aud`, never against that buyer. Every later execution check resolves that original intent by its opaque action binding before evaluating delegation—the immediately prior check's caller may be the seller. On an execution check, the authenticated `caller` MUST equal the audience preserved from the approved intent, and that seller identity is evaluated against `approved_sellers`. The execution commitment may narrow the approved intent but MUST use the same currency and MUST NOT exceed the intent's `authorized_commitment`. For `update_media_buy`, the seller computes `max(0, new committed total − authoritative current total)` atomically with its revision check and write, enforces the signed intent ceiling, and reports that value as `execution_commitment`; the governance agent never infers a delta by reading seller state or subtracting from the seller's post-update total. A buyer/seller delta mismatch fails closed and requires a fresh intent. +Identity is role-specific. On the buyer's intent check, `caller` is the authenticated buyer-side principal and is evaluated against `delegations`; `approved_sellers` is evaluated against the target service that becomes the token `aud`, never against that buyer. Every later execution check resolves that original intent by its opaque action binding before evaluating delegation—the immediately prior check's caller may be the seller. On an execution check, the authenticated `caller` MUST equal the audience preserved from the approved intent, and that seller identity is evaluated against `approved_sellers`. A failed `delegations` or `approved_sellers` evaluation for an authenticated caller, including an execution check whose authenticated caller is not that preserved audience, is returned as a `denied` verdict with a finding and a `check_id`, never as an error, in every governance mode. A failed `delegations` or `approved_sellers` evaluation is never `PERMISSION_DENIED`; that error is for authentication and credential failures, such as an unauthenticated caller or an authenticated identity that does not match `caller`. A plan is accessible to a caller that is its owner principal, that is named in a `delegations` entry that has not expired, or that presents a `governance_context` or `consultation_context` the governance agent issued for that plan. For any other caller `check_governance` returns `PLAN_NOT_FOUND`, exactly as for a `plan_id` that does not exist, and the attempt writes no audit entry: the `denied` verdict for a failed `delegations` evaluation is for a caller that can access the plan. The governance agent verifies a presented `governance_context`, and its match with `plan_id`, before it resolves plan access. A context that fails verification or was issued for another plan is `PERMISSION_DENIED`, whether or not `plan_id` exists. Because a `plan_id` is unique per owner principal, a caller can access more than one plan with the same ID; the governance agent MUST then reject the check with `VALIDATION_ERROR` and MUST NOT evaluate it against either plan. The execution commitment may narrow the approved intent but MUST use the same currency and MUST NOT exceed the intent's `authorized_commitment`. For `update_media_buy`, the seller computes `max(0, new committed total − authoritative current total)` atomically with its revision check and write, enforces the signed intent ceiling, and reports that value as `execution_commitment`; the governance agent never infers a delta by reading seller state or subtracting from the seller's post-update total. A buyer/seller delta mismatch fails closed and requires a fresh intent. Sellers MUST persist the accepted intent token and any lifecycle tokens they subsequently hold, keyed at minimum by `jti` with `iss`, `aud`, the opaque action binding in `sub`, `phase`, decision outcome, and the timestamp of acceptance. They MUST NOT treat `sub` as a plan identifier. Retention follows the seller's regulatory retention period. Without seller-side retention, the audit log is single-sourced from the governance agent; independent reconciliation between seller records and `get_plan_audit_logs` is the cross-check that catches a compromised or misbehaving governance agent. @@ -337,7 +337,7 @@ Authority levels: | `execute_only` | Can execute pre-approved actions but cannot initiate new campaigns or reallocate budget | | `propose_only` | Can propose actions for governance review but cannot execute without explicit approval | -The governance agent resolves the authenticated transport credential to an agent URL and requires the request's `caller` assertion to match it. For a non-owner caller, it then compares that resolved URL with the delegation's `agent_url`. It MUST NOT authorize from the body assertion alone. Matching is exact and case-sensitive after normalization per RFC 3986. Every call fails closed when the credential has no agent-URL mapping. An agent requesting a media buy in France must have a delegation that includes France in its `markets`. An agent with `execute_only` authority cannot reallocate budget between channels. +The governance agent resolves the authenticated transport credential to an agent URL and requires the request's `caller` assertion to match it. For a non-owner caller, it then compares that resolved URL with the delegation's `agent_url`. It MUST NOT authorize from the body assertion alone. Matching is exact and case-sensitive after normalization per RFC 3986. Every call fails closed when the credential has no agent-URL mapping. An agent requesting a media buy in France must have a delegation that includes France in its `markets`. An agent with `execute_only` authority cannot reallocate budget between channels. A pre-approved action is one whose opaque action binding already holds an approved intent check in this plan's lifecycle: an `execute_only` delegate MAY act only on such an action, which includes `accept_proposal` for it. The governance agent MUST deny an intent check from an `execute_only` delegate that would create a new binding or increase committed spend. The authenticated buyer principal that synchronized the plan is its owner and always retains full authority. Delegations add explicitly scoped non-owner @@ -484,7 +484,7 @@ Policies are declared directly on the plan via `policy_ids` and `custom_policies **`custom_policies` are additive only.** Governance agents MUST pin registry-sourced policy text as system-level instructions and MUST NOT permit `custom_policies` (or the plan's `objectives` field) to relax, override, or disable registry-sourced policies. Custom policies may add tighter restrictions — they cannot lower enforcement levels or exempt categories. A `custom_policies` entry that contradicts a registry policy is evaluated alongside it, not instead of it; the stricter constraint governs. -The plan's `countries` and `regions` fields also serve as **geo enforcement**: the governance agent MUST reject governed actions targeting markets outside the plan's allowed geography. A plan with `regions: ["US-MA"]` rejects actions not explicitly targeting Massachusetts, even if they are otherwise compliant. These fields use the same ISO codes and semantics as `product-filters`, `offerings`, and `create_media_buy`. +The plan's `countries` and `regions` fields also serve as **geo enforcement**: the governance agent MUST reject governed actions targeting markets outside the plan's allowed geography. A plan with `regions: ["US-MA"]` rejects actions not explicitly targeting Massachusetts, even if they are otherwise compliant. An action with no geographic targeting, or with country-level targeting only, is treated as targeting the whole country and is outside a regions-restricted plan: an intent check returns `conditions` naming the region constraint, and an execution check returns `denied`. These fields use the same ISO codes and semantics as `product-filters`, `offerings`, and `create_media_buy`. The resolved policy set is what the governance agent evaluates during [`check_governance`](/docs/governance/campaign/tasks/check_governance). For the `brand_policy` and `regulatory_compliance` categories, the governance agent validates against this resolved set. @@ -619,7 +619,7 @@ Organizations set only the thresholds relevant to their concern. An `escalation_ ### Plan amendments -Calling `sync_plans` with an existing `plan_id` updates the plan (upsert). The governance agent increments `plan_version` and applies the new parameters immediately. Active media buys that were approved under the previous plan version are not automatically re-validated -- the governance agent evaluates them against the updated plan on the next `check_governance` call (e.g., the next delivery check). If an amendment reduces the budget below the currently committed amount, the governance agent flags this as a finding on the next governance check. +Calling `sync_plans` with an existing `plan_id` updates the plan (upsert). The governance agent increments `plan_version` and applies the new parameters immediately. Active media buys that were approved under the previous plan version are not automatically re-validated -- the governance agent evaluates them against the updated plan on the next `check_governance` call (e.g., the next delivery check). A sync that reduces `budget.total` (or a period `amount`) below the amount already committed is rejected with `VALIDATION_ERROR` and leaves the plan unchanged. ## Validation logic @@ -878,10 +878,12 @@ The seller stores these endpoints and presents the credentials when calling `che Governance mode (audit, advisory, enforce) is an internal implementation detail of the governance agent, not a protocol-level field. The caller sends `check_governance` and acts on the verdict without needing to know what mode produced it. Intent checks may return `approved`, `denied`, or `conditions`; execution checks return `approved` or `denied`. This means: -- A governance agent in audit mode internally always returns `approved` with findings attached -- A governance agent in advisory mode returns `approved` with prominent findings and recommended corrections +- A governance agent in audit mode internally returns `approved` with findings attached, with the two exceptions below +- A governance agent in advisory mode returns `approved` with prominent findings and recommended corrections, with the same two exceptions - A governance agent in enforce mode returns `denied` and expects the caller to stop +Two outcomes do not depend on mode. Plans with `human_review_required: true` escalate in every mode. A failed `approved_sellers` or `delegations` evaluation is `denied` in every mode, including: an intent check whose target is not in `approved_sellers`, an execution check by a caller that is not the audience preserved from the approved intent or that has since been removed from `approved_sellers`, an execution check whose original intent was made by a buyer that no longer holds a current delegation, an intent check by a buyer-side caller that can access the plan but is neither its owner nor a current delegate, and an intent check by a delegate that acts outside the `authority`, `budget_limit` or `markets` of its delegation. + Mode is configured by the buyer's policy team on the governance agent itself, not via the protocol. The governance agent MAY include mode information in its audit logs or `get_plan_audit_logs` response for post-hoc analysis, but callers MUST NOT branch behavior based on mode — they act on the status they receive. See the [safety model](/docs/governance/campaign/safety-model) for the crawl-walk-run adoption path. diff --git a/docs/governance/campaign/tasks/check_governance.mdx b/docs/governance/campaign/tasks/check_governance.mdx index 734ee60aed..c79f9cbb4e 100644 --- a/docs/governance/campaign/tasks/check_governance.mdx +++ b/docs/governance/campaign/tasks/check_governance.mdx @@ -284,7 +284,7 @@ See the [specification](/docs/governance/campaign/specification#spend-commit-inv `conditions` is valid only for intent checks and carries no `governance_context`. It returns a separate `consultation_context`, which is only a negotiation handle: the buyer returns it with the adjusted `plan_id` + `tool` + `payload` re-check and MUST NOT send it to a service. The governance agent binds that handle to the authenticated principal, caller, plan, tool, purchase type, and target audience; any mismatch is rejected. The caller must receive `approved` before proceeding. Conditions with a `required_value` are machine-actionable; conditions without one describe the adjustment the buyer must make. Execution and lifecycle checks return either `approved` or `denied`. -Governance agents SHOULD return `denied` after 3 unsuccessful intent re-calls for the same action. This prevents infinite negotiation loops. +Governance agents SHOULD return `denied` after 3 unsuccessful intent re-calls for the same action. "The same action" means re-checks that carry the same `consultation_context`. A `conditions` verdict on a re-check returns the same `consultation_context`. This prevents infinite negotiation loops. ### Human review @@ -738,10 +738,10 @@ The seller MUST pause delivery immediately and correct the geo targeting before | Code | Recovery | Description | |------|----------|-------------| -| [`PLAN_NOT_FOUND`](/docs/building/verification/compliance-catalog#error-code-plan-not-found) | correctable | No plan with this ID. The buyer may not have synced the plan yet. | -| [`VALIDATION_ERROR`](/docs/building/verification/compliance-catalog#error-code-validation-error) | correctable | The request mixes intent and execution fields, omits a shape-dependent field such as `target_agent` or `execution_commitment`, changes a consultation binding, or carries an invalid amount/currency. Correct the named field and retry; send exactly one check shape. | +| [`PLAN_NOT_FOUND`](/docs/building/verification/compliance-catalog#error-code-plan-not-found) | correctable | No plan with this ID, or the plan is not accessible to the caller: the caller is not its owner or a current delegate and presents no `governance_context` or `consultation_context` issued for it. The two cases are indistinguishable in the response, and neither writes an audit entry. The buyer may not have synced the plan yet. | +| [`VALIDATION_ERROR`](/docs/building/verification/compliance-catalog#error-code-validation-error) | correctable | The request mixes intent and execution fields, omits a shape-dependent field such as `target_agent` or `execution_commitment`, changes a consultation binding, carries an invalid amount/currency, or names a `plan_id` that matches more than one plan the caller can access. Correct the named field and retry; send exactly one check shape. | | [`CAMPAIGN_SUSPENDED`](/docs/building/verification/compliance-catalog#error-code-campaign-suspended) | transient | Campaign governance is suspended pending human review. Wait for the escalation to resolve; contact the plan operator if it persists. | -| [`PERMISSION_DENIED`](/docs/building/verification/compliance-catalog#error-code-permission-denied) | correctable | Authenticated identity is missing/mismatched, the buyer-side caller is not authorized by `delegations`, or the target/executing service is not authorized by `approved_sellers`. Retry only with the correct authenticated identity or after authority is granted. | +| [`PERMISSION_DENIED`](/docs/building/verification/compliance-catalog#error-code-permission-denied) | correctable | Authentication or credential failure, such as an unauthenticated caller, an authenticated identity that does not match the declared `caller`, or a presented `governance_context` that is expired, fails verification, or was issued for another plan. Retry only with valid credentials and the correct authenticated identity. A failed `delegations` or `approved_sellers` evaluation for an authenticated caller is a `denied` verdict with a finding in every governance mode, not this error. | | [`GOVERNANCE_UNAVAILABLE`](/docs/building/verification/compliance-catalog#error-code-governance-unavailable) | transient | The configured governance agent could not be reached. Retry with backoff; do not perform the governed action while the gate is unavailable. | ## Related tasks diff --git a/docs/governance/campaign/tasks/get_plan_audit_logs.mdx b/docs/governance/campaign/tasks/get_plan_audit_logs.mdx index dac3ff05a6..775dc400d2 100644 --- a/docs/governance/campaign/tasks/get_plan_audit_logs.mdx +++ b/docs/governance/campaign/tasks/get_plan_audit_logs.mdx @@ -323,7 +323,7 @@ You can combine `plan_ids` and `portfolio_plan_ids` to query both specific plans | `plans[].entries[].tool` | string | The AdCP tool (present for `check` entries). | | `plans[].entries[].verdict` | enum | Governance verdict: `approved`, `denied`, or `conditions` (present for `check` entries). Renamed from `status` in 3.1. | | `plans[].entries[].check_type` | enum | `intent` or `execution` (present for `check` entries). Inferred from the fields present on the original check request. | -| `plans[].entries[].mode` | enum | `audit`, `advisory`, or `enforce` — governance mode active when this check was evaluated. Recorded by the governance agent from its runtime configuration at check time, not from a plan field. Present on check entries; absent on outcome entries and on governance agents that have not yet adopted this field. Lets auditors distinguish `approved` decisions made under `enforce` from those made under `audit` (where the agent could not have blocked anything). | +| `plans[].entries[].mode` | enum | `audit`, `advisory`, or `enforce` — governance mode active when this check was evaluated. Recorded by the governance agent from its runtime configuration at check time, not from a plan field. Present on check entries; absent on outcome entries and on governance agents that have not yet adopted this field. Lets auditors distinguish `approved` decisions made under `enforce` from those made under `audit` (where the agent could not have blocked anything except an action on a plan with `human_review_required: true` or a failed `approved_sellers` or `delegations` evaluation). | | `plans[].entries[].explanation` | string | Human-readable explanation of the governance decision (present for `check` entries). | | `plans[].entries[].policies_evaluated` | array | Registry policy IDs evaluated during this check. | | `plans[].entries[].categories_evaluated` | array | Governance categories evaluated (e.g., `budget_authority`, `regulatory_compliance`). **Agent-internal labels**, not a protocol-level enum — each string is defined by the governance agent's policy model. Since one governance agent per account composes all specialist review (legal, brand safety, category-specialist reviewers) behind its single endpoint, `categories_evaluated` and `findings[].details` are how internal decomposition surfaces for audit. Consumers MUST treat values as opaque labels: pattern-matching against a fixed list is not safe across agents. | diff --git a/docs/governance/campaign/tasks/sync_plans.mdx b/docs/governance/campaign/tasks/sync_plans.mdx index a93b9f7b5e..1050b1931c 100644 --- a/docs/governance/campaign/tasks/sync_plans.mdx +++ b/docs/governance/campaign/tasks/sync_plans.mdx @@ -111,6 +111,8 @@ Plans originate in external systems -- an agency's planning tool, a brand's budg Syncing a plan that already exists (same `plan_id`) updates it. The governance agent increments the version. Active media buys approved under the previous version are not re-validated automatically; the governance agent evaluates them against the updated plan on their next [`check_governance`](/docs/governance/campaign/tasks/check_governance) call. This handles mid-flight amendments like budget increases or channel additions. Content-standards configurations are separate resources, and their wire contract does not define how running media buys adopt later updates; see [updating content-standards policies](/docs/governance/content-standards/index#updating-policies). +A `plan_id` is unique per owner principal. The authenticated buyer principal that syncs a plan owns it, and a `sync_plans` from another principal that names the same `plan_id` creates or updates that principal's own plan. The governance agent MUST NOT let it read, change or reveal the existence of another principal's plan. Buyers SHOULD use globally unique plan IDs, such as UUIDs. A `check_governance` caller that can access more than one plan with the `plan_id` it sends (a delegate of two owners that chose the same ID, for example) gets [`VALIDATION_ERROR`](/docs/building/verification/compliance-catalog#error-code-validation-error), and the check is evaluated against neither plan. + Multiple campaigns (identified by `governance_context` in [`check_governance`](/docs/governance/campaign/tasks/check_governance) and [`report_plan_outcome`](/docs/governance/campaign/tasks/report_plan_outcome)) can reference the same plan. The governance agent tracks budget across all campaigns tied to a plan. The plan specifies campaign context -- budget, channels, flight dates, and authorized markets. The governance agent resolves applicable policies from the brand's compliance configuration, but plans can also reference registry policies directly via `policy_ids` and include campaign-specific rules via `custom_policies`. This supports both centralized policy management (brand-level) and campaign-specific overrides when the buying team needs additional requirements for a particular campaign. @@ -180,7 +182,7 @@ Each plan item a buyer supplies here is the preimage the governance agent hashes | Field | Type | Required | Description | |-------|------|----------|-------------| | `plans` | array | Yes | One or more campaign plans to sync. | -| `plans[].plan_id` | string | Yes | Unique identifier for this plan. | +| `plans[].plan_id` | string | Yes | Identifier for this plan, unique per owner principal. See [How it works](#how-it-works). | | `plans[].brand` | BrandRef | Yes | Brand being governed. The governance agent resolves the brand's compliance configuration to determine applicable policies. | | `plans[].objectives` | string | Yes | Natural language campaign objectives. Used for strategic alignment validation. | | `plans[].budget` | object | Yes | Budget parameters. | @@ -288,8 +290,8 @@ Policy categories are distinct from `brand.industries`. Industries describe what | Code | Recovery | Description | |------|----------|-------------| | [`INVALID_REQUEST`](/docs/building/verification/compliance-catalog#error-code-invalid-request) | correctable | Plan is missing required fields or has invalid values, including a `flight.end` that is not later than `flight.start`, a repeated ID in `policy_ids`, and a `custom_policies[].policy_id` that equals an ID in `policy_ids`. For `budget.periods`, this covers a duplicate `budget_period_id`, overlapping or empty windows, a window outside `flight`, amounts above `budget.total`, and more than 366 periods. `error.field` identifies the offending plan field. | -| [`REFERENCE_NOT_FOUND`](/docs/building/verification/compliance-catalog#error-code-reference-not-found) | correctable | Brand domain could not be resolved via the Brand Protocol. The governance agent cannot determine applicable compliance policies without a valid brand reference. `error.field` MUST identify the brand field that failed to resolve. | -| [`VALIDATION_ERROR`](/docs/building/verification/compliance-catalog#error-code-validation-error) | correctable | Cannot reduce budget below the amount already committed (on plan update), leave a dated commitment outside every budget period, or set a period `amount` below what is already committed to it. `error.field` identifies the budget field. | +| [`REFERENCE_NOT_FOUND`](/docs/building/verification/compliance-catalog#error-code-reference-not-found) | correctable | Brand domain could not be resolved via the Brand Protocol, or a registry policy ID in `policy_ids` could not be resolved in the policy registry. The governance agent cannot determine applicable compliance policies without a valid brand reference. `error.field` MUST identify the brand field that failed to resolve, or name the `policy_ids` array parameter. | +| [`VALIDATION_ERROR`](/docs/building/verification/compliance-catalog#error-code-validation-error) | correctable | Cannot reduce budget below the amount already committed (on plan update), leave a dated commitment outside every budget period, or set a period `amount` below what is already committed to it. `error.field` identifies the budget field. Also returned for an explicit `human_review_required: false` on a plan whose resolved policies or policy categories require human review. | ## Related tasks diff --git a/docs/governance/overview.mdx b/docs/governance/overview.mdx index 569eb8a045..87f4fb6030 100644 --- a/docs/governance/overview.mdx +++ b/docs/governance/overview.mdx @@ -237,7 +237,7 @@ Every decision, every approval, every outcome — structured, timestamped, attri ## Crawl, walk, run -Jordan didn't start with full enforcement. She configured the governance agent to start in audit mode — it evaluated every check fully but always returned `approved`, attaching findings for her to review. After two weeks she reviewed the logs, tuned policies to reduce false positives, and moved to advisory. In advisory mode, the governance agent returned real `denied` statuses but Jordan's team treated them as non-blocking. When she trusted the system, she switched to enforce. +Jordan didn't start with full enforcement. She configured the governance agent to start in audit mode — it evaluated every check fully and returned `approved` with the findings attached for her to review. Two outcomes did not wait for enforce mode: a plan that requires human review still escalated, and an unapproved seller or a caller outside the plan's delegations was still denied. After two weeks she reviewed the logs, tuned policies to reduce false positives, and moved to advisory. In advisory mode, the governance agent returned `approved` with prominent findings, and Jordan's team reviewed them. When she trusted the system, she switched to enforce. The callers (orchestrator, sellers) never changed their code. They always acted on the status they received. The mode was entirely the governance agent's internal configuration. diff --git a/server/src/training-agent/governance-handlers.ts b/server/src/training-agent/governance-handlers.ts index dfbe841ca0..78931a6fb6 100644 --- a/server/src/training-agent/governance-handlers.ts +++ b/server/src/training-agent/governance-handlers.ts @@ -1276,6 +1276,20 @@ export async function handleSyncPlans(args: ToolArgs, ctx: TrainingContext) { } } } + + // A re-sync may not reduce budget.total below what is already committed + // to the plan. The prior plan stays in force. + if (existing + && plan.budget.total < existing.budget.total + && exceedsBound(existing.committedBudget, plan.budget.total)) { + return { + errors: [{ + code: 'VALIDATION_ERROR', + message: `plan ${plan.plan_id} budget.total ${plan.budget.total} is below the $${existing.committedBudget} already committed to it`, + field: `plans[${i}].budget.total`, + }], + }; + } } for (const [planIndex, plan] of input.plans.entries()) { @@ -1724,14 +1738,42 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext }; } + // An authenticated caller that fails an authority gate before plan + // evaluation gets a denied verdict, not an error: the attempt has a check_id + // and, when the plan owner is known, an entry in that plan's audit log. The + // record carries no governance_context and no action binding, and the + // response reveals nothing about the plan. The denial does not depend on the + // plan's mode. + const denyBeforeEvaluation = ( + finding: GovernanceFinding, + explanation: string, + extra: Partial> = {}, + ) => { + const checkId = `chk_${randomUUID().slice(0, 8)}`; + const check: GovernanceCheckState = { + checkId, + planId, + binding, + status: 'denied', + caller, + tool, + phase, + findings: [finding], + explanation, + mode: 'enforce', + categoriesEvaluated: [finding.categoryId], + policiesEvaluated: [], + purchaseType, + timestamp: new Date().toISOString(), + ...extra, + }; + session.governanceChecks.set(checkId, check); + return buildCheckResponse(check, governanceServedVersion(ctx)); + }; + if ( binding === 'committed' - && ( - !priorCheck?.targetAudience - || authenticatedCaller === undefined - || authenticatedCaller !== priorCheck.targetAudience - || claimedCaller !== priorCheck.targetAudience - ) + && (!priorCheck?.targetAudience || authenticatedCaller === undefined) ) { return { errors: [{ @@ -1741,6 +1783,18 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext }; } + if (binding === 'committed' && authenticatedCaller !== priorCheck?.targetAudience) { + const explanation = `Caller ${caller} is not the service audience bound by the approved intent.`; + return denyBeforeEvaluation( + { categoryId: 'seller_compliance', severity: 'critical', explanation }, + `Denied: ${explanation}`, + { + ...(priorCheck?.planOwnerAgentUrl ? { planOwnerAgentUrl: priorCheck.planOwnerAgentUrl } : {}), + tool: priorCheck?.tool, + }, + ); + } + if ( binding === 'committed' && (phase === 'modification' || phase === 'delivery') @@ -1869,27 +1923,17 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext }; } + // One response for a plan that does not exist and for a plan the caller + // cannot access (error-code.json PLAN_NOT_FOUND, uniform-response rule). + // Nothing is stored and no check_id is issued. if (!plan) { - const checkId = `chk_${randomUUID().slice(0, 8)}`; - const check: GovernanceCheckState = { - checkId, - planId, - governanceContext, - binding, - status: 'denied', - caller, - tool, - phase, - findings: [{ categoryId: 'plan_lookup', severity: 'critical', explanation: `Plan not found: ${planId}` }], - explanation: `Plan not found: ${planId}. Call sync_plans first.`, - mode: 'enforce', - categoriesEvaluated: ['plan_lookup'], - policiesEvaluated: [], - purchaseType, - timestamp: new Date().toISOString(), + return { + errors: [{ + code: 'PLAN_NOT_FOUND', + message: 'No plan with this plan_id exists or is accessible to the caller. Call sync_plans first.', + field: 'plan_id', + }], }; - session.governanceChecks.set(checkId, check); - return buildCheckResponse(check, governanceServedVersion(ctx)); } const ownerOrDelegated = authenticatedCaller === plan.ownerAgentUrl @@ -1897,9 +1941,12 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext delegation.agentUrl === authenticatedCaller && (!delegation.expiresAt || new Date(delegation.expiresAt) >= new Date()))); if (binding === 'proposed' && !ownerOrDelegated) { - return { - errors: [{ code: 'PERMISSION_DENIED', message: 'The authenticated buyer does not own this plan and has no active delegation.' }], - }; + const explanation = `Buyer-side caller ${caller} is not the plan owner and holds no current delegation on this plan.`; + return denyBeforeEvaluation( + { categoryId: 'delegation_authority', severity: 'critical', explanation }, + `Denied: ${explanation}`, + { planOwnerAgentUrl: plan.ownerAgentUrl }, + ); } const originalIntentCheck = priorCheck?.binding === 'proposed' @@ -2585,9 +2632,15 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext // Apply governance mode — but mode CANNOT neuter human_review_required. // Annex III / Art 22 obligations override advisory/audit downgrades. + // Mode also cannot approve an authority failure (adcp#8733 A4): a failed + // approved_sellers or delegations evaluation is denied in every mode. const mode = plan.mode; + const authorityFailed = criticalFindings.some(finding => + finding.categoryId === 'seller_compliance' || finding.categoryId === 'delegation_authority'); if (!plan.humanReviewRequired) { - if (mode === 'advisory' && (status === 'denied' || status === 'conditions')) { + if (authorityFailed) { + // Leave the denial in place. + } else if (mode === 'advisory' && (status === 'denied' || status === 'conditions')) { status = 'approved'; } else if (mode === 'audit') { status = 'approved'; diff --git a/server/tests/unit/training-agent-governance-agent-credentials.test.ts b/server/tests/unit/training-agent-governance-agent-credentials.test.ts index 5ae02aa1e8..aa2600e0d6 100644 --- a/server/tests/unit/training-agent-governance-agent-credentials.test.ts +++ b/server/tests/unit/training-agent-governance-agent-credentials.test.ts @@ -177,8 +177,10 @@ describe('governance agent credentials (adcp#7758)', () => { expect(publicAsSeller.error?.message).toContain('must match caller'); const publicAsItself = await callTool(governanceMcp(), PUBLIC_TOKEN, 'check_governance', executionCheck(context, PUBLIC_IDENTITY)); - expect(publicAsItself.error?.code).toBe('PERMISSION_DENIED'); - expect(publicAsItself.error?.message).toContain('service audience'); + expect(publicAsItself.error, JSON.stringify(publicAsItself.json)).toBeUndefined(); + expect(publicAsItself.structured.verdict).toBe('denied'); + expect(publicAsItself.structured.governance_context).toBeUndefined(); + expect((publicAsItself.structured.findings as Array<{ category_id?: string }>)[0]?.category_id).toBe('seller_compliance'); }); it('lets a minted credential run the seller execution check at the registered governance URL', async () => { @@ -223,8 +225,10 @@ describe('governance agent credentials (adcp#7758)', () => { expect(claimsSeller.error?.code).toBe('PERMISSION_DENIED'); const asItself = await callTool(governanceMcp(), otherSellerCredential, 'check_governance', executionCheck(context, OTHER_SELLER)); - expect(asItself.error?.code).toBe('PERMISSION_DENIED'); - expect(asItself.error?.message).toContain('service audience'); + expect(asItself.error, JSON.stringify(asItself.json)).toBeUndefined(); + expect(asItself.structured.verdict).toBe('denied'); + expect(asItself.structured.governance_context).toBeUndefined(); + expect((asItself.structured.findings as Array<{ category_id?: string }>)[0]?.category_id).toBe('seller_compliance'); }); it('scopes the credential to the plans of its own hosted run', async () => { diff --git a/server/tests/unit/training-agent-governance-budget-periods.test.ts b/server/tests/unit/training-agent-governance-budget-periods.test.ts index f2d60cb9db..f2a7824f94 100644 --- a/server/tests/unit/training-agent-governance-budget-periods.test.ts +++ b/server/tests/unit/training-agent-governance-budget-periods.test.ts @@ -552,6 +552,59 @@ describe('sync_plans re-sync with existing commitments', () => { const result = await intent(30_000, { start_time: '2027-02-01T00:00:00Z', end_time: '2027-03-01T00:00:00Z' }); expect(result.verdict).toBe('approved'); })); + + // adcp#8733 A1: the same rule for budget.total. + const totalOnly = (total: number) => + plan(null, { budget: { total, currency: 'USD', reallocation_unlimited: true } }); + + it('rejects a budget.total reduced below what is already committed to the plan', () => run(async () => { + await syncOk(plan(null)); + await commit('mb_total_a', 30_000, '2027-01-15T00:00:00Z', '2027-03-15T00:00:00Z'); + const result = await sync(totalOnly(29_999)); + expect(result.errors?.[0]).toMatchObject({ + code: 'VALIDATION_ERROR', + field: 'plans[0].budget.total', + }); + expect(result.errors[0].message).toContain('below the $30000 already committed'); + })); + + it('accepts a budget.total equal to the committed amount to stop new spending', () => run(async () => { + await syncOk(plan(null)); + await commit('mb_total_a', 30_000, '2027-01-15T00:00:00Z', '2027-03-15T00:00:00Z'); + await syncOk(totalOnly(30_000)); + const blocked = await intent(1, undefined); + expect(blocked.verdict).toBe('conditions'); + })); + + it('does not mutate the plan when a budget.total cut is rejected', () => run(async () => { + await syncOk(plan(null)); + await commit('mb_total_a', 30_000, '2027-01-15T00:00:00Z', '2027-03-15T00:00:00Z'); + const rejected = await sync(totalOnly(1)); + expect(rejected.errors?.[0]?.code).toBe('VALIDATION_ERROR'); + // The original total is still in force and the version did not advance. + const result = await intent(60_000, { start_time: '2027-04-01T00:00:00Z', end_time: '2027-05-01T00:00:00Z' }); + expect(result.verdict).toBe('approved'); + const resynced = await syncOk(plan(null)); + expect(resynced.plans[0].version).toBe(2); + })); + + it('still accepts a re-sync that does not reduce budget.total on an over-committed plan', () => run(async () => { + await syncOk(plan(null)); + // Checks do not reserve budget, so two approvals can together exceed the total. + const first = await intent(60_000, { start_time: '2027-01-15T00:00:00Z', end_time: '2027-02-15T00:00:00Z' }); + const second = await intent(60_000, { start_time: '2027-02-15T00:00:00Z', end_time: '2027-03-15T00:00:00Z' }); + await settle(first, 'mb_total_a'); + await settle(second, 'mb_total_b'); + // The total is unchanged, so the plan can still be edited. + await syncOk(plan(null, { countries: ['US', 'CA'] })); + // A further cut is rejected. + const result = await sync(totalOnly(99_999)); + expect(result.errors?.[0]).toMatchObject({ + code: 'VALIDATION_ERROR', + field: 'plans[0].budget.total', + }); + expect(result.errors[0].message).toContain('below the $120000 already committed'); + })); }); describe('flight spoofing and ledger coverage', () => { diff --git a/server/tests/unit/training-agent-governance-caller-binding.test.ts b/server/tests/unit/training-agent-governance-caller-binding.test.ts index c846a1f007..b8c9df9f84 100644 --- a/server/tests/unit/training-agent-governance-caller-binding.test.ts +++ b/server/tests/unit/training-agent-governance-caller-binding.test.ts @@ -7,7 +7,7 @@ import { handleSyncPlans, } from '../../src/training-agent/governance-handlers.js'; import { computeDeliveryStatementDigest } from '../../src/training-agent/governance-payload-hash.js'; -import { clearSessions, getSession, runWithSessionContext } from '../../src/training-agent/state.js'; +import { clearSessions, getSession, runWithSessionContext, sessionKeyFromArgs } from '../../src/training-agent/state.js'; import type { TrainingContext } from '../../src/training-agent/types.js'; const DELEGATE = 'https://delegated.example'; @@ -142,6 +142,123 @@ describe('check_governance authenticated caller binding', () => { }); }); + // adcp#8733 A4: a buyer-side caller that lost its delegation gets a verdict. + it('denies a re-check by a caller whose delegation was removed and audits the attempt', async () => { + await runWithSessionContext(async () => { + const delegateCtx: TrainingContext = { mode: 'open', authenticatedAgentUrl: DELEGATE }; + const policies = [{ policy_id: 'frequency', policy: 'Apply a frequency cap.', enforcement: 'must' }]; + expect((await sync({ + delegations: [{ agent_url: DELEGATE, authority: 'full' }], + custom_policies: policies, + })).errors).toBeUndefined(); + const conditioned = await check(DELEGATE, delegateCtx); + expect(conditioned.verdict, JSON.stringify(conditioned)).toBe('conditions'); + + expect((await sync({ custom_policies: policies })).errors).toBeUndefined(); + const result = await handleCheckGovernance({ + plan_id: PLAN.plan_id, + caller: DELEGATE, + target_agent: 'https://seller.example', + tool: 'create_media_buy', + consultation_context: conditioned.consultation_context, + payload: { + total_budget: { amount: 10_000, currency: 'USD' }, + geo: { countries: ['US'] }, + ext: { governance_policy_acknowledgements: ['frequency'] }, + }, + }, delegateCtx) as Record; + const audit = await handleGetPlanAuditLogs({ + brand: BRAND, + plan_ids: [PLAN.plan_id], + include_entries: true, + }, OWNER_CTX) as Record; + + expect(result.errors).toBeUndefined(); + expect(result.verdict).toBe('denied'); + expect(result.check_id).toEqual(expect.any(String)); + expect(result.findings).toEqual([ + expect.objectContaining({ category_id: 'delegation_authority', severity: 'critical' }), + ]); + expect(result).not.toHaveProperty('governance_context'); + expect(result).not.toHaveProperty('consultation_context'); + expect(audit.plans[0].entries).toContainEqual(expect.objectContaining({ + id: result.check_id, + type: 'check', + caller: DELEGATE, + verdict: 'denied', + })); + }); + }); + + it('answers a caller with no relationship to the plan as it answers an unknown plan, and writes nothing', async () => { + await runWithSessionContext(async () => { + expect((await sync()).errors).toBeUndefined(); + const strangerCtx: TrainingContext = { mode: 'open', authenticatedAgentUrl: ATTACKER }; + const existing = await check(ATTACKER, strangerCtx); + const unknown = await handleCheckGovernance({ + plan_id: 'plan-that-does-not-exist', + caller: ATTACKER, + target_agent: 'https://seller.example', + tool: 'create_media_buy', + payload: { + total_budget: { amount: 10_000, currency: 'USD' }, + geo: { countries: ['US'] }, + }, + }, strangerCtx) as Record; + const audit = await handleGetPlanAuditLogs({ + brand: BRAND, + plan_ids: [PLAN.plan_id], + include_entries: true, + }, OWNER_CTX) as Record; + + // error-code.json PLAN_NOT_FOUND: one response for both cases, no verdict and no check_id. + expect(existing).toEqual({ + errors: [{ code: 'PLAN_NOT_FOUND', message: expect.any(String), field: 'plan_id' }], + }); + expect(JSON.stringify(existing)).toBe(JSON.stringify(unknown)); + expect(audit.plans[0].summary.checks_performed).toBe(0); + // Neither the owner's session nor the request's own session holds a check. + for (const key of ['open:caller-binding.example', sessionKeyFromArgs({}, 'open')]) { + expect((await getSession(key)).governanceChecks.size).toBe(0); + } + }); + }); + + it('denies the preserved audience once it is removed from approved_sellers and audits the attempt', async () => { + await runWithSessionContext(async () => { + const seller = 'https://seller.example'; + expect((await sync({ approved_sellers: [seller] })).errors).toBeUndefined(); + const intent = await check(OWNER, OWNER_CTX); + expect(intent.verdict, JSON.stringify(intent)).toBe('approved'); + + expect((await sync({ approved_sellers: ['https://other-seller.example'] })).errors).toBeUndefined(); + const result = await handleCheckGovernance({ + caller: seller, + governance_context: intent.governance_context, + phase: 'purchase', + planned_delivery: { media_buy_id: 'mb_removed_seller', total_budget: 10_000, currency: 'USD' }, + }, { mode: 'open', authenticatedAgentUrl: seller }) as Record; + const audit = await handleGetPlanAuditLogs({ + brand: BRAND, + plan_ids: [PLAN.plan_id], + include_entries: true, + }, OWNER_CTX) as Record; + + expect(result.errors).toBeUndefined(); + expect(result.verdict).toBe('denied'); + expect(result.findings).toContainEqual( + expect.objectContaining({ category_id: 'seller_compliance', severity: 'critical' }), + ); + expect(result).not.toHaveProperty('governance_context'); + expect(audit.plans[0].entries).toContainEqual(expect.objectContaining({ + id: result.check_id, + caller: seller, + check_type: 'execution', + verdict: 'denied', + })); + }); + }); + it('rejects a same-owner re-sync that would move an existing plan to a fresh scope', async () => { await runWithSessionContext(async () => { expect((await sync()).errors).toBeUndefined(); diff --git a/server/tests/unit/training-agent-governance-intent-binding.test.ts b/server/tests/unit/training-agent-governance-intent-binding.test.ts index 7448f92e52..0b4d40f74b 100644 --- a/server/tests/unit/training-agent-governance-intent-binding.test.ts +++ b/server/tests/unit/training-agent-governance-intent-binding.test.ts @@ -6,6 +6,7 @@ import { decodeJwt } from 'jose'; import { handleUpdateMediaBuy } from '../../src/training-agent/task-handlers.js'; import { handleCheckGovernance, + handleGetPlanAuditLogs, handleSyncPlans, } from '../../src/training-agent/governance-handlers.js'; import { @@ -851,24 +852,152 @@ describe('check_governance request-shape binding', () => { expect(result).not.toHaveProperty('governance_context'); }); - it('rejects execution by an agent other than the intent token audience', async () => { + const ownerAudit = () => handleGetPlanAuditLogs({ + brand: PLAN.brand, + plan_ids: [PLAN.plan_id], + include_entries: true, + }, CTX) as Promise>; + + const executionAs = (caller: string, governanceContext: unknown, ctx: TrainingContext) => + handleCheckGovernance({ + caller, + governance_context: governanceContext, + phase: 'purchase', + planned_delivery: { total_budget: 1_000, currency: 'USD' }, + }, ctx) as Promise>; + + const approvedIntent = () => check({ + tool: 'create_media_buy', + target_agent: 'https://seller.example', + payload: { + total_budget: { amount: 1_000, currency: 'USD' }, + }, + }); + + // adcp#8733 A4: an authenticated caller that is not the audience gets a verdict. + it('denies execution by an authenticated agent other than the intent token audience and audits the attempt', async () => { + const { result, audit } = await withPlan(async () => { + const intent = await approvedIntent(); + const result = await executionAs( + 'https://attacker.example', + intent.governance_context, + { ...CTX, authenticatedAgentUrl: 'https://attacker.example' }, + ); + return { result, audit: await ownerAudit() }; + }); + + expect(result.errors).toBeUndefined(); + expect(result.verdict).toBe('denied'); + expect(result.check_type).toBe('execution'); + expect(result.check_id).toEqual(expect.any(String)); + expect(result.findings).toEqual([ + expect.objectContaining({ category_id: 'seller_compliance', severity: 'critical' }), + ]); + expect(result).not.toHaveProperty('governance_context'); + expect(result).not.toHaveProperty('plan_id'); + expect(audit.plans[0].entries).toContainEqual(expect.objectContaining({ + id: result.check_id, + type: 'check', + caller: 'https://attacker.example', + check_type: 'execution', + verdict: 'denied', + })); + }); + + it.each(['advisory', 'audit'])('denies a non-audience execution caller in %s mode', async (mode) => { const result = await withPlan(async () => { - const intent = await check({ - tool: 'create_media_buy', - target_agent: 'https://seller.example', - payload: { - total_budget: { amount: 1_000, currency: 'USD' }, - }, - }); + const resync = await handleSyncPlans({ plans: [{ ...PLAN, mode }] }, CTX) as Record; + expect(resync.errors, JSON.stringify(resync)).toBeUndefined(); + const intent = await approvedIntent(); + return executionAs( + 'https://attacker.example', + intent.governance_context, + { ...CTX, authenticatedAgentUrl: 'https://attacker.example' }, + ); + }); + + expect(result.errors).toBeUndefined(); + expect(result.verdict).toBe('denied'); + expect(result).not.toHaveProperty('governance_context'); + }); + + // adcp#8733 A4: mode does not approve a failed approved_sellers or delegations evaluation. + it.each(['advisory', 'audit'])('denies an intent whose target seller is outside approved_sellers in %s mode', async (mode) => { + const { result, audit } = await withPlan(async () => { + const resync = await handleSyncPlans({ + plans: [{ ...PLAN, mode, approved_sellers: ['https://approved-seller.example'] }], + }, CTX) as Record; + expect(resync.errors, JSON.stringify(resync)).toBeUndefined(); + const result = await approvedIntent(); + return { result, audit: await ownerAudit() }; + }); + + expect(result.errors).toBeUndefined(); + expect(result.verdict).toBe('denied'); + expect(result.check_id).toEqual(expect.any(String)); + expect(result.findings).toContainEqual( + expect.objectContaining({ category_id: 'seller_compliance', severity: 'critical' }), + ); + expect(result).not.toHaveProperty('governance_context'); + expect(audit.plans[0].entries).toContainEqual(expect.objectContaining({ + id: result.check_id, + type: 'check', + verdict: 'denied', + })); + }); + + it.each(['advisory', 'audit'])('denies an intent from a delegate over its budget_limit in %s mode', async (mode) => { + const result = await withPlan(async () => { + const resync = await handleSyncPlans({ + plans: [{ ...PLAN, mode, delegations: [{ agent_url: 'https://delegate.example', authority: 'full', budget_limit: { amount: 500, currency: 'USD' } }] }], + }, CTX) as Record; + expect(resync.errors, JSON.stringify(resync)).toBeUndefined(); return handleCheckGovernance({ - caller: 'https://attacker.example', - governance_context: intent.governance_context, - phase: 'purchase', - planned_delivery: { total_budget: 1_000, currency: 'USD' }, - }, { ...CTX, authenticatedAgentUrl: 'https://attacker.example' }) as Promise>; + plan_id: PLAN.plan_id, + caller: 'https://delegate.example', + target_agent: 'https://seller.example', + tool: 'create_media_buy', + payload: { total_budget: { amount: 1_000, currency: 'USD' } }, + }, { ...CTX, authenticatedAgentUrl: 'https://delegate.example' }) as Promise>; + }); + + expect(result.errors).toBeUndefined(); + expect(result.verdict).toBe('denied'); + expect(result.findings).toContainEqual( + expect.objectContaining({ category_id: 'delegation_authority', severity: 'critical' }), + ); + expect(result).not.toHaveProperty('governance_context'); + }); + + it('keeps PERMISSION_DENIED for an unauthenticated execution check and writes no audit entry', async () => { + const { result, audit } = await withPlan(async () => { + const intent = await approvedIntent(); + const result = await executionAs('https://seller.example', intent.governance_context, { mode: 'open' }); + return { result, audit: await ownerAudit() }; + }); + + expect(result.errors?.[0]?.code).toBe('PERMISSION_DENIED'); + expect(result).not.toHaveProperty('check_id'); + // Only the buyer's own intent check is in the log. + expect(audit.plans[0].summary.checks_performed).toBe(1); + }); + + it('rejects an expired context before the audience check, so it writes no audit entry', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-08-04T12:00:00Z')); + const { result, audit } = await withPlan(async () => { + const intent = await approvedIntent(); + vi.setSystemTime(new Date('2026-08-04T12:16:01Z')); + const result = await executionAs( + 'https://attacker.example', + intent.governance_context, + { ...CTX, authenticatedAgentUrl: 'https://attacker.example' }, + ); + return { result, audit: await ownerAudit() }; }); expect(result.errors?.[0]?.code).toBe('PERMISSION_DENIED'); + expect(audit.plans[0].summary.checks_performed).toBe(1); }); it.each([ diff --git a/server/tests/unit/training-agent.test.ts b/server/tests/unit/training-agent.test.ts index ff75bc5f77..f7c15c0680 100644 --- a/server/tests/unit/training-agent.test.ts +++ b/server/tests/unit/training-agent.test.ts @@ -18966,8 +18966,8 @@ describe('sync_plans input validation', () => { binding: 'proposed', caller: 'https://buyer.example', }); - expect(result.status).toBe('denied'); - expect(result.explanation).toContain('Plan not found'); + expect(result.code).toBe('PLAN_NOT_FOUND'); + expect(result.field).toBe('plan_id'); }); }); diff --git a/static/schemas/source/enums/delegation-authority.json b/static/schemas/source/enums/delegation-authority.json index d89d0f56c8..e98982c67a 100644 --- a/static/schemas/source/enums/delegation-authority.json +++ b/static/schemas/source/enums/delegation-authority.json @@ -11,7 +11,7 @@ ], "enumDescriptions": { "full": "Can execute any action within the delegation's budget and market constraints.", - "execute_only": "Can execute pre-approved actions but cannot initiate new campaigns or reallocate budget.", + "execute_only": "Can execute pre-approved actions but cannot initiate new campaigns or reallocate budget. A pre-approved action is one whose opaque action binding already holds an approved intent check in the plan's lifecycle: the delegate may act only on such an action, which includes accept_proposal for it. The governance agent MUST deny an intent check from an execute_only delegate that would create a new binding or increase committed spend.", "propose_only": "Can propose actions for governance review but cannot execute without explicit approval." } } diff --git a/static/schemas/source/enums/governance-mode.json b/static/schemas/source/enums/governance-mode.json index 51373d9add..55d737cf78 100644 --- a/static/schemas/source/enums/governance-mode.json +++ b/static/schemas/source/enums/governance-mode.json @@ -11,8 +11,8 @@ "enforce" ], "enumDescriptions": { - "audit": "Log all checks, never block. Findings are recorded but the governance agent always returns approved.", - "advisory": "Flag issues and return findings, but do not block execution. Human reviews happen post-hoc.", + "audit": "Log all checks. Findings are recorded and the governance agent returns approved, except in two cases that hold in every mode: plans with human_review_required: true escalate, and a failed approved_sellers or delegations evaluation is denied.", + "advisory": "Flag issues and return findings, but do not block execution. Human reviews happen post-hoc. The same two exceptions apply as in audit mode.", "enforce": "Block on denied or escalated. Require resolution before proceeding." } } diff --git a/static/schemas/source/governance/sync-plans-request.json b/static/schemas/source/governance/sync-plans-request.json index 627dbd9fe2..b61ba3027f 100644 --- a/static/schemas/source/governance/sync-plans-request.json +++ b/static/schemas/source/governance/sync-plans-request.json @@ -28,7 +28,7 @@ "properties": { "plan_id": { "type": "string", - "description": "Unique identifier for this plan.", + "description": "Identifier for this plan, unique per owner principal. Two principals may use the same `plan_id`; neither can read, change or detect the other's plan.", "x-entity": "governance_plan" }, "brand": {