Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
218 changes: 213 additions & 5 deletions server/src/training-agent/governance-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,48 @@ function sessionBuyCommitments(session: SessionState, plan: GovernancePlanState)
);
}

/**
* The pre-approved action an intent check acts on, for an `execute_only`
* delegate (specification.mdx "Delegation"; enums/delegation-authority.json).
* A pre-approved action is one whose opaque action binding already holds an
* approved intent check in this plan's lifecycle. The intent check names it
* either through the media buy that binding governs (`payload.media_buy_id`,
* or the `media_buy_id` of an update or cancellation proposal), or, for
* `accept_proposal`, through a proposal an approved intent check already
* authorized.
*/
function findPreApprovedAction(
session: SessionState,
plan: GovernancePlanState,
mediaBuyId: string | undefined,
proposalId: string | undefined,
): { intent: GovernanceCheckState; via: 'media_buy' | 'proposal' } | undefined {
const onPlan = (entry: { planId: string; planOwnerAgentUrl?: string }) =>
entry.planId === plan.planId && entry.planOwnerAgentUrl === plan.ownerAgentUrl;
const checks = [...session.governanceChecks.values()].filter(onPlan);
const isApprovedIntent = (check: GovernanceCheckState) =>
check.binding === 'proposed' && check.status === 'approved' && check.governanceBindingId !== undefined;
if (mediaBuyId) {
const buyKey = mediaBuyId.slice(0, 255);
const bindingIds = new Set<string>();
for (const check of checks) {
if (check.mediaBuyId?.slice(0, 255) === buyKey && check.governanceBindingId) bindingIds.add(check.governanceBindingId);
}
for (const outcome of session.governanceOutcomes.values()) {
if (onPlan(outcome) && outcome.mediaBuyId === buyKey && outcome.governanceBindingId) {
bindingIds.add(outcome.governanceBindingId);
}
}
const intent = checks.find(check => isApprovedIntent(check) && bindingIds.has(check.governanceBindingId!));
if (intent) return { intent, via: 'media_buy' };
}
if (proposalId) {
const intent = checks.find(check => isApprovedIntent(check) && check.authorizedProposalId === proposalId);
if (intent) return { intent, via: 'proposal' };
}
return undefined;
}

/**
* Evaluate one action against the plan's budget periods and translate the
* result into critical findings. The action's flight is resolved even when the
Expand Down Expand Up @@ -512,6 +554,8 @@ interface GovernanceCanonicalProposal {
proposal_status: string;
commercial_terms: Record<string, unknown>;
terms_digest: string;
/** The existing buy an update or cancellation proposal changes. */
media_buy_id?: unknown;
}

interface CheckPayload {
Expand All @@ -522,13 +566,16 @@ interface CheckPayload {
budget?: number;
channels?: string[];
canceled?: boolean;
targeting_overlay?: { geo_regions?: unknown };
}>;
new_packages?: Array<{ budget?: number }>;
budget?: number | { total?: number };
total_budget?: number | { amount?: number };
geo?: { countries?: string[] };
targeting?: { countries?: string[] };
geo?: { countries?: string[]; regions?: unknown };
targeting?: { countries?: string[]; geo_regions?: unknown };
targeting_overlay?: { geo_regions?: unknown };
countries?: string[];
regions?: unknown;
channels?: string[];
channel?: string;
start_time?: string;
Expand Down Expand Up @@ -630,7 +677,7 @@ interface PlannedDeliveryInput {
media_buy_id?: string;
proposal_id?: string;
proposal_terms_digest?: string;
geo?: { countries?: string[] };
geo?: { countries?: string[]; regions?: unknown };
channels?: string[];
start_time?: string;
end_time?: string;
Expand Down Expand Up @@ -1446,11 +1493,21 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext
: sellerCredentialPlanScopeError(ctx, planId);
if (credentialError) return credentialError;
}
// A presented governance_context, and its match with plan_id, is verified
// before plan access is resolved. A context this agent did not issue, or
// one issued for another plan, is a credential failure: PERMISSION_DENIED
// whether or not plan_id names a plan (specification.mdx "Governance-agent
// obligations"; error-code.json PERMISSION_DENIED). An intent-shaped request
// that carries a context is malformed instead, and is rejected below.
const intentShapedRequest = req.tool !== undefined && req.payload !== undefined;
if (governanceContext && !priorCheck && !intentShapedRequest) {
return { errors: [{ code: 'PERMISSION_DENIED', message: 'governance_context was not issued by this governance agent or is no longer known.' }] };
}
if (!planId) {
return { errors: [{ code: 'PLAN_NOT_FOUND', message: 'No plan could be resolved from plan_id or governance_context.' }] };
}
if (req.plan_id && priorCheck && req.plan_id !== priorCheck.planId) {
return { errors: [{ code: 'VALIDATION_ERROR', message: 'plan_id does not match the governance_context binding.' }] };
return { errors: [{ code: 'PERMISSION_DENIED', message: 'governance_context was issued for a different plan than plan_id.' }] };
}
if (req.plan_id && priorConsultationCheck && req.plan_id !== priorConsultationCheck.planId) {
return { errors: [{ code: 'VALIDATION_ERROR', message: 'plan_id does not match the consultation_context.' }] };
Expand Down Expand Up @@ -1721,7 +1778,7 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext

if (binding === 'committed' && !priorCheck) {
return {
errors: [{ code: 'VALIDATION_ERROR', message: 'governance_context is unknown or expired.' }],
errors: [{ code: 'PERMISSION_DENIED', message: 'governance_context was not issued by this governance agent or is no longer known.' }],
};
}

Expand Down Expand Up @@ -2170,6 +2227,44 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext
}
}

