= self::MAX_FAILURES) {
return;
}
if (!self::acquire_lock()) {
return;
}
try {
self::run();
} catch (\Throwable $error) {
self::record_failure($error);
} finally {
self::release_lock();
}
}
public static function is_complete(): bool {
return (int) get_option(self::VERSION_OPTION, 0) >= self::DB_VERSION;
}
public static function failures(): int {
return (int) get_option(self::FAILURES_OPTION, 0);
}
/**
* Rebuilds every record and the index from the old options, writes the
* log, then bumps the version. Throws on failure; maybe_run() catches.
*
* @return array The log.
*/
public static function run(): array {
$plan = self::plan(Legacy_Placement::options(), [self::class, 'post_type_of']);
$keep = [];
foreach ($plan['records'] as $record) {
$keep[Placement_Store::option_name($record['namespace'])] = true;
}
foreach (Placement_Store::record_option_names() as $option_name) {
if (!isset($keep[$option_name])) {
delete_option($option_name);
}
}
foreach ($plan['records'] as $record) {
Placement_Store::write_record($record);
}
Placement_Store::write_index(array_column($plan['records'], 'namespace'));
$log = $plan['log'];
$log['ran_at'] = time();
update_option(self::LOG_OPTION, $log, false);
update_option(self::VERSION_OPTION, self::DB_VERSION, true);
delete_option(self::FAILURES_OPTION);
return $log;
}
/**
* The post type of a post, or null when it no longer exists. Reads the
* stored post, so it works before custom post types are registered.
*
* @param int $post_id
*/
public static function post_type_of($post_id): ?string {
$post_type = get_post_type((int) $post_id);
return is_string($post_type) && '' !== $post_type ? $post_type : null;
}
/**
* Takes the migration lock. Acquired only when this request inserted the
* row; a lock older than LOCK_TTL is treated as a crashed run and taken
* over. Reads the row from the database, never from the option cache.
*/
public static function acquire_lock(): bool {
global $wpdb;
$now = time();
if (self::insert_lock($now)) {
return true;
}
$held_since = $wpdb->get_var($wpdb->prepare(
"SELECT option_value FROM `{$wpdb->options}` WHERE option_name = %s LIMIT 1",
self::LOCK_OPTION
));
if (null === $held_since || (int) $held_since > $now - self::LOCK_TTL) {
return false;
}
// Stale: remove exactly the row we read, so a lock another request just took survives.
$wpdb->query($wpdb->prepare(
"DELETE FROM `{$wpdb->options}` WHERE `option_name` = %s AND `option_value` = %s",
self::LOCK_OPTION,
$held_since
));
return self::insert_lock($now);
}
public static function release_lock(): void {
global $wpdb;
$wpdb->query($wpdb->prepare(
"DELETE FROM `{$wpdb->options}` WHERE `option_name` = %s",
self::LOCK_OPTION
));
}
/**
* Shown on admin screens to administrators: after the third failed run,
* or when a completed run logged a changed winner.
*/
public static function admin_notice(): void {
if (!current_user_can('manage_options')) {
return;
}
if (!self::is_complete()) {
if (self::failures() >= self::MAX_FAILURES) {
printf(
'
',
esc_html__('AI BotKit could not update how it stores where your agents show. Your site keeps showing them exactly as before. Please contact AI BotKit support.', 'ai-botkit-for-lead-generation')
);
}
return;
}
$log = get_option(self::LOG_OPTION, []);
$count = is_array($log) && isset($log['mismatches']) && is_array($log['mismatches']) ? count($log['mismatches']) : 0;
if ($count > 0) {
printf(
'',
esc_html(sprintf(
/* translators: %d: number of pages or page groups */
_n(
'AI BotKit updated where your agents show, but %d page may now show a different agent. Please check where your agents show, or contact AI BotKit support.',
'AI BotKit updated where your agents show, but %d pages may now show a different agent. Please check where your agents show, or contact AI BotKit support.',
$count,
'ai-botkit-for-lead-generation'
),
$count
))
);
}
}
private static function insert_lock(int $now): bool {
global $wpdb;
$inserted = $wpdb->query($wpdb->prepare(
"INSERT IGNORE INTO `{$wpdb->options}` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, 'no') /* LOCK */",
self::LOCK_OPTION,
(string) $now
));
return 1 === (int) $inserted;
}
private static function record_failure(\Throwable $error): void {
update_option(self::FAILURES_OPTION, self::failures() + 1, true);
update_option(self::LOG_OPTION, [
'db_version' => self::DB_VERSION,
'failed_at' => time(),
'error' => get_class($error) . ': ' . $error->getMessage(),
], false);
}
/**
* Turns today's three options into placement records. Pure apart from
* $post_type_of, and never calls the network.
*
* - Every agent gets one record. Its Show rules are the pages and post
* types it was enabled on; the sitewide agent gets Entire site and goes
* last, so it wins everywhere, as today.
* - The other agents are ordered so each post type's key-0 agent is above
* the rest of that type's list. Where no order can do that (or key 0 is
* missing), the agent that must lose gets a Hide on exception for that
* post type, or, where that hide would also hide it on a page it wins,
* loses that post type's Show rule instead (today it never won there).
* - Each page then gets Hide on exceptions for every agent that would
* outrank today's key-0 agent, or every agent when key 0 is missing.
* - The other agents are planned as if sitewide were off, so their pages
* are already right if the owner later turns Entire site off.
*
* @param array $legacy From Legacy_Placement::options().
* @param callable $post_type_of fn(int $post_id): ?string, null when the post is gone.
* @return array ['records' => array[] in priority order, 'log' => array]
*/
public static function plan(array $legacy, callable $post_type_of): array {
$log = [
'db_version' => self::DB_VERSION,
'counts' => ['agents' => 0, 'pages' => 0, 'post_types' => 0, 'hides_added' => 0],
'dropped_page_ids' => [],
'dropped_post_types' => [],
'show_rules_dropped' => [],
'mismatches' => [],
'archive_scope_changes' => [],
];
$sitewide = Legacy_Placement::sitewide_namespace(isset($legacy['sitewide']) ? $legacy['sitewide'] : null);
$seen = [];
$pages = [];
$page_types = []; // every existing post an old page entry names, kept or not
$raw_pages = isset($legacy['pages']) ? $legacy['pages'] : null;
if (is_array($raw_pages)) {
foreach ($raw_pages as $key => $list) {
if (null === $list) {
continue; // isset() is false for it, so it never matched.
}
$id = (int) $key;
$post_type = ($id > 0 && (string) $id === (string) $key) ? $post_type_of($id) : null;
$exists = is_string($post_type) && '' !== $post_type;
if ($exists) {
$page_types[$id] = $post_type;
}
if (!$exists || !is_array($list)) {
$log['dropped_page_ids'][] = $key;
continue;
}
$members = self::members($list);
$pages[$id] = ['post_type' => $post_type, 'members' => $members, 'winner' => Legacy_Placement::first_agent($list)];
foreach ($members as $namespace) {
$seen[$namespace] = true;
}
}
}
ksort($pages);
$types = [];
$raw_types = isset($legacy['post_types']) ? $legacy['post_types'] : null;
if (is_array($raw_types)) {
foreach ($raw_types as $key => $list) {
if (empty($list)) {
continue; // today's !empty() skipped it.
}
if (!is_string($key) || !is_array($list)) {
$log['dropped_post_types'][] = (string) $key;
continue;
}
$members = self::members($list);
$types[$key] = ['members' => $members, 'winner' => Legacy_Placement::first_agent($list)];
foreach ($members as $namespace) {
$seen[$namespace] = true;
}
}
}
$agents = array_values(array_diff(array_map('strval', array_keys($seen)), null === $sitewide ? [] : [$sitewide]));
$order = self::order($agents, $types);
if (null !== $sitewide) {
$order[] = $sitewide;
}
$position = array_flip($order);
$records = [];
foreach ($order as $namespace) {
$records[$namespace] = [
'namespace' => $namespace,
'mode' => 'selected',
'show' => ['home' => false, 'post_types' => [], 'items' => []],
'hide' => ['home' => false, 'post_types' => [], 'items' => []],
];
}
foreach ($pages as $id => $page) {
foreach ($page['members'] as $namespace) {
$records[$namespace]['show']['items'][] = $id;
}
}
foreach ($types as $post_type => $type) {
foreach ($type['members'] as $namespace) {
$records[$namespace]['show']['post_types'][] = (string) $post_type;
}
}
// Post types: nobody may outrank today's key-0 agent on its type.
foreach ($types as $post_type => $type) {
$post_type = (string) $post_type;
$winner = $type['winner'];
foreach ($type['members'] as $namespace) {
if ($namespace === $winner || $namespace === $sitewide) {
continue;
}
if (null !== $winner && $position[$namespace] < $position[$winner]) {
continue;
}
if (self::wins_a_page_of_type($namespace, $post_type, $pages)) {
$records[$namespace]['show']['post_types'] = array_values(array_diff($records[$namespace]['show']['post_types'], [$post_type]));
$log['show_rules_dropped'][] = ['namespace' => $namespace, 'post_type' => $post_type];
} else {
$records[$namespace]['hide']['post_types'][] = $post_type;
$log['counts']['hides_added']++;
}
}
}
// Pages: hide whoever outranks today's key-0 agent, one at a time.
foreach ($pages as $id => $page) {
$context = self::single_context($id, $page['post_type']);
for ($guard = count($records); $guard >= 0; $guard--) {
$shown = Placement_Evaluator::winner($context, array_values($records));
if ($shown === $page['winner'] || null === $shown) {
break;
}
$records[$shown]['hide']['items'][] = $id;
$log['counts']['hides_added']++;
}
}
if (null !== $sitewide) {
$records[$sitewide]['mode'] = 'entire_site';
$records[$sitewide]['hide'] = ['home' => false, 'post_types' => [], 'items' => []];
}
$priority = 0;
foreach ($records as $namespace => $record) {
$record['priority'] = ++$priority;
$records[$namespace] = Placement_Store::normalize($record);
}
$records = array_values($records);
$log['counts']['agents'] = count($records);
$log['counts']['pages'] = count($pages);
$log['counts']['post_types'] = count($types);
$log['mismatches'] = self::mismatches($legacy, $records, $page_types, $pages, $types);
$log['archive_scope_changes'] = self::archive_scope_changes($legacy, $records, $types);
return ['records' => $records, 'log' => $log];
}
/**
* Agents of an old list in stored order, as strings, without blanks or repeats.
*
* @return string[]
*/
private static function members(array $list): array {
$members = [];
foreach ($list as $namespace) {
if (is_scalar($namespace) && '' !== (string) $namespace && !in_array((string) $namespace, $members, true)) {
$members[] = (string) $namespace;
}
}
return $members;
}
/**
* A priority order, earliest first, that puts each post type's key-0
* agent after the rest of its list wherever the lists allow it. Ties and
* cycles are broken by the order agents first appear in the old options.
*
* @param string[] $agents In first-seen order.
* @return string[]
*/
private static function order(array $agents, array $types): array {
$before = array_fill_keys($agents, 0); // agent => how many agents must come first
$after = array_fill_keys($agents, []); // agent => agents that must come after it
foreach ($types as $type) {
$winner = $type['winner'];
if (null === $winner || !isset($before[$winner])) {
continue;
}
foreach ($type['members'] as $namespace) {
if ($namespace !== $winner && isset($after[$namespace]) && !in_array($winner, $after[$namespace], true)) {
$after[$namespace][] = $winner;
$before[$winner]++;
}
}
}
$order = [];
$remaining = $agents;
while ($remaining) {
$pick = $remaining[0]; // a cycle: break it at the earliest-seen agent
foreach ($remaining as $namespace) {
if ($before[$namespace] <= 0) {
$pick = $namespace;
break;
}
}
$order[] = $pick;
$remaining = array_values(array_diff($remaining, [$pick]));
foreach ($after[$pick] as $next) {
$before[$next]--;
}
}
return $order;
}
private static function wins_a_page_of_type(string $namespace, string $post_type, array $pages): bool {
foreach ($pages as $page) {
if ($page['post_type'] === $post_type && $page['winner'] === $namespace) {
return true;
}
}
return false;
}
private static function single_context(int $id, string $post_type): array {
return [
'front_page' => false,
'singular' => true,
'object_id' => $id,
'post_type' => $post_type,
'view' => 'singular',
'archive_of' => '',
'legacy_post_id' => $id,
'legacy_post_type' => $post_type,
];
}
/**
* A view whose loop's first post (today's global $post) is a $post_type
* with no page rule. For 'singular', a single of that type with no page rule.
*/
private static function view_context(string $view, string $post_type): array {
$singular = 'singular' === $view;
return [
'front_page' => false,
'singular' => $singular,
'object_id' => 0,
'post_type' => $singular ? $post_type : '',
'view' => $view,
'archive_of' => $singular ? '' : Request_Context::archive_for_view($view, $post_type),
'legacy_post_id' => null,
'legacy_post_type' => $post_type,
];
}
/**
* Compares today's winner with the new one on every referenced page and
* post type: singles, and the post type's archives in ARCHIVE_SCOPE.
* Expected: none.
*/
private static function mismatches(array $legacy, array $records, array $page_types, array $pages, array $types): array {
$contexts = [];
// Deleted posts serve no request, so only existing ones are compared.
foreach ($page_types as $id => $post_type) {
$contexts['page ' . $id] = self::single_context($id, $post_type);
}
// Every post type the old option names, including entries the plan dropped.
$post_types = array_map('strval', array_keys($types));
$raw_types = isset($legacy['post_types']) && is_array($legacy['post_types']) ? $legacy['post_types'] : [];
foreach ($raw_types as $key => $list) {
if (is_string($key) && !empty($list)) {
$post_types[] = $key;
}
}
foreach ($pages as $page) {
$post_types[] = $page['post_type'];
}
foreach (array_unique($post_types) as $post_type) {
$contexts['post type ' . $post_type] = self::view_context('singular', $post_type);
foreach (array_keys(Request_Context::ARCHIVE_SCOPE) as $view) {
if ($post_type === Request_Context::archive_for_view($view, $post_type)) {
$contexts[$view . ' of ' . $post_type] = self::view_context($view, $post_type);
}
}
}
$mismatches = [];
foreach ($contexts as $label => $context) {
$before = Legacy_Placement::winner($context, $legacy);
$after = Placement_Evaluator::winner($context, $records);
if ($before !== $after) {
$mismatches[] = ['context' => (string) $label, 'before' => $before, 'after' => $after];
}
}
return $mismatches;
}
/**
* Views outside ARCHIVE_SCOPE where today's lookup reached a post type's
* agent through the loop's first post and the new placement shows a
* different one. The owner accepted this archive scope (plan KTD10,
* 2026-10-28); logged, but not a migration mismatch.
*/
private static function archive_scope_changes(array $legacy, array $records, array $types): array {
$changes = [];
foreach (array_keys($types) as $post_type) {
foreach (['search', 'author', 'taxonomy'] as $view) {
$context = self::view_context($view, (string) $post_type);
$before = Legacy_Placement::winner($context, $legacy);
$after = Placement_Evaluator::winner($context, $records);
if ($before !== $after) {
$changes[] = ['view' => $view, 'post_type' => (string) $post_type, 'before' => $before, 'after' => $after];
}
}
}
return $changes;
}
}