> */ public function fact_catalog(): array { return null === $this->extensions ? array() : $this->extensions->fact_catalog(); } /** * Evaluate an action for an agent. * * @param int $agent_id Acting agent. * @param ActionDescriptor $action Normalized action. * @param \DateTimeImmutable|null $now Reference time for rate windows. */ public function evaluate( int $agent_id, ActionDescriptor $action, ?\DateTimeImmutable $now = null ): Decision { return $this->evaluate_action( $agent_id, $action, $now )->decision; } /** * Evaluate an action and report why the decision was reached. * * @param int $agent_id Acting agent. * @param ActionDescriptor $action Normalized action. * @param \DateTimeImmutable|null $now Reference time for rate windows. */ public function evaluate_action( int $agent_id, ActionDescriptor $action, ?\DateTimeImmutable $now = null ): Evaluation { return $this->resolve( $agent_id, $action, $now, true ); } /** * Decide a live action whose alerts the caller raises once the decision * is recorded (ADR-17). * * The pipeline decides inside the ledger append, which may run the * decision more than once when a concurrent write wins the race; raising * the alert on each run would report one denial as several. The caller * passes the decision that was recorded to raise_alerts(). * * @param int $agent_id Acting agent. * @param ActionDescriptor $action Normalized action. * @param \DateTimeImmutable|null $now Reference time for rate windows. */ public function decide( int $agent_id, ActionDescriptor $action, ?\DateTimeImmutable $now = null ): Evaluation { return $this->resolve( $agent_id, $action, $now, false ); } /** * Raise the anomaly alerts a decision calls for. * * @param int $agent_id Acting agent. * @param Evaluation $evaluation The decision, as recorded. */ public function raise_alerts( int $agent_id, Evaluation $evaluation ): void { if ( null === $evaluation->limit_rule ) { return; } /** * Fires when an agent exceeds a rate limit (anomaly alert). * * @param int $agent_id Agent id. * @param array $rule The matched rule. */ do_action( 'adaf_anomaly_rate_limit', $agent_id, $evaluation->limit_rule ); } /** * Evaluate without side effects, for answering "what would happen if". * * Identical matching to the live path, with alerts suppressed: the * anomaly hook emails the administrator, so raising it for a hypothetical * action would report an attack that never happened. Nothing here writes - * the rate limiter only reads the ledger - so a simulation costs the agent * no rate budget and leaves no audit trail. * * @param int $agent_id Acting agent. * @param ActionDescriptor $action Normalized action. * @param \DateTimeImmutable|null $now Reference time for rate windows. */ public function explain( int $agent_id, ActionDescriptor $action, ?\DateTimeImmutable $now = null ): Evaluation { return $this->resolve( $agent_id, $action, $now, false ); } /** * A dry-run as if these policies were also stored: what an import or a * template would change, before anything is written. They are merged * into the site's own by priority, the site's first on a tie, which is * where a later create() of the same priority would land. * * @param list $extra Hypothetical policies. * @param int $agent_id Acting agent. * @param ActionDescriptor $action Normalized action. * @param \DateTimeImmutable|null $now Reference time for rate windows. */ public function explain_with( array $extra, int $agent_id, ActionDescriptor $action, ?\DateTimeImmutable $now = null ): Evaluation { return $this->resolve( $agent_id, $action, $now, false, $extra ); } /** * The site's policies for an agent, with any hypothetical ones merged in. * * @param int $agent_id Acting agent. * @param list $extra Hypothetical policies. * @return list */ private function site_policies( int $agent_id, array $extra ): array { $stored = array_values( $this->policies->for_agent( $agent_id ) ); if ( array() === $extra ) { return $stored; } $ranked = array(); foreach ( $stored as $index => $policy ) { $ranked[] = array( $policy->priority, 0, $index, $policy ); } foreach ( array_values( $extra ) as $index => $policy ) { $ranked[] = array( $policy->priority, 1, $index, $policy ); } usort( $ranked, static fn ( array $a, array $b ): int => array( $a[0], $a[1], $a[2] ) <=> array( $b[0], $b[1], $b[2] ) ); return array_map( static fn ( array $row ): Policy => $row[3], $ranked ); } /** * The matching routine behind both paths. * * @param int $agent_id Acting agent. * @param ActionDescriptor $action Normalized action. * @param \DateTimeImmutable|null $now Reference time for rate windows. * @param bool $alert Whether to raise anomaly alerts. * @param list $extra Hypothetical policies (explain_with()). */ private function resolve( int $agent_id, ActionDescriptor $action, ?\DateTimeImmutable $now, bool $alert, array $extra = array() ): Evaluation { // Network rules first, and locked: on a multisite network the Agency // network layer answers this filter, so a site's own rules apply only // to what no network rule decided (ADR-16 §2). Nothing answers it in // the free build or on a single site. $network = apply_filters( 'adaf_network_policies', array() ); $network = is_array( $network ) ? array_values( array_filter( $network, static fn ( $p ): bool => $p instanceof Policy ) ) : array(); $evaluation = $this->first_match( $network, true, $agent_id, $action, $now ) ?? $this->first_match( $this->site_policies( $agent_id, $extra ), false, $agent_id, $action, $now ) ?? $this->extension_default( $agent_id, $action, $now ); if ( null !== $evaluation ) { if ( $alert ) { $this->raise_alerts( $agent_id, $evaluation ); } return $evaluation; } $default = $this->default_decision( $action ); return new Evaluation( $default, Decision::DENY === $default ? Evaluation::REASON_POLICY : null ); } /** * The first extension default rule that decides, or null (AF-25.10). * * Extensions' defaults come after every stored rule and before the * built-in defaults. Each extension's rules are matched as one policy, * so the evaluation's rule index is the rule's position among that * extension's defaults and it names the extension instead of a policy. * * @param int $agent_id Acting agent. * @param ActionDescriptor $action Normalized action. * @param \DateTimeImmutable|null $now Reference time for rate windows. */ private function extension_default( int $agent_id, ActionDescriptor $action, ?\DateTimeImmutable $now ): ?Evaluation { $by_extension = array(); foreach ( null === $this->extensions ? array() : $this->extensions->default_rules() as $default ) { $by_extension[ $default['extension'] ][] = $default['rule']; } $epoch = new \DateTimeImmutable( '@0' ); foreach ( $by_extension as $extension => $rules ) { $evaluation = $this->first_match( array( new Policy( 0, null, $rules, 0, $epoch, $epoch ) ), false, $agent_id, $action, $now, (string) $extension ); if ( null !== $evaluation ) { return $evaluation; } } return null; } /** * The first rule in these policies that decides, or null. * * A network rule may only restrict (decided 2026-10-16): an ALLOW or * LOG_ONLY decision in a network rule is never honored, so the network * sets a floor a site can tighten but never loosen. Its limit, if it * has one, still binds. * * @param list $policies Policies in evaluation order. * @param bool $network Whether these are network rules. * @param int $agent_id Acting agent. * @param ActionDescriptor $action Normalized action. * @param \DateTimeImmutable|null $now Reference time for rate windows. * @param string|null $extension Extension whose defaults these * are; they credit no policy. */ private function first_match( array $policies, bool $network, int $agent_id, ActionDescriptor $action, ?\DateTimeImmutable $now, ?string $extension = null ): ?Evaluation { $catalog = $this->fact_catalog(); $unstored = $network || null !== $extension; foreach ( $policies as $policy ) { foreach ( $policy->rules as $index => $rule ) { $match = isset( $rule['match'] ) && is_array( $rule['match'] ) ? $rule['match'] : array(); if ( ! $this->matches( $match, $action ) ) { continue; } // Three-valued (ADR-18 §4): false skips the rule; unknown // lets its limit bind and fires only a restrictive decision. $holds = ! array_key_exists( 'when', $rule ) ? true : ( is_array( $rule['when'] ) ? Conditions::holds( $rule['when'], $action->facts, $catalog ) : null ); if ( false === $holds ) { continue; } if ( isset( $rule['limit'] ) && is_array( $rule['limit'] ) && null !== $this->limiter ) { if ( ! $this->limiter->check( $agent_id, $rule['limit'], $now ?? new \DateTimeImmutable( 'now' ) ) ) { return new Evaluation( Decision::DENY, Evaluation::REASON_RATE_LIMITED, $unstored ? null : $policy->id, (int) $index, // Tell the agent when a slot frees, so "waiting // clears it" is actionable rather than a riddle. $this->limiter->retry_after( $agent_id, $rule['limit'], $now ?? new \DateTimeImmutable( 'now' ) ), false, $network, $rule, false, false, $extension ); } // Within the limit: a pure limit rule (no decision) // only constrains volume; keep evaluating. if ( ! isset( $rule['decision'] ) && ! isset( $rule['budget'] ) ) { continue; } } $decision = $this->decision_of( $rule ); $lenient = Decision::ALLOW === $decision || Decision::LOG_ONLY === $decision; // The budget is one more conjunct: within it the rule does // not fire, however its conditions came out (ADR-18 §6). if ( array_key_exists( 'budget', $rule ) ) { if ( $lenient ) { continue; } $over = $this->over_budget( $agent_id, $rule['budget'], $action, $catalog, $now ); if ( null === $over ) { continue; } return new Evaluation( $decision, // Unmeasured, the denial is the policy's, not "too large // to ever fit": nobody knows the amount. Decision::DENY === $decision ? ( $over['unresolved'] ? Evaluation::REASON_POLICY : Evaluation::REASON_BUDGET ) : null, $unstored ? null : $policy->id, (int) $index, Decision::DENY === $decision ? $over['retry_after'] : null, Decision::EVALUATE_AI->value === ( $rule['decision'] ?? null ), $network, null, null === $holds || $over['unresolved'], true, $extension ); } if ( $lenient && ( $network || null === $holds ) ) { continue; } return new Evaluation( $decision, Decision::DENY === $decision ? Evaluation::REASON_POLICY : null, $unstored ? null : $policy->id, (int) $index, null, in_array( $rule['decision'] ?? null, array( Decision::EVALUATE_AI->value ), true ), $network, null, null === $holds, false, $extension ); } } return null; } /** * Whether this action takes the agent over a rule's budget: null when it * does not, else the retry hint and whether the answer is a guess. * * A budget that cannot be measured - a value that cannot be known, a * malformed budget, no meter - counts as exceeded: an unknown amount is * treated as large, as an unknown condition is (ADR-18 §4). * * @param int $agent_id Acting agent. * @param mixed $budget The rule's budget. * @param ActionDescriptor $action The action. * @param array> $catalog Facts active extensions declare. * @param \DateTimeImmutable|null $now Reference time. * @return array{retry_after: int|null, unresolved: bool}|null */ private function over_budget( int $agent_id, mixed $budget, ActionDescriptor $action, array $catalog, ?\DateTimeImmutable $now ): ?array { $unknown = array( 'retry_after' => null, 'unresolved' => true, ); $fact = is_array( $budget ) ? ( $budget['fact'] ?? null ) : null; $max = is_array( $budget ) ? ( $budget['max'] ?? null ) : null; $window = is_array( $budget ) ? ( $budget['window'] ?? null ) : null; if ( ! is_string( $fact ) || ! ( is_int( $max ) || is_float( $max ) ) || ! is_int( $window ) || array() !== self::budget_errors( 0, $budget, null, null ) || null === $this->budgets ) { return $unknown; } $value = BudgetMeter::value_of( $action, $fact, $catalog ); if ( null === $value ) { return $unknown; } $measured = $this->budgets->measure( $agent_id, array( 'fact' => $fact, 'max' => $max, 'window' => $window, ), $value, $now ?? new \DateTimeImmutable( 'now' ) ); if ( null === $measured ) { return $unknown; } return $measured['over'] ? array( 'retry_after' => $measured['retry_after'], 'unresolved' => false, ) : null; } /** * Validate a rules list before persisting (used by the policies API). * * Conditions are checked against the fact catalog: a fact no active * extension declares is an error. Network rules pass null, accepting * any well-formed fact, because each site has its own extensions. * * A budget's window may be no longer than the ledger keeps rows, or the * pruned rows would make it undercount (ADR-18 §6). * * @param array $rules Decoded rules list. * @param array>|null $facts The fact catalog, or null for any. * @param int|null $max_window Longest budget window in seconds * (the retention window), or null * when rows are kept forever. * @return list Validation errors; empty when valid. */ public static function validate_rules( array $rules, ?array $facts = array(), ?int $max_window = null ): array { $errors = array(); $catch_all_at = null; foreach ( $rules as $index => $rule ) { if ( ! is_int( $index ) || ! is_array( $rule ) ) { $errors[] = 'Rules must be a list of rule objects.'; continue; } $has_decision = isset( $rule['decision'] ); $has_limit = isset( $rule['limit'] ); $has_budget = array_key_exists( 'budget', $rule ); foreach ( array_keys( $rule ) as $key ) { if ( ! in_array( $key, self::RULE_KEYS, true ) ) { $errors[] = sprintf( 'Rule %d: unknown key "%s". A rule may contain %s.', $index, (string) $key, implode( ', ', self::RULE_KEYS ) ); } } if ( $has_decision && ( ! is_string( $rule['decision'] ) || null === Decision::tryFrom( $rule['decision'] ) ) ) { $errors[] = sprintf( 'Rule %d: unknown decision.', $index ); } if ( ! $has_decision && ! $has_limit && ! $has_budget ) { $errors[] = sprintf( 'Rule %d: needs a decision or a limit.', $index ); } if ( $has_limit ) { $limit = $rule['limit']; $writes = is_array( $limit ) && isset( $limit['writes'] ) ? $limit['writes'] : null; $window = is_array( $limit ) && isset( $limit['window'] ) ? $limit['window'] : null; if ( ! is_int( $writes ) || $writes < 1 || ! is_int( $window ) || $window < 1 ) { $errors[] = sprintf( 'Rule %d: limit needs positive integer writes and window.', $index ); } } $match = null; if ( isset( $rule['match'] ) ) { if ( ! is_array( $rule['match'] ) ) { $errors[] = sprintf( 'Rule %d: match must be an object.', $index ); continue; } $match = $rule['match']; $errors = array_merge( $errors, self::validate_match( $index, $match ) ); } if ( array_key_exists( 'when', $rule ) ) { $errors = array_merge( $errors, Conditions::validate( $index, $rule['when'], $facts ) ); } if ( $has_budget ) { $errors = array_merge( $errors, self::budget_errors( (int) $index, $rule['budget'], $facts, $max_window ) ); // Over budget the decision applies; a permissive one would // let spending past the budget through. if ( ! in_array( $rule['decision'] ?? null, array( Decision::DENY->value, Decision::REQUIRE_APPROVAL->value, Decision::EVALUATE_AI->value ), true ) ) { $errors[] = sprintf( 'Rule %d: a budget needs a DENY, REQUIRE_APPROVAL or EVALUATE_AI decision, which applies once the budget is exceeded.', $index ); } } // Facts mean something only for what they describe, so a rule // on facts says what that is. if ( ( array_key_exists( 'when', $rule ) || $has_budget ) && ( ! is_array( $match ) || ( ! isset( $match['entity_type'] ) && ! isset( $match['ability'] ) ) ) ) { $errors[] = sprintf( 'Rule %d: a rule with conditions or a budget must match an entity_type or an ability.', $index ); } // A rule that constrains nothing matches every action, so nothing // after it can ever be reached. Report the shadowing rather than // let an operator believe a later DENY is protecting them. A rule // with conditions or a budget constrains by them. if ( null === $catch_all_at && ( null === $match || array() === $match ) && $has_decision && ! array_key_exists( 'when', $rule ) && ! $has_budget ) { $catch_all_at = $index; } elseif ( null !== $catch_all_at ) { $errors[] = sprintf( 'Rule %d is unreachable: rule %d matches every action.', $index, $catch_all_at ); } } return $errors; } /** * What is wrong with a budget: `{fact, max, window}`, summing a number * or money fact the catalog declares (any well-formed one without a * catalog) up to a positive max - whole minor units for money - over a * window of whole seconds no longer than the ledger keeps rows. * * @param int $index Rule position, for messages. * @param mixed $budget The rule's budget. * @param array>|null $facts The fact catalog, or null for any. * @param int|null $max_window Longest window in seconds, or null. * @return list */ private static function budget_errors( int $index, mixed $budget, ?array $facts, ?int $max_window ): array { $keys = array( 'fact', 'max', 'window' ); if ( ! is_array( $budget ) || count( $keys ) !== count( $budget ) || array() !== array_diff_key( $budget, array_flip( $keys ) ) ) { return array( sprintf( 'Rule %d: a budget is an object of exactly fact, max and window.', $index ) ); } $errors = array(); $fact = $budget['fact']; $type = null; if ( ! is_string( $fact ) || 1 !== preg_match( Registry::FACT_PATTERN, $fact ) ) { $errors[] = sprintf( 'Rule %d: a budget names a fact as namespace.name.', $index ); } elseif ( null !== $facts ) { $type = $facts[ $fact ]['type'] ?? null; if ( ! in_array( $type, array( 'number', 'money' ), true ) ) { $errors[] = sprintf( 'Rule %d: the budget fact "%s" is not a number or money fact any active extension provides.', $index, $fact ); } } $max = $budget['max']; if ( ! ( is_int( $max ) || ( is_float( $max ) && is_finite( $max ) && 'money' !== $type ) ) || $max <= 0 ) { $errors[] = sprintf( 'Rule %d: a budget max is a positive number, in whole minor units for money.', $index ); } $window = $budget['window']; if ( ! is_int( $window ) || $window < 1 || $window > BudgetMeter::MAX_WINDOW ) { $errors[] = sprintf( 'Rule %1$d: a budget window is a whole number of seconds from 1 to %2$d (366 days).', $index, BudgetMeter::MAX_WINDOW ); } elseif ( null !== $max_window && $window > $max_window ) { $errors[] = sprintf( 'Rule %1$d: the budget window of %2$d seconds is longer than ledger retention (%3$d seconds), so pruned rows would make it undercount. Shorten the window or lengthen retention.', $index, $window, $max_window ); } return $errors; } /** * Validate the values inside a match object. * * Keys alone are not enough. A rule matching action_cat "delte" saves * cleanly and then never fires, which leaves an operator believing a * protection exists when it does not, so closed dimensions are checked * against the values a descriptor can actually carry. * * @param int $index Rule position, for error messages. * @param array $match Match object. * @return list */ private static function validate_match( int $index, array $match ): array { $errors = array(); foreach ( array_keys( $match ) as $key ) { if ( ! in_array( $key, self::MATCH_KEYS, true ) ) { $errors[] = sprintf( 'Rule %d: unknown match dimension "%s".', $index, (string) $key ); } } if ( array_key_exists( 'destructive', $match ) && ! is_bool( $match['destructive'] ) ) { $errors[] = sprintf( 'Rule %d: destructive must be true or false.', $index ); } if ( isset( $match['action_cat'] ) && ! in_array( $match['action_cat'], RuleSchema::ACTION_CATS, true ) ) { $errors[] = sprintf( 'Rule %d: action_cat must be one of %s.', $index, implode( ', ', RuleSchema::ACTION_CATS ) ); } if ( isset( $match['source'] ) && ! in_array( $match['source'], RuleSchema::SOURCES, true ) ) { $errors[] = sprintf( 'Rule %d: source must be one of %s.', $index, implode( ', ', RuleSchema::SOURCES ) ); } if ( isset( $match['entity_id'] ) && ( ! is_int( $match['entity_id'] ) || $match['entity_id'] < 1 ) ) { $errors[] = sprintf( 'Rule %d: entity_id must be a positive integer.', $index ); } if ( isset( $match['ability'] ) ) { $ability = $match['ability']; if ( ! is_string( $ability ) || 1 !== preg_match( RuleSchema::ABILITY_PATTERN, $ability ) ) { $errors[] = sprintf( 'Rule %d: ability must look like namespace/name, optionally ending in *.', $index ); } } // Entity types are open: an ability named acme/update-widget mints the // type "widget". Shape is enforced, membership is not. if ( isset( $match['entity_type'] ) ) { $entity_type = $match['entity_type']; if ( ! is_string( $entity_type ) || 1 !== preg_match( RuleSchema::ENTITY_TYPE_PATTERN, $entity_type ) ) { $errors[] = sprintf( 'Rule %d: entity_type must be lowercase letters, digits and underscores.', $index ); } } return $errors; } /** * AND-match a rule's dimensions against the action. * * @param array $match Rule match object. * @param ActionDescriptor $action Action under evaluation. */ private function matches( array $match, ActionDescriptor $action ): bool { if ( isset( $match['ability'] ) ) { if ( null === $action->ability_name ) { return false; } if ( ! $this->ability_matches( (string) $match['ability'], $action->ability_name ) ) { return false; } } if ( isset( $match['action_cat'] ) && (string) $match['action_cat'] !== $action->action_cat ) { return false; } if ( isset( $match['entity_type'] ) && (string) $match['entity_type'] !== $action->entity_type ) { return false; } if ( isset( $match['entity_id'] ) && (int) $match['entity_id'] !== $action->entity_id ) { return false; } if ( isset( $match['source'] ) && (string) $match['source'] !== $action->source ) { return false; } // Tri-state, and the strict comparison is the point: an action that // declares nothing is neither destructive nor declared safe, so // "destructive": false must not reach it. array_key_exists rather // than isset because false is a value here, not an absence. if ( array_key_exists( 'destructive', $match ) && $match['destructive'] !== $action->destructive ) { return false; } return true; } /** * Exact or trailing-wildcard ability comparison. * * @param string $pattern Rule pattern (e.g. wp/delete_post or wp/*). * @param string $ability Actual ability name. */ private function ability_matches( string $pattern, string $ability ): bool { if ( str_ends_with( $pattern, '*' ) ) { return str_starts_with( $ability, substr( $pattern, 0, -1 ) ); } return $pattern === $ability; } /** * Resolve a rule's decision, failing safe on anything unexpected. * * @param array $rule Matched rule. */ private function decision_of( array $rule ): Decision { $decision = isset( $rule['decision'] ) && is_string( $rule['decision'] ) ? Decision::tryFrom( $rule['decision'] ) : null; if ( null === $decision ) { return Decision::REQUIRE_APPROVAL; } // ADR-4, ADR-15 §1: always a human-review hold, everywhere. The Pro // evaluator reviews such holds out of band; the evaluation's // ai_triage flag is how it knows which. if ( Decision::EVALUATE_AI === $decision ) { return Decision::REQUIRE_APPROVAL; } return $decision; } /** * Defaults when no rule matched (PRD STORY-4.1). The ladder here is * described for operators by RuleSchema::defaults(), which is probed * against this method so the two cannot drift. * * @param ActionDescriptor $action Action under evaluation. */ private function default_decision( ActionDescriptor $action ): Decision { // What the ability says about itself outranks what its category // implies. WooCommerce marks product-update destructive, and an // update to ordinary content would otherwise be allowed outright - // an unattended price rewrite. This also settles the contradictory // declaration (readonly and destructive both true) in favor of the // safe half (AF-17.1). if ( true === $action->destructive ) { return Decision::REQUIRE_APPROVAL; } if ( 'read' === $action->action_cat ) { return Decision::ALLOW; } if ( in_array( $action->entity_type, RuleSchema::HIGH_RISK_ENTITIES, true ) ) { return Decision::REQUIRE_APPROVAL; } switch ( $action->action_cat ) { case 'create': case 'update': return Decision::ALLOW; default: // Deletions and anything uncategorized fail safe. return Decision::REQUIRE_APPROVAL; } } }