// Delegation authority level. An execute_only delegate acts only on a
// pre-approved action, which includes accept_proposal for it; an intent
// check that would open a new action or increase committed spend is
// denied. The finding is a delegations failure, so it is denied in every
// governance mode (adcp#8733 A4, C2).
if (callerDelegation?.authority === 'execute_only') {
const proposalMediaBuyId = req.proposal?.proposal_kind !== 'new_media_buy'
? req.proposal?.media_buy_id
: undefined;
const targetMediaBuyId = typeof policyPayload.media_buy_id === 'string'
? policyPayload.media_buy_id
: typeof proposalMediaBuyId === 'string'
? proposalMediaBuyId
: undefined;
const preApproved = findPreApprovedAction(session, plan, targetMediaBuyId, req.proposal?.proposal_id);
if (!preApproved) {
findings.push({
categoryId: 'delegation_authority',
severity: 'critical',
explanation: `Delegated agent ${caller} has execute_only authority and may act only on a pre-approved action; this ${tool} intent would open a new governed action.`,
});
} else {
// Acting on a pre-approved media buy, any positive commitment is new
// spend on top of it. Re-authorizing a pre-approved proposal may carry
// what that proposal's approved intent already authorized, no more.
const preApprovedCommitment = preApproved.via === 'proposal' ? preApproved.intent.authorizedBudget ?? 0 : 0;
if (payloadBudget !== undefined && payloadBudget > preApprovedCommitment) {
findings.push({
categoryId: 'delegation_authority',
severity: 'critical',
explanation: preApproved.via === 'proposal'
? `Delegated agent ${caller} has execute_only authority and cannot increase committed spend: this ${tool} intent commits $${payloadBudget}, more than the $${preApprovedCommitment} the pre-approved proposal authorized.`
: `Delegated agent ${caller} has execute_only authority and cannot increase committed spend: this ${tool} intent adds $${payloadBudget} to pre-approved media buy ${targetMediaBuyId}.`,
});
}
}
}

// Budget compliance
categoriesEvaluated.push('budget_authority');
if (payloadBudget !== undefined) {
Expand Down Expand Up @@ -2258,6 +2353,37 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext
}
}

// A regions-restricted plan admits only actions that target its regions.
// No geography, or country-level geography only, targets the whole country
// and is outside the plan, as is a region the plan does not list. At intent
// that is a counterproposal naming the region constraint. A modification
// that states no regions keeps the buy's existing geography, so only the
// regions it states are compared.
if (plan.regions?.length) {
const planRegions = plan.regions;
const planRegionSet = new Set(planRegions);
const isModification = typeof policyPayload.media_buy_id === 'string'
|| (req.proposal !== undefined && req.proposal.proposal_kind !== 'new_media_buy');
const regionScopes = req.proposal
? extractProposalRegionScopes(req.proposal)
: extractRegionScopes(policyPayload);
for (const scope of regionScopes) {
const outside = scope.regions.filter(region => !planRegionSet.has(region));
const countryWide = scope.regions.length === 0;
if (countryWide ? isModification : outside.length === 0) continue;
const inPlan = scope.regions.filter(region => planRegionSet.has(region));
const reason = countryWide
? `Plan is restricted to regions ${planRegions.join(', ')}; an action without region-level targeting targets the whole country.`
: `Regions ${outside.join(', ')} are outside the plan's regions ${planRegions.join(', ')}.`;
findings.push({ categoryId: 'geo_compliance', severity: 'warning', explanation: reason });
conditions.push({
field: scope.field,
requiredValue: inPlan.length > 0 ? inPlan : [...planRegions],
reason,
});
}
}

// Channel compliance
categoriesEvaluated.push('channel_compliance');
if (payloadChannels.length > 0 && plan.channels?.allowed?.length) {
Expand Down Expand Up @@ -2401,6 +2527,31 @@ export async function handleCheckGovernance(args: ToolArgs, ctx: TrainingContext
}
}

// On a regions-restricted plan, a purchase must state region-level
// delivery inside the plan's regions: none, or country-level only, delivers
// country-wide and is denied. A modification that states no regions keeps
// the buy's existing geography, as at intent, and a delivery check reports
// on a commitment already authorized, so for both only the regions stated
// are compared.
if (plan.regions?.length) {
const planRegionSet = new Set(plan.regions);
const pdRegions = stringList(plannedDelivery.geo?.regions) ?? [];
const outside = pdRegions.filter(region => !planRegionSet.has(region));
if (pdRegions.length === 0 && phase === 'purchase') {
findings.push({
categoryId: 'geo_compliance',
severity: 'critical',
explanation: `Planned delivery states no region-level geography, so it delivers country-wide; the plan is restricted to regions ${plan.regions.join(', ')}.`,
});
} else if (outside.length > 0) {
findings.push({
categoryId: 'geo_compliance',
severity: 'critical',
explanation: `Planned delivery includes regions outside the plan: ${outside.join(', ')}. Plan allows: ${plan.regions.join(', ')}.`,
});
}
}

const pdChannels = plannedDelivery.channels || [];
if (pdChannels.length > 0 && plan.channels?.allowed?.length) {
const allowedSet = new Set(plan.channels.allowed);
Expand Down Expand Up @@ -4291,6 +4442,63 @@ function extractFromPayload(payload: CheckPayload): ExtractedFields {
};
}

/** One place an action states its region-level geography. */
interface RegionScope {
/** Request path a `conditions` entry names, rooted at the check_governance arguments. */
field: string;
/** ISO 3166-2 codes stated there. Empty means country-level or no geography. */
regions: string[];
}

function stringList(value: unknown): string[] | undefined {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : undefined;
}

/**
* The region-level geography of an intent payload. Top-level geography covers
* the whole action; otherwise each live package is its own scope, because a
* package without `targeting_overlay.geo_regions` delivers country-wide.
*/
function extractRegionScopes(payload: CheckPayload): RegionScope[] {
const topLevel: Array<[string, unknown]> = [
['payload.geo.regions', payload.geo?.regions],
['payload.targeting.geo_regions', payload.targeting?.geo_regions],
['payload.targeting_overlay.geo_regions', payload.targeting_overlay?.geo_regions],
['payload.regions', payload.regions],
];
for (const [field, value] of topLevel) {
const regions = stringList(value);
if (regions) return [{ field, regions }];
}
const packages = (payload.packages ?? [])
.map((pkg, index) => ({ pkg, index }))
.filter(({ pkg }) => pkg && !pkg.canceled);
if (packages.length > 0) {
return packages.map(({ pkg, index }) => ({
field: `payload.packages.${index}.targeting_overlay.geo_regions`,
regions: stringList(pkg.targeting_overlay?.geo_regions) ?? [],
}));
}
return [{ field: 'payload.geo.regions', regions: [] }];
}

/** The region-level geography of each purchase in a proposal being accepted. */
function extractProposalRegionScopes(proposal: GovernanceCanonicalProposal): RegionScope[] {
const purchases = Array.isArray(proposal.commercial_terms.purchases) ? proposal.commercial_terms.purchases : [];
const scopes = purchases.flatMap((purchase, index) => {
if (!purchase || typeof purchase !== 'object' || Array.isArray(purchase)) return [];
const targeting = (purchase as Record<string, unknown>).targeting_overlay;
const geoRegions = targeting && typeof targeting === 'object' && !Array.isArray(targeting)
? (targeting as Record<string, unknown>).geo_regions
: undefined;
return [{
field: `proposal.commercial_terms.purchases.${index}.targeting_overlay.geo_regions`,
regions: stringList(geoRegions) ?? [],
}];
});
return scopes.length > 0 ? scopes : [{ field: 'proposal.commercial_terms.purchases', regions: [] }];
}

function extractBudget(payload: CheckPayload): { amount: number; fieldPath: string } | undefined {
// Try total_budget.amount first, then total_budget as bare number
if (payload.total_budget !== undefined) {
Expand Down
Loading
Loading