|\WP_Error Execution result, or an error. */ public function approve( int $pending_id, int $decided_by, DateTimeImmutable $now ) { if ( null === $this->ledger || null === $this->executor ) { return new \WP_Error( 'adaf_not_configured', __( 'Approval flow is not wired.', 'agentic-daisy-ai-agent-firewall' ) ); } $pending = $this->pending->find( $pending_id ); $entry = null === $pending ? null : $this->ledger->find( $pending->ledger_id ); if ( null !== $pending && 'pending' === $pending->status && null === $entry ) { return new \WP_Error( 'adaf_exec_failed', __( 'The ledger entry for this action is missing.', 'agentic-daisy-ai-agent-firewall' ) ); } // Claimed before anything runs: two approvers at once - two people, // or a person and the AI evaluator - must run the action once. Only // one claim matches a pending row; the other finds it decided. if ( null === $pending || null === $entry || ! $this->pending->claim_for_approval( $pending_id, $now ) ) { return new \WP_Error( 'adaf_not_pending', __( 'This action is not awaiting approval.', 'agentic-daisy-ai-agent-firewall' ), array( 'status' => 409 ) ); } try { return $this->carry_out( $pending, $entry, $decided_by, $now ); } catch ( \Throwable $error ) { // A crash mid-run must not leave the hold stuck mid-approval. $this->pending->release_approval( $pending_id ); throw $error; } } /** * Run a claimed approval: drift-check, execute as the original user, * and settle or release the claim. * * @param PendingAction $pending The claimed hold. * @param LedgerEntry $entry Its ledger row. * @param int $decided_by Approving WP user. * @param DateTimeImmutable $now Decision time. * @return array|\WP_Error */ private function carry_out( PendingAction $pending, LedgerEntry $entry, int $decided_by, DateTimeImmutable $now ) { assert( null !== $this->ledger && null !== $this->executor ); $pending_id = $pending->id; // Pre-flight state-drift verification (ADR-8): a concurrent human // edit always wins over the queued agent intent. if ( null !== $pending->initial_entity_modified_at ) { $current = $this->current_entity_modified( $entry->entity_type, $entry->entity_id ); $initial = $pending->initial_entity_modified_at->format( 'Y-m-d H:i:s' ); if ( null === $current || $current->format( 'Y-m-d H:i:s' ) !== $initial ) { $this->pending->settle_approval( $pending_id, 'drift_conflict', $decided_by, $now ); $this->ledger->update_status( $entry->id, 'denied' ); // Otherwise the row reads as a policy denial - "a built-in // default applied" - when it was approved and then stopped. $this->ledger->update_result( $entry->id, array( 'denial_reason' => 'drift_conflict' ) + self::ai_review( $entry ) ); return new \WP_Error( 'adaf_drift_conflict', __( 'Target entity was modified after action was queued.', 'agentic-daisy-ai-agent-firewall' ), array( 'status' => 409 ) ); } } // Capture before-state immediately ahead of execution, exactly as an // allowed action gets at interception - otherwise an approved change // has nothing to undo from (AF-18.2). Taken now, not at hold time: // the state being replaced is today's, not the state when it queued. $this->snapshots?->capture( new ActionDescriptor( $entry->source, $entry->action_cat, $entry->entity_type, $entry->entity_id, $entry->ability_name, $pending->stored_input ), $entry->id, $now ); // Execute the stored payload as the original linked WP user. $previous_user = get_current_user_id(); wp_set_current_user( $entry->wp_user_id ); try { $result = $this->executor->execute( $entry, $pending ); } finally { wp_set_current_user( $previous_user ); } if ( $result instanceof \WP_Error ) { // Nothing changed, so the snapshot describes nothing; a retry // takes a fresh one. $this->snapshots?->discard( $entry->id ); // Refused for permissions, the action is finished: approving it // again runs as the same user and cannot succeed. Anything else // - a validation error, a failed write - goes back to the queue // so the admin can retry or reject. if ( self::is_permission_refusal( $result ) ) { $this->pending->settle_approval( $pending_id, 'refused', $decided_by, $now ); $this->ledger->update_status( $entry->id, 'refused' ); $this->ledger->update_result( $entry->id, array( 'refused_at' => 'permission', 'code' => $result->get_error_code(), 'on_approval' => true, ) + self::ai_review( $entry ) ); } else { $this->pending->release_approval( $pending_id ); } return $result; } $this->pending->settle_approval( $pending_id, 'approved', $decided_by, $now ); $this->ledger->update_status( $entry->id, 'allowed' ); $this->ledger->update_result( $entry->id, $result + self::ai_review( $entry ) ); return $result; } /** * The AI evaluator's part in a hold, from its ledger row. * * @param LedgerEntry $entry Ledger row. * @return array */ private static function ai_review( LedgerEntry $entry ): array { return array_intersect_key( $entry->result ?? array(), array_flip( self::AI_REVIEW_KEYS ) ); } /** * Return approvals left in flight by a request that died - a fatal * error, a timeout - to the queue, on the hourly sweep. Ten minutes is * far longer than any approval takes. * * @param DateTimeImmutable $now Now. * @return int How many were returned. */ public function recover_stale_approvals( DateTimeImmutable $now ): int { return $this->pending->release_stale_approvals( $now->modify( '-' . self::STALE_APPROVAL . ' seconds' ) ); } /** * Why approving this action cannot run it, or null when it can - the * executor's own rules, for the approval queue to show (AF-18.2). * * @param PendingAction $action Held action. */ public function why_not_executable( PendingAction $action ): ?string { return $this->review( $action )['reason']; } /** * What the approval queue shows about one held action: the ledger row * that names its target (AF-18.6), and why approving cannot run it, or * null when it can (AF-18.2). One ledger read serves both. * * @param PendingAction $action Held action. * @return array{entry: \AgentFirewall\Model\LedgerEntry|null, reason: string|null} */ public function review( PendingAction $action ): array { if ( null === $this->ledger || null === $this->executor ) { return array( 'entry' => null, 'reason' => null, ); } $entry = $this->ledger->find( $action->ledger_id ); if ( null === $entry ) { return array( 'entry' => null, 'reason' => __( 'The ledger entry for this action is missing.', 'agentic-daisy-ai-agent-firewall' ), ); } return array( 'entry' => $entry, 'reason' => $this->executor->why_not( $entry, $action ), ); } /** * Whether a failed execution was core refusing the linked user - an * authentication or authorization failure, which retrying cannot fix. * * @param \WP_Error $error Execution error. */ private static function is_permission_refusal( \WP_Error $error ): bool { $data = $error->get_error_data(); return is_array( $data ) && isset( $data['status'] ) && in_array( (int) $data['status'], array( 401, 403 ), true ); } /** * Reject a pending action. * * @param int $pending_id Pending row id. * @param int $decided_by Rejecting WP user. * @param DateTimeImmutable $now Decision time. * @return bool Whether the record transitioned. */ public function reject( int $pending_id, int $decided_by, DateTimeImmutable $now ): bool { $pending = $this->pending->find( $pending_id ); if ( null === $pending ) { return false; } $transitioned = $this->pending->transition( $pending_id, 'rejected', $decided_by, $now ); if ( $transitioned && null !== $this->ledger ) { $this->ledger->update_status( $pending->ledger_id, 'denied' ); } return $transitioned; } /** * Expire every overdue pending action and sync its ledger row * (fail-closed: ancient intents are never executed, ADR-8 §5). * * @param DateTimeImmutable|null $now Reference time. * @return int Number of actions expired. */ public function expire_overdue( ?DateTimeImmutable $now = null ): int { $now = $now ?? new DateTimeImmutable( 'now' ); $count = 0; foreach ( $this->pending->list_overdue( $now ) as $overdue ) { if ( ! $this->pending->transition( $overdue->id, 'expired', null, $now ) ) { continue; } ++$count; if ( null !== $this->ledger ) { $this->ledger->update_status( $overdue->ledger_id, 'denied' ); } } return $count; } /** * Current modification timestamp of an entity by type/id. * * @param string $entity_type Entity type. * @param int|null $entity_id Entity id. */ private function current_entity_modified( string $entity_type, ?int $entity_id ): ?DateTimeImmutable { if ( null === $entity_id || ! in_array( $entity_type, self::POST_ENTITIES, true ) ) { return null; } $post = get_post( $entity_id ); if ( ! $post instanceof \WP_Post || '' === $post->post_modified_gmt ) { return null; } return new DateTimeImmutable( $post->post_modified_gmt, new DateTimeZone( 'UTC' ) ); } /** * Queue an action for approval. * * @param Agent $agent Acting agent. * @param ActionDescriptor $action Normalized action. * @param int $ledger_id Ledger row already written for this action. * @param DateTimeImmutable $now Reference time. */ public function queue( Agent $agent, ActionDescriptor $action, int $ledger_id, DateTimeImmutable $now ): PendingAction { $ttl = get_option( 'adaf_pending_ttl', self::DEFAULT_TTL ); $ttl = is_numeric( $ttl ) ? (int) $ttl : self::DEFAULT_TTL; return $this->pending->create( array( 'ledger_id' => $ledger_id, 'agent_id' => $agent->id, 'ability_name' => $action->ability_name ?? ( 'rest:' . $action->action_cat . ':' . $action->entity_type ), 'stored_input' => $action->input, 'request' => $action->replay, 'initial_entity_modified_at' => $this->entity_modified_at( $action ), 'expires_at' => $now->modify( sprintf( '+%d seconds', $ttl ) ), ) ); } /** * The target entity's current modification timestamp, when it has one. * * @param ActionDescriptor $action Normalized action. */ public function entity_modified_at( ActionDescriptor $action ): ?DateTimeImmutable { return $this->current_entity_modified( $action->entity_type, $action->entity_id ); } }