diff --git a/plugins/data-machine/docs/core-system/tool-result-finder.md b/plugins/data-machine/docs/core-system/tool-result-finder.md index d98a79b08b..a578093542 100644 --- a/plugins/data-machine/docs/core-system/tool-result-finder.md +++ b/plugins/data-machine/docs/core-system/tool-result-finder.md @@ -24,7 +24,7 @@ Data Packet Array Flow: │ Each entry may have: │ │ • type: 'tool_result' or 'ai_handler_complete' │ │ • metadata.handler_tool: 'twitter', 'wordpress' │ -│ • metadata.tool_result: {success, data, error} │ +│ • metadata.tool_result_envelope: {success, data} │ └─────────────────────────────────────────────────────┘ │ ▼ @@ -73,7 +73,7 @@ $data = [ 'metadata' => [ 'handler_tool' => 'wordpress_update', 'tool_name' => 'wordpress_update', - 'tool_result' => [ + 'tool_result_envelope' => [ 'success' => true, 'data' => [ 'updated_id' => 123, @@ -89,7 +89,7 @@ $data = [ $result = ToolResultFinder::findHandlerResult($data, 'wordpress_update'); if ($result) { - $tool_result = $result['metadata']['tool_result'] ?? []; + $tool_result = $result['metadata']['tool_result_envelope'] ?? []; $success = $tool_result['success'] ?? false; $updated_id = $tool_result['data']['updated_id'] ?? null; @@ -146,7 +146,7 @@ While Publish steps currently don't use ToolResultFinder (they execute tools dir $tool_result = ToolResultFinder::findHandlerResult($data, 'twitter'); if ($tool_result) { - $tweet_url = $tool_result['metadata']['tool_result']['data']['url'] ?? null; + $tweet_url = $tool_result['metadata']['tool_result_envelope']['data']['url'] ?? null; // Use tweet URL for logging or follow-up actions } ``` @@ -162,7 +162,7 @@ $data = [ 'metadata' => [ 'handler_tool' => 'wordpress_update', // Handler slug 'tool_name' => 'wordpress_update', // Tool name - 'tool_result' => [ // Tool execution result + 'tool_result_envelope' => [ // Tool execution result 'success' => true, 'data' => [ 'updated_id' => 123, @@ -195,7 +195,7 @@ Standard tool execution result from AI step: 'metadata' => [ 'handler_tool' => 'twitter', 'tool_name' => 'twitter_publish', - 'tool_result' => [ + 'tool_result_envelope' => [ 'success' => true, 'data' => ['id' => '123', 'url' => 'https://twitter.com/user/status/123'], 'tool_name' => 'twitter_publish' @@ -215,7 +215,7 @@ Legacy format for handler completion: 'type' => 'ai_handler_complete', 'metadata' => [ 'handler_tool' => 'wordpress', - 'tool_result' => [ + 'tool_result_envelope' => [ 'success' => true, 'data' => ['id' => 456, 'url' => 'https://example.com/post-456/'] ] diff --git a/plugins/data-machine/inc/Cli/Commands/AgentsCommand.php b/plugins/data-machine/inc/Cli/Commands/AgentsCommand.php index 4980fbb3d1..9cfbd93f3d 100644 --- a/plugins/data-machine/inc/Cli/Commands/AgentsCommand.php +++ b/plugins/data-machine/inc/Cli/Commands/AgentsCommand.php @@ -986,86 +986,4 @@ public function import_agent( array $args, array $assoc_args ): void { WP_CLI::success( $result['message'] ?? 'Agent bundle imported.' ); } - - /** - * Remove legacy contexts/ directories from agent memory. - * - * Scans all agent directories and deletes contexts/ subdirectories - * and their contents. These files are superseded by the runtime - * AgentModeDirective which provides mode guidance without per-agent - * disk files. - * - * ## OPTIONS - * - * [--dry-run] - * : Show what would be deleted without actually deleting. - * - * ## EXAMPLES - * - * # Preview what would be cleaned up - * wp datamachine agents cleanup-legacy-context-files --dry-run - * - * # Actually remove legacy context files - * wp datamachine agents cleanup-legacy-context-files - * - * @subcommand cleanup-legacy-context-files - */ - public function cleanup_legacy_context_files( array $args, array $assoc_args ): void { - $dry_run = isset( $assoc_args['dry-run'] ); - $upload_dir = wp_upload_dir(); - $agents_dir = trailingslashit( $upload_dir['basedir'] ) . 'datamachine-files/agents'; - if ( ! is_dir( $agents_dir ) ) { - WP_CLI::success( 'No agents directory found — nothing to clean.' ); - return; - } - - $deleted_files = 0; - $deleted_dirs = 0; - $iterator = new \DirectoryIterator( $agents_dir ); - - foreach ( $iterator as $agent_entry ) { - if ( $agent_entry->isDot() || ! $agent_entry->isDir() ) { - continue; - } - - $contexts_dir = $agent_entry->getPathname() . '/contexts'; - if ( ! is_dir( $contexts_dir ) ) { - continue; - } - - // Delete all files in contexts/. - $files = new \DirectoryIterator( $contexts_dir ); - foreach ( $files as $file ) { - if ( $file->isDot() || ! $file->isFile() ) { - continue; - } - - $path = $file->getPathname(); - if ( $dry_run ) { - WP_CLI::log( sprintf( '[dry-run] Would delete: %s', $path ) ); - } else { - unlink( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink - WP_CLI::log( sprintf( 'Deleted: %s', $path ) ); - } - ++$deleted_files; - } - - // Remove the empty contexts/ directory. - if ( $dry_run ) { - WP_CLI::log( sprintf( '[dry-run] Would remove directory: %s', $contexts_dir ) ); - } else { - rmdir( $contexts_dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir - WP_CLI::log( sprintf( 'Removed directory: %s', $contexts_dir ) ); - } - ++$deleted_dirs; - } - - if ( 0 === $deleted_files && 0 === $deleted_dirs ) { - WP_CLI::success( 'No legacy context files found — already clean.' ); - return; - } - - $prefix = $dry_run ? '[dry-run] Would delete' : 'Cleaned up'; - WP_CLI::success( sprintf( '%s %d file(s) and %d directory(ies).', $prefix, $deleted_files, $deleted_dirs ) ); - } } diff --git a/plugins/data-machine/inc/Core/Agents/AgentConfigFactory.php b/plugins/data-machine/inc/Core/Agents/AgentConfigFactory.php index fd9f17a5fc..53625c92e6 100644 --- a/plugins/data-machine/inc/Core/Agents/AgentConfigFactory.php +++ b/plugins/data-machine/inc/Core/Agents/AgentConfigFactory.php @@ -17,40 +17,13 @@ final class AgentConfigFactory { /** * Normalize persisted agent_config into the canonical model shape. * - * Canonical model defaults live at default_provider/default_model. Legacy - * scalar provider/model aliases are accepted as input but not persisted back. + * Canonical model defaults live at default_provider/default_model. * * @param array $config Raw agent config. * @return array */ public static function normalize( array $config ): array { - $config = self::normalize_model_defaults( $config ); - $config = self::normalize_mode_models( $config ); - - return $config; - } - - /** @param array $config */ - private static function normalize_model_defaults( array $config ): array { - $legacy_provider = is_scalar( $config['provider'] ?? null ) ? trim( (string) $config['provider'] ) : ''; - $legacy_model = is_scalar( $config['model'] ?? null ) ? trim( (string) $config['model'] ) : ''; - - if ( '' === trim( (string) ( $config['default_provider'] ?? '' ) ) && '' !== $legacy_provider ) { - $config['default_provider'] = $legacy_provider; - } - - if ( '' === trim( (string) ( $config['default_model'] ?? '' ) ) && '' !== $legacy_model ) { - $config['default_model'] = $legacy_model; - } - - if ( is_scalar( $config['provider'] ?? null ) ) { - unset( $config['provider'] ); - } - if ( is_scalar( $config['model'] ?? null ) ) { - unset( $config['model'] ); - } - - return $config; + return self::normalize_mode_models( $config ); } /** @param array $config */ diff --git a/plugins/data-machine/inc/Core/Database/Agents/Agents.php b/plugins/data-machine/inc/Core/Database/Agents/Agents.php index 7db2b730ce..d946d2d04e 100644 --- a/plugins/data-machine/inc/Core/Database/Agents/Agents.php +++ b/plugins/data-machine/inc/Core/Database/Agents/Agents.php @@ -25,7 +25,6 @@ class Agents extends BaseRepository { const TABLE_NAME = 'datamachine_agents'; private const DEFAULT_INSTANCE_KEY = 'default'; - private const IDENTITY_INDEX_NAME = 'agent_identity_scope_hash'; private const PROVISIONING_LEASE_SECONDS = 300; /** @@ -77,155 +76,6 @@ public static function create_table(): void { dbDelta( $sql ); } - /** - * Migrate legacy slug-only identity storage to the Agents API scope tuple. - * - * Existing rows become their owner's default materialized instance. Full - * instance keys remain lossless in LONGTEXT while a fixed-width SHA-256 - * digest provides portable MySQL/SQLite uniqueness. - */ - public static function ensure_identity_scope_schema(): void { - global $wpdb; - - $table_name = $wpdb->base_prefix . self::TABLE_NAME; - $had_provisioned_at = BaseRepository::column_exists( $table_name, 'provisioned_at', $wpdb ); - self::ensure_identity_column( $wpdb, $table_name, 'instance_key', 'LONGTEXT NULL' ); - self::ensure_identity_column( $wpdb, $table_name, 'instance_key_hash', 'CHAR(64) NULL' ); - self::ensure_identity_column( $wpdb, $table_name, 'provisioning_token', "CHAR(64) NOT NULL DEFAULT ''" ); - self::ensure_identity_column( $wpdb, $table_name, 'provisioning_started_at', 'DATETIME NULL DEFAULT NULL' ); - // SQLite rejects non-constant defaults when ALTER TABLE adds a column. - self::ensure_identity_column( $wpdb, $table_name, 'provisioned_at', 'DATETIME NULL DEFAULT NULL' ); - - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery - self::query_or_throw( - $wpdb, - $wpdb->prepare( 'UPDATE %i SET instance_key = %s WHERE instance_key IS NULL OR instance_key = %s', $table_name, self::DEFAULT_INSTANCE_KEY, '' ), - 'backfill legacy agent instance keys' - ); - if ( ! $had_provisioned_at ) { - self::query_or_throw( - $wpdb, - $wpdb->prepare( 'UPDATE %i SET provisioned_at = %s WHERE provisioned_at IS NULL', $table_name, gmdate( 'Y-m-d H:i:s' ) ), - 'backfill legacy agent provisioning state' - ); - } - - // Hash in PHP so SQLite and MySQL persist byte-for-byte equivalent digests. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT agent_id, instance_key, instance_key_hash FROM %i', $table_name ), ARRAY_A ); - foreach ( $rows as $row ) { - $instance_key = (string) ( $row['instance_key'] ?? self::DEFAULT_INSTANCE_KEY ); - $digest = self::instance_key_hash( $instance_key ); - if ( hash_equals( $digest, (string) ( $row['instance_key_hash'] ?? '' ) ) ) { - continue; - } - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery - if ( false === $wpdb->update( $table_name, array( 'instance_key_hash' => $digest ), array( 'agent_id' => (int) $row['agent_id'] ), array( '%s' ), array( '%d' ) ) ) { - throw new \RuntimeException( 'Failed to backfill agent identity scope digest.' ); - } - } - - if ( ! self::is_sqlite() ) { - $identity_columns = BaseRepository::get_column_meta( $table_name, array( 'instance_key', 'instance_key_hash' ), $wpdb ); - if ( 'NO' !== ( $identity_columns['instance_key']->IS_NULLABLE ?? null ) ) { - self::query_or_throw( $wpdb, $wpdb->prepare( 'ALTER TABLE %i MODIFY instance_key LONGTEXT NOT NULL', $table_name ), 'make agent instance keys non-null' ); - } - if ( 'NO' !== ( $identity_columns['instance_key_hash']->IS_NULLABLE ?? null ) ) { - self::query_or_throw( $wpdb, $wpdb->prepare( 'ALTER TABLE %i MODIFY instance_key_hash CHAR(64) NOT NULL', $table_name ), 'make agent instance digests non-null' ); - } - } - - $indexes = self::get_identity_indexes( $wpdb, $table_name ); - if ( ! self::has_unique_index( $indexes, array( 'agent_slug', 'owner_id', 'instance_key_hash' ) ) ) { - $sql = self::is_sqlite() - ? $wpdb->prepare( 'CREATE UNIQUE INDEX %i ON %i (agent_slug, owner_id, instance_key_hash)', self::IDENTITY_INDEX_NAME, $table_name ) - : $wpdb->prepare( 'ALTER TABLE %i ADD UNIQUE KEY %i (agent_slug, owner_id, instance_key_hash)', $table_name, self::IDENTITY_INDEX_NAME ); - self::query_or_throw( $wpdb, $sql, 'create agent identity scope index' ); - } - - $indexes = self::get_identity_indexes( $wpdb, $table_name ); - if ( ! self::has_unique_index( $indexes, array( 'agent_slug', 'owner_id', 'instance_key_hash' ) ) ) { - throw new \RuntimeException( 'Agent identity scope index verification failed.' ); - } - - // Only remove obsolete uniqueness after the digest-backed replacement is verified. - foreach ( $indexes as $name => $index ) { - if ( ! $index['unique'] || ! in_array( $index['columns'], array( array( 'agent_slug' ), array( 'agent_slug', 'owner_id', 'instance_key' ) ), true ) ) { - continue; - } - BaseRepository::drop_index( $table_name, $name, $wpdb ); - } - - $indexes = self::get_identity_indexes( $wpdb, $table_name ); - if ( ! self::has_unique_index( $indexes, array( 'agent_slug', 'owner_id', 'instance_key_hash' ) ) || self::has_unique_index( $indexes, array( 'agent_slug' ) ) ) { - throw new \RuntimeException( 'Agent identity schema migration did not reach a valid final state.' ); - } - } - - private static function ensure_identity_column( \wpdb $wpdb, string $table_name, string $column, string $definition ): void { - if ( BaseRepository::column_exists( $table_name, $column, $wpdb ) ) { - return; - } - // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Column and definition are private schema constants, while the table identifier is prepared. - self::query_or_throw( $wpdb, $wpdb->prepare( "ALTER TABLE %i ADD COLUMN {$column} {$definition}", $table_name ), "add agent identity column {$column}" ); // @phpstan-ignore argument.type (column and definition are private schema constants) - } - - private static function query_or_throw( \wpdb $wpdb, string $sql, string $operation ): void { - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.NotPrepared - if ( false === $wpdb->query( $sql ) ) { - throw new \RuntimeException( sprintf( 'Failed to %s: %s', esc_html( $operation ), esc_html( (string) $wpdb->last_error ) ) ); - } - } - - /** @return array */ - private static function get_identity_indexes( \wpdb $wpdb, string $table_name ): array { - $indexes = array(); - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $index_rows = $wpdb->get_results( $wpdb->prepare( 'SHOW INDEX FROM %i', $table_name ), ARRAY_A ); - foreach ( $index_rows as $index_row ) { - $name = (string) ( $index_row['Key_name'] ?? '' ); - if ( '' === $name ) { - continue; - } - $indexes[ $name ]['unique'] = 0 === (int) ( $index_row['Non_unique'] ?? 1 ); - $indexes[ $name ]['columns'][ (int) ( $index_row['Seq_in_index'] ?? 0 ) ] = (string) ( $index_row['Column_name'] ?? '' ); - } - foreach ( $indexes as &$index ) { - ksort( $index['columns'] ); - $index['columns'] = array_values( $index['columns'] ); - } - return $indexes; - } - - private static function has_unique_index( array $indexes, array $columns ): bool { - foreach ( $indexes as $index ) { - if ( $index['unique'] && $columns === $index['columns'] ) { - return true; - } - } - return false; - } - - /** - * Ensure site_scope column exists on existing installs. - * - * @return void - */ - public static function ensure_site_scope_column(): void { - global $wpdb; - - $table_name = $wpdb->base_prefix . self::TABLE_NAME; - - if ( ! BaseRepository::column_exists( $table_name, 'site_scope', $wpdb ) ) { - // `AFTER ` is MySQL-only; SQLite (Studio) rejects it. Column position - // is cosmetic — both engines accept the bare ADD COLUMN form. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD COLUMN site_scope BIGINT(20) UNSIGNED NULL DEFAULT NULL', $table_name ) ); - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD KEY site_scope (site_scope)', $table_name ) ); - } - } - /** * Get agent by agent ID. * diff --git a/plugins/data-machine/inc/Core/Database/ProcessedItems/ProcessedItemDeferrals.php b/plugins/data-machine/inc/Core/Database/ProcessedItems/ProcessedItemDeferrals.php index dfc3f7da54..d9443e6a1e 100644 --- a/plugins/data-machine/inc/Core/Database/ProcessedItems/ProcessedItemDeferrals.php +++ b/plugins/data-machine/inc/Core/Database/ProcessedItems/ProcessedItemDeferrals.php @@ -182,107 +182,4 @@ public function find_stale_deferrals( int $max_age_hours, int $limit = 100, int 'next_after_id' => $has_more ? (int) ( $last_item['id'] ?? 0 ) : 0, ); } - - /** Ensure durable deferral columns and the operational index exist. */ - public static function ensure_deferral_schema( string $table_name ): void { - global $wpdb; - foreach ( self::deferral_column_definitions() as $column => $definition ) { - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- Schema inspection. - $actual = $wpdb->get_row( $wpdb->prepare( 'SHOW FULL COLUMNS FROM %i LIKE %s', $table_name, $column ), ARRAY_A ); - if ( self::valid_deferral_column( $column, $actual ) ) { - continue; - } - $operation = is_array( $actual ) ? 'MODIFY COLUMN' : 'ADD COLUMN'; - // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Column names and definitions come from the fixed map above. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.NotPrepared -- Fixed migration definition and prepared table identifier. - $wpdb->query( $wpdb->prepare( "ALTER TABLE %i {$operation} `{$column}` {$definition}", $table_name ) ); - // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared - } - - if ( ! self::validate_deferral_index( $table_name ) ) { - $operation = empty( self::deferral_index_metadata( $table_name ) ) - ? 'ADD KEY `status_deferred_at` (`status`, `deferred_at`)' - : 'DROP INDEX `status_deferred_at`, ADD KEY `status_deferred_at` (`status`, `deferred_at`)'; - // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Operation is selected from the two fixed definitions above. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.NotPrepared -- Required operational index repair. - $wpdb->query( $wpdb->prepare( "ALTER TABLE %i {$operation}", $table_name ) ); - // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared - } - } - - /** Verify the complete durable-deferral schema before migration completion. */ - public static function validate_deferral_schema( string $table_name ): bool { - global $wpdb; - foreach ( self::deferral_column_definitions() as $column => $definition ) { - unset( $definition ); - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- Schema validation. - $actual = $wpdb->get_row( $wpdb->prepare( 'SHOW FULL COLUMNS FROM %i LIKE %s', $table_name, $column ), ARRAY_A ); - if ( ! self::valid_deferral_column( $column, $actual ) ) { - return false; - } - } - return self::validate_deferral_index( $table_name ); - } - - /** Canonical SQL definitions for durable deferral columns. */ - private static function deferral_column_definitions(): array { - return array( - 'deferral_count' => 'INT UNSIGNED NOT NULL DEFAULT 0', - 'last_deferral_job_id' => 'BIGINT(20) UNSIGNED NULL', - 'deferred_at' => 'DATETIME NULL', - 'last_seen_at' => 'DATETIME NULL', - ); - } - - /** Validate one column's semantic type, nullability, and default. */ - private static function valid_deferral_column( string $column, mixed $actual ): bool { - if ( ! is_array( $actual ) || ( $actual['Field'] ?? null ) !== $column ) { - return false; - } - $type = strtolower( (string) ( $actual['Type'] ?? '' ) ); - $rules = array( - 'deferral_count' => array( '/^int(?:\(\d+\))? unsigned$/', 'NO', '0' ), - 'last_deferral_job_id' => array( '/^bigint(?:\(\d+\))? unsigned$/', 'YES', null ), - 'deferred_at' => array( '/^datetime$/', 'YES', null ), - 'last_seen_at' => array( '/^datetime$/', 'YES', null ), - ); - if ( ! isset( $rules[ $column ] ) ) { - return false; - } - [ $type_pattern, $nullable, $default ] = $rules[ $column ]; - $actual_default = $actual['Default'] ?? null; - $default_matches = null === $default - ? null === $actual_default - : (string) $actual_default === $default; - return 1 === preg_match( $type_pattern, $type ) - && ( $actual['Null'] ?? null ) === $nullable - && $default_matches; - } - - /** Verify the exact non-unique, unprefixed BTREE operational index. */ - private static function validate_deferral_index( string $table_name ): bool { - $rows = self::deferral_index_metadata( $table_name ); - if ( 2 !== count( (array) $rows ) || array( 'status', 'deferred_at' ) !== array_column( $rows, 'Column_name' ) ) { - return false; - } - foreach ( $rows as $offset => $row ) { - if ( 1 !== (int) ( $row['Non_unique'] ?? 0 ) - || (int) ( $row['Seq_in_index'] ?? 0 ) !== $offset + 1 - || 'BTREE' !== strtoupper( (string) ( $row['Index_type'] ?? '' ) ) - || null !== ( $row['Sub_part'] ?? null ) ) { - return false; - } - } - return true; - } - - /** Read operational index metadata in sequence order. */ - private static function deferral_index_metadata( string $table_name ): array { - global $wpdb; - // SHOW INDEX has no ORDER BY clause; normalize its rows after retrieval. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- Schema validation. - $rows = (array) $wpdb->get_results( $wpdb->prepare( 'SHOW INDEX FROM %i WHERE Key_name = %s', $table_name, 'status_deferred_at' ), ARRAY_A ); - usort( $rows, static fn( array $left, array $right ): int => (int) $left['Seq_in_index'] <=> (int) $right['Seq_in_index'] ); - return $rows; - } } diff --git a/plugins/data-machine/inc/Core/FilesRepository/DirectoryManager.php b/plugins/data-machine/inc/Core/FilesRepository/DirectoryManager.php index 00213af0e4..4aa964f5d3 100644 --- a/plugins/data-machine/inc/Core/FilesRepository/DirectoryManager.php +++ b/plugins/data-machine/inc/Core/FilesRepository/DirectoryManager.php @@ -189,29 +189,6 @@ public function get_pipeline_context_directory( int|string $pipeline_id): string return "{$pipeline_dir}/context"; } - /** - * Get agent directory path. - * - * When a user_id is provided, returns the per-agent subdirectory - * ({base}/agent/{user_id}). When user_id is 0, returns the legacy - * shared directory ({base}/agent) for backward compatibility. - * - * @since 0.37.0 Added $user_id parameter for multi-agent partitioning. - * - * @param int $user_id WordPress user ID. 0 = legacy shared directory. - * @return string Full path to agent directory. - */ - public function get_agent_directory( int $user_id = 0 ): string { - $upload_dir = wp_upload_dir(); - $base = trailingslashit( $upload_dir['basedir'] ) . self::REPOSITORY_DIR; - - if ( 0 < $user_id ) { - return "{$base}/agent/{$user_id}"; - } - - return "{$base}/agent"; - } - /** * Get shared site directory path. * @@ -518,40 +495,4 @@ public function ensure_directory_exists( string $directory ): bool { } return true; } - - /** - * Ensure the agent directory and its parents are group-writable. - * - * Agent files need to be writable by both the web server user (www-data) - * and the coding agent user (e.g. opencode). This method creates the - * agent directory if needed and sets 0775 permissions on the agent - * directory and its parent (datamachine-files/). - * - * @since 0.32.0 - * @since 0.37.0 Added $user_id parameter for multi-agent partitioning. - * - * @param int $user_id WordPress user ID. 0 = legacy shared directory. - * @return bool True if directory exists and permissions were set. - */ - public function ensure_agent_directory_writable( int $user_id = 0 ): bool { - $agent_dir = $this->get_agent_directory( $user_id ); - - if ( ! $this->ensure_directory_exists( $agent_dir ) ) { - return false; - } - - $perms = FilesystemHelper::AGENT_DIR_PERMISSIONS; - - // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod - chmod( $agent_dir, $perms ); - - // Also set the parent datamachine-files/ directory. - $parent = dirname( $agent_dir ); - if ( is_dir( $parent ) ) { - // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod - chmod( $parent, $perms ); - } - - return true; - } } diff --git a/plugins/data-machine/inc/Engine/AI/ComposableFileGenerator.php b/plugins/data-machine/inc/Engine/AI/ComposableFileGenerator.php index 16f8f21ae5..3cfb2c40c9 100644 --- a/plugins/data-machine/inc/Engine/AI/ComposableFileGenerator.php +++ b/plugins/data-machine/inc/Engine/AI/ComposableFileGenerator.php @@ -24,14 +24,11 @@ class ComposableFileGenerator { * Regenerate a single composable file from its registered sections. * * Generates content via SectionRegistry. For files with a `convention_path` - * the file is written ONLY at `ABSPATH + convention_path` (since v0.67.0); - * any pre-v0.67.0 copy in the layer directory is removed so consumers don't - * read a frozen snapshot. Files without a `convention_path` write to their - * layer directory as before. + * the file is written ONLY at `ABSPATH + convention_path`. Files without a + * `convention_path` write to their layer directory. * * @since 0.66.0 * @since 0.67.0 Convention-path files write only to the convention path. - * @since x.y.z Removes pre-v0.67.0 layer-dir copies during regenerate. * * @param string $filename Composable filename (e.g. 'AGENTS.md'). * @param array $context { @@ -41,7 +38,7 @@ class ComposableFileGenerator { * @type string $agent_slug Agent slug. * @type int $agent_id Agent ID. * } - * @return array{success:true,message:string,filepath:string,stale_removed:string}|array{success:false,message:string,error_code?:string,blocker?:array} + * @return array{success:true,message:string,filepath:string}|array{success:false,message:string,error_code?:string,blocker?:array} */ public static function regenerate( string $filename, array $context = array() ): array { $meta = MemoryFileRegistry::get( $filename ); @@ -128,19 +125,6 @@ public static function regenerate( string $filename, array $context = array() ): ); } - $stale_layer_path = ''; - if ( ! empty( $meta['convention_path'] ) ) { - // Pre-v0.67.0 versions wrote to the layer dir; resolving that - // directory must not make best-effort cleanup fail composition. - $layer_dir = ScaffoldAbilities::resolve_directory( $meta['layer'], $context ); - if ( $layer_dir ) { - $candidate = trailingslashit( $layer_dir ) . $filename; - if ( $candidate !== $filepath && file_exists( $candidate ) ) { - $stale_layer_path = $candidate; - } - } - } - $write_result = self::write_file( $filepath, $directory, $content ); if ( ! $write_result['success'] ) { @@ -151,15 +135,6 @@ public static function regenerate( string $filename, array $context = array() ): ); } - // Best-effort cleanup only targets the dead layer-directory copy. - $stale_removed = ''; - if ( '' !== $stale_layer_path ) { - $fs = FilesystemHelper::get(); - if ( $fs && $fs->delete( $stale_layer_path ) ) { - $stale_removed = $stale_layer_path; - } - } - /** * Fires after a composable file has been regenerated. * @@ -172,16 +147,10 @@ public static function regenerate( string $filename, array $context = array() ): */ do_action( 'datamachine_composable_regenerated', $filename, $filepath, $context ); - $message = sprintf( 'Regenerated %s at %s (%d sections).', $filename, $filepath, count( SectionRegistry::get_sections( $filename ) ) ); - if ( '' !== $stale_removed ) { - $message .= sprintf( ' Removed stale layer-dir copy at %s.', $stale_removed ); - } - return array( - 'success' => true, - 'message' => $message, - 'filepath' => $filepath, - 'stale_removed' => $stale_removed, + 'success' => true, + 'message' => sprintf( 'Regenerated %s at %s (%d sections).', $filename, $filepath, count( SectionRegistry::get_sections( $filename ) ) ), + 'filepath' => $filepath, ); } finally { $lock->release(); diff --git a/plugins/data-machine/inc/Engine/AI/Tools/ToolExecutor.php b/plugins/data-machine/inc/Engine/AI/Tools/ToolExecutor.php index 0e87bfe3d6..10090153de 100644 --- a/plugins/data-machine/inc/Engine/AI/Tools/ToolExecutor.php +++ b/plugins/data-machine/inc/Engine/AI/Tools/ToolExecutor.php @@ -420,15 +420,6 @@ public static function finishPendingPacketExecutionForRequest( string $tool_name return self::finishPendingPacketExecution( $tool_name, $disposition_id, $job_id, $state, $token, $request_id ); } - /** Backward-compatible success recorder for callers that already own a reservation. */ - public static function recordPacketExecutionSuccess( string $tool_name, string $disposition_id, array $payload ): bool { - $reservation = self::beginPacketExecution( $tool_name, $disposition_id, $payload ); - if ( empty( $reservation['acquired'] ) ) { - return ! empty( $reservation['result']['success'] ); - } - return self::finishPacketExecution( $tool_name, $disposition_id, $payload, (string) $reservation['token'], 'succeeded' ); - } - private static function duplicatePacketExecutionResult( string $tool_name, string $disposition_id ): array { return array( 'success' => true, diff --git a/plugins/data-machine/inc/Engine/AI/Tools/ToolResultFinder.php b/plugins/data-machine/inc/Engine/AI/Tools/ToolResultFinder.php index ff2c33fec0..2005422f9b 100644 --- a/plugins/data-machine/inc/Engine/AI/Tools/ToolResultFinder.php +++ b/plugins/data-machine/inc/Engine/AI/Tools/ToolResultFinder.php @@ -20,9 +20,7 @@ class ToolResultFinder { /** * Project the stable tool-result data payload from a result packet. * - * New packets carry both the full execution envelope and projected data. - * Legacy packets overloaded metadata.tool_result, so compatibility remains - * isolated here instead of leaking into every consumer. + * Packets carry both the full execution envelope and projected data. * * @param array $entry Tool result packet. * @return array @@ -82,10 +80,6 @@ public static function projectResultEnvelope( array $entry ): array { return $metadata['tool_result_envelope']; } - if ( is_array( $metadata['tool_result'] ?? null ) ) { - return $metadata['tool_result']; - } - if ( is_array( $metadata['tool_result_data'] ?? null ) ) { return array( 'success' => (bool) ( $metadata['tool_success'] ?? false ), diff --git a/plugins/data-machine/inc/Engine/Agents/PersistedAgentGraphProjector.php b/plugins/data-machine/inc/Engine/Agents/PersistedAgentGraphProjector.php index 75f85cb6e2..b18c770ee8 100644 --- a/plugins/data-machine/inc/Engine/Agents/PersistedAgentGraphProjector.php +++ b/plugins/data-machine/inc/Engine/Agents/PersistedAgentGraphProjector.php @@ -68,7 +68,7 @@ public static function project( string $slug, ?Agents $repository = null ): arra 'label' => (string) ( $row['agent_name'] ?? $slug ), 'description' => (string) ( $config['description'] ?? '' ), 'subagents' => $edges, - 'model' => (string) ( $config['model'] ?? $config['default_model'] ?? '' ), + 'model' => (string) ( $config['default_model'] ?? '' ), 'sources' => array( 'instructions' => $paths, 'skills' => $artifact_paths['skills'], diff --git a/plugins/data-machine/tests/Unit/Abilities/AgentAbilitiesTest.php b/plugins/data-machine/tests/Unit/Abilities/AgentAbilitiesTest.php index 57de43d40d..e6d2c11c94 100644 --- a/plugins/data-machine/tests/Unit/Abilities/AgentAbilitiesTest.php +++ b/plugins/data-machine/tests/Unit/Abilities/AgentAbilitiesTest.php @@ -287,14 +287,14 @@ public function test_updateAgent_config(): void { array( 'agent_slug' => 'config-bot', 'owner_id' => $this->admin_id, - 'config' => array( 'provider' => 'anthropic' ), + 'config' => array( 'default_provider' => 'anthropic' ), ) ); $result = AgentAbilities::updateAgent( array( 'agent_id' => $created['agent_id'], - 'agent_config' => array( 'provider' => 'openai', 'model' => 'gpt-4o' ), + 'agent_config' => array( 'default_provider' => 'openai', 'default_model' => 'gpt-4o' ), ) ); @@ -316,7 +316,7 @@ public function test_updateAgent_multiple_fields(): void { array( 'agent_id' => $created['agent_id'], 'agent_name' => 'After', - 'agent_config' => array( 'provider' => 'anthropic' ), + 'agent_config' => array( 'default_provider' => 'anthropic' ), ) ); diff --git a/plugins/data-machine/tests/Unit/Abilities/MultiAgentScopingTest.php b/plugins/data-machine/tests/Unit/Abilities/MultiAgentScopingTest.php index 3e68a77715..bc9abc3d16 100644 --- a/plugins/data-machine/tests/Unit/Abilities/MultiAgentScopingTest.php +++ b/plugins/data-machine/tests/Unit/Abilities/MultiAgentScopingTest.php @@ -507,27 +507,12 @@ public function test_job_listing_filtered_by_user_id(): void { public function test_agent_directories_isolated(): void { $dm = new DirectoryManager(); - $shared_dir = $dm->get_agent_directory( 0 ); $agent_a_dir = $dm->get_agent_identity_directory_for_user( $this->agent_a_id ); $agent_b_dir = $dm->get_agent_identity_directory_for_user( $this->agent_b_id ); - // All three directories should be different paths. - $this->assertNotEquals( $shared_dir, $agent_a_dir ); - $this->assertNotEquals( $shared_dir, $agent_b_dir ); $this->assertNotEquals( $agent_a_dir, $agent_b_dir ); } - /** - * Test shared agent directory is the legacy path (agent/). - */ - public function test_shared_agent_uses_legacy_path(): void { - $dm = new DirectoryManager(); - $shared_dir = $dm->get_agent_directory( 0 ); - - // Should end with /agent (no user suffix). - $this->assertStringEndsWith( '/agent', $shared_dir ); - } - /** * Test user-scoped agent directory uses agent slug path. */ diff --git a/plugins/data-machine/tests/Unit/Core/Database/ProcessedItemsTest.php b/plugins/data-machine/tests/Unit/Core/Database/ProcessedItemsTest.php index ef2761afdf..5a27b1da39 100644 --- a/plugins/data-machine/tests/Unit/Core/Database/ProcessedItemsTest.php +++ b/plugins/data-machine/tests/Unit/Core/Database/ProcessedItemsTest.php @@ -514,43 +514,9 @@ public function test_deferred_status_timestamp_index_exists(): void { $this->assertNotEmpty( $rows, 'Deferred identity reporting requires its bounded status/timestamp index.' ); } - public function test_deferral_schema_repairs_malformed_same_name_column_and_index(): void { - global $wpdb; - $table = $this->db->get_table_name(); - try { - $this->db->add_processed_item( $this->flow_step_id, $this->source_type, 'schema-repair-row', 901 ); - $rows_before = $this->schema_repair_rows(); - $wpdb->query( "ALTER TABLE {$table} MODIFY COLUMN `last_seen_at` VARCHAR(30) NOT NULL DEFAULT 'bad'" ); - $wpdb->query( "ALTER TABLE {$table} DROP INDEX `status_deferred_at`, ADD KEY `status_deferred_at` (`deferred_at`, `status`)" ); - $this->assertFalse( ProcessedItems::validate_deferral_schema( $table ) ); - - ProcessedItems::ensure_deferral_schema( $table ); - $this->assertTrue( ProcessedItems::validate_deferral_schema( $table ) ); - $this->assert_deferral_column_metadata(); - $this->assert_deferral_index_metadata(); - $this->assertSame( $rows_before, $this->schema_repair_rows() ); - } finally { - ProcessedItems::ensure_deferral_schema( $table ); - } - } - - public function test_deferral_schema_repairs_unique_and_prefix_indexes(): void { - global $wpdb; - $table = $this->db->get_table_name(); - try { - $this->db->add_processed_item( $this->flow_step_id, $this->source_type, 'index-repair-row', 902 ); - $rows_before = $this->schema_repair_rows(); - $this->assert_index_repair( - "ALTER TABLE {$table} DROP INDEX `status_deferred_at`, ADD UNIQUE KEY `status_deferred_at` (`status`, `deferred_at`)", - $rows_before - ); - $this->assert_index_repair( - "ALTER TABLE {$table} DROP INDEX `status_deferred_at`, ADD KEY `status_deferred_at` (`status`(8), `deferred_at`)", - $rows_before - ); - } finally { - ProcessedItems::ensure_deferral_schema( $table ); - } + public function test_installer_creates_canonical_deferral_schema(): void { + $this->assert_deferral_column_metadata(); + $this->assert_deferral_index_metadata(); } // ----------------------------------------------------------------- @@ -640,28 +606,4 @@ private function assert_deferral_index_metadata(): void { $this->assertSame( array( null, null ), array_column( $rows, 'Sub_part' ) ); $this->assertSame( array( 'BTREE', 'BTREE' ), array_map( 'strtoupper', array_column( $rows, 'Index_type' ) ) ); } - - /** Malform, repair, and verify one operational index shape. */ - private function assert_index_repair( string $alter_query, array $rows_before ): void { - global $wpdb; - $wpdb->query( $alter_query ); - $table = $this->db->get_table_name(); - $this->assertFalse( ProcessedItems::validate_deferral_schema( $table ) ); - ProcessedItems::ensure_deferral_schema( $table ); - $this->assertTrue( ProcessedItems::validate_deferral_schema( $table ) ); - $this->assert_deferral_index_metadata(); - $this->assertSame( $rows_before, $this->schema_repair_rows() ); - } - - /** Snapshot row identity and lifecycle data unaffected by schema repair. */ - private function schema_repair_rows(): array { - global $wpdb; - return $wpdb->get_results( - $wpdb->prepare( - 'SELECT id, flow_step_id, source_type, item_identifier, job_id, status FROM %i ORDER BY id ASC', - $this->db->get_table_name() - ), - ARRAY_A - ); - } } diff --git a/plugins/data-machine/tests/Unit/Core/Identity/AgentIdentityStoreAdapterTest.php b/plugins/data-machine/tests/Unit/Core/Identity/AgentIdentityStoreAdapterTest.php index d9b3e17578..d9bb37e421 100644 --- a/plugins/data-machine/tests/Unit/Core/Identity/AgentIdentityStoreAdapterTest.php +++ b/plugins/data-machine/tests/Unit/Core/Identity/AgentIdentityStoreAdapterTest.php @@ -210,69 +210,6 @@ public function test_duplicate_key_loser_reconciles_pending_winner(): void { $this->assertCount( 1, array_filter( $this->repository->get_all(), static fn( array $row ): bool => 'concurrent-agent' === $row['agent_slug'] ) ); } - public function test_schema_migration_preserves_legacy_rows_and_replaces_slug_unique_key(): void { - global $wpdb; - $table = $wpdb->base_prefix . Agents::TABLE_NAME; - - // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i DROP INDEX %i', $table, 'agent_identity_scope_hash' ) ); - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i DROP COLUMN instance_key', $table ) ); - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i DROP COLUMN instance_key_hash', $table ) ); - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i DROP COLUMN provisioning_token', $table ) ); - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i DROP COLUMN provisioning_started_at', $table ) ); - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i DROP COLUMN provisioned_at', $table ) ); - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD UNIQUE KEY %i (agent_slug)', $table, 'agent_slug' ) ); - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD KEY %i (owner_id)', $table, 'agent_identity_scope_hash' ) ); - $wpdb->insert( - $table, - array( 'agent_slug' => 'pre-migration-agent', 'agent_name' => 'Pre Migration Agent', 'owner_id' => $this->owner_a, 'agent_config' => '{}' ), - array( '%s', '%s', '%d', '%s' ) - ); - $agent_id = (int) $wpdb->insert_id; - ( new AgentAccess() )->bootstrap_owner_access( $agent_id, $this->owner_a ); - - try { - Agents::ensure_identity_scope_schema(); - $this->fail( 'A conflicting replacement index must fail the migration.' ); - } catch ( \RuntimeException $exception ) { - $this->assertStringContainsString( 'create agent identity scope index', $exception->getMessage() ); - } - $failed_indexes = $wpdb->get_results( $wpdb->prepare( 'SHOW INDEX FROM %i', $table ), ARRAY_A ); - $this->assertNotEmpty( array_filter( $failed_indexes, static fn( array $index ): bool => 'agent_slug' === $index['Key_name'] && 0 === (int) $index['Non_unique'] ) ); - - $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i DROP INDEX %i', $table, 'agent_identity_scope_hash' ) ); - Agents::ensure_identity_scope_schema(); - Agents::ensure_identity_scope_schema(); - $row = ( new Agents() )->get_agent( $agent_id ); - $indexes = $wpdb->get_results( $wpdb->prepare( 'SHOW INDEX FROM %i', $table ), ARRAY_A ); - // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - - $this->assertSame( 'default', $row['instance_key'] ); - $this->assertSame( hash( 'sha256', 'default' ), $row['instance_key_hash'] ); - $this->assertNotEmpty( $row['provisioned_at'] ); - $this->assertTrue( ( new AgentAccess() )->user_can_access( $agent_id, $this->owner_a, 'admin' ) ); - $this->assertNotEmpty( array_filter( $indexes, static fn( array $index ): bool => 'agent_identity_scope_hash' === $index['Key_name'] ) ); - $this->assertEmpty( array_filter( $indexes, static fn( array $index ): bool => 'agent_slug' === $index['Key_name'] && 0 === (int) $index['Non_unique'] ) ); - } - - public function test_schema_reconciliation_is_idempotent_with_existing_identity_index(): void { - global $wpdb; - $table = $wpdb->base_prefix . Agents::TABLE_NAME; - - Agents::ensure_identity_scope_schema(); - Agents::ensure_identity_scope_schema(); - - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $indexes = $wpdb->get_results( $wpdb->prepare( 'SHOW INDEX FROM %i', $table ), ARRAY_A ); - $identity_index = array_filter( - $indexes, - static fn( array $index ): bool => 'agent_identity_scope_hash' === $index['Key_name'] - ); - - $this->assertCount( 3, $identity_index ); - $this->assertSame( array( 'agent_slug', 'owner_id', 'instance_key_hash' ), array_column( $identity_index, 'Column_name' ) ); - } - private function register_agent( string $slug, array $args = array() ): void { \WP_Agents_Registry::get_instance()->register( $slug, array_merge( array( 'label' => $slug ), $args ) ); $this->registered[] = $slug; diff --git a/plugins/data-machine/tests/Unit/Core/Steps/Upsert/UpsertStepTest.php b/plugins/data-machine/tests/Unit/Core/Steps/Upsert/UpsertStepTest.php index cf7d429aa9..9247d7dd29 100644 --- a/plugins/data-machine/tests/Unit/Core/Steps/Upsert/UpsertStepTest.php +++ b/plugins/data-machine/tests/Unit/Core/Steps/Upsert/UpsertStepTest.php @@ -91,9 +91,9 @@ public function test_required_handler_slugs_allows_non_first_handler_when_config array( 'type' => 'tool_result', 'metadata' => array( - 'handler_tool' => 'publish_post', - 'tool_success' => true, - 'tool_result' => array( + 'handler_tool' => 'publish_post', + 'tool_success' => true, + 'tool_result_envelope' => array( 'success' => true, ), ), diff --git a/plugins/data-machine/tests/Unit/Engine/AI/Tools/ToolResultFinderTest.php b/plugins/data-machine/tests/Unit/Engine/AI/Tools/ToolResultFinderTest.php index 488cfd08e3..ee81eb4247 100644 --- a/plugins/data-machine/tests/Unit/Engine/AI/Tools/ToolResultFinderTest.php +++ b/plugins/data-machine/tests/Unit/Engine/AI/Tools/ToolResultFinderTest.php @@ -73,19 +73,6 @@ public function test_project_result_data_prefers_stable_projected_contract(): vo $this->assertSame( array( 'id' => 456 ), ToolResultFinder::projectResultData( $entry ) ); } - public function test_project_result_data_reads_legacy_envelope_shape(): void { - $entry = array( - 'metadata' => array( - 'tool_result' => array( - 'success' => true, - 'data' => array( 'id' => 123 ), - ), - ), - ); - - $this->assertSame( array( 'id' => 123 ), ToolResultFinder::projectResultData( $entry ) ); - } - public function test_project_result_data_reads_legacy_top_level_payload_shape(): void { $entry = array( 'metadata' => array( diff --git a/plugins/data-machine/tests/agent-bundle-export-config-projection-smoke.php b/plugins/data-machine/tests/agent-bundle-export-config-projection-smoke.php index 4bef0ed776..e72bc22981 100644 --- a/plugins/data-machine/tests/agent-bundle-export-config-projection-smoke.php +++ b/plugins/data-machine/tests/agent-bundle-export-config-projection-smoke.php @@ -177,8 +177,8 @@ function export_config_bundler( array $agent ): AgentBundler { 'owner_id' => 1, 'site_scope' => 7, 'agent_config' => array( - 'provider' => 'openai', - 'model' => 'gpt-5.5', + 'default_provider' => 'openai', + 'default_model' => 'gpt-5.5', 'tool_policy' => array( 'allow' => array( 'datamachine/search' ) ), 'example_extension' => array( 'graph' => array( 'enabled' => true ) ), 'example' => array( @@ -251,8 +251,8 @@ static function ( array $policies ): array { export_config_assert( "{$profile} omits tracking-excluded plugin config", ! isset( $config['plugin_runtime'] ) ); } export_config_assert( "{$profile} honors explicit backup-private exclusion", ! isset( $config['backup_private'] ) ); - export_config_assert_equals( "{$profile} keeps normalized provider", 'openai', $config['default_provider'] ?? null ); - export_config_assert_equals( "{$profile} keeps normalized model", 'gpt-5.5', $config['default_model'] ?? null ); + export_config_assert_equals( "{$profile} keeps default provider", 'openai', $config['default_provider'] ?? null ); + export_config_assert_equals( "{$profile} keeps default model", 'gpt-5.5', $config['default_model'] ?? null ); export_config_assert_equals( "{$profile} keeps tool policy", array( 'datamachine/search' ), $config['tool_policy']['allow'] ?? null ); export_config_assert_equals( "{$profile} keeps plugin bundle-owned policy", true, $config['example_extension']['graph']['enabled'] ?? null ); export_config_assert_equals( "{$profile} keeps site scope", 7, $round_trip['agent']['site_scope'] ?? null ); diff --git a/plugins/data-machine/tests/agent-bundle-portable-update-smoke.php b/plugins/data-machine/tests/agent-bundle-portable-update-smoke.php index bb591dd6cb..016430b897 100644 --- a/plugins/data-machine/tests/agent-bundle-portable-update-smoke.php +++ b/plugins/data-machine/tests/agent-bundle-portable-update-smoke.php @@ -332,7 +332,7 @@ function call_bundle_private( AgentBundler $bundler, string $method, array $args return $out; }; $cli_expected = array( - 'datamachine agents' => array( $cli_subcommands( 'AgentsCommand', 'AgentsCommand' ) + $cli_subcommands( 'AgentBundleCommand', 'AgentBundleCommand' ), array( 'list', 'rename', 'create', 'show', 'delete', 'prune', 'config', 'export', 'import', 'cleanup-legacy-context-files', 'install', 'run-bundle', 'installed', 'graph', 'status', 'inspect', 'validate', 'diff', 'upgrade', 'adopt', 'apply', 'rebase' ) ), + 'datamachine agents' => array( $cli_subcommands( 'AgentsCommand', 'AgentsCommand' ) + $cli_subcommands( 'AgentBundleCommand', 'AgentBundleCommand' ), array( 'list', 'rename', 'create', 'show', 'delete', 'prune', 'config', 'export', 'import', 'install', 'run-bundle', 'installed', 'graph', 'status', 'inspect', 'validate', 'diff', 'upgrade', 'adopt', 'apply', 'rebase' ) ), 'datamachine agents active' => array( $cli_subcommands( 'Agents/ActiveCommand', 'ActiveCommand' ), array( 'get', 'set' ) ), 'datamachine agents access' => array( $cli_subcommands( 'Agents/AccessCommand', 'AccessCommand' ), array( 'grant', 'grant-audience', 'revoke', 'revoke-audience', 'list' ) ), 'datamachine agents token' => array( $cli_subcommands( 'Agents/TokenCommand', 'TokenCommand' ), array( 'create', 'list', 'revoke' ) ), diff --git a/plugins/data-machine/tests/agents-api-persisted-agent-registry-smoke.php b/plugins/data-machine/tests/agents-api-persisted-agent-registry-smoke.php index b064179219..d7e7f581de 100644 --- a/plugins/data-machine/tests/agents-api-persisted-agent-registry-smoke.php +++ b/plugins/data-machine/tests/agents-api-persisted-agent-registry-smoke.php @@ -162,12 +162,13 @@ static function () use ( $repository ): void { agents_api_smoke_assert_equals( 'wordpress-com', $agent ? $agent->get_meta()['example_extension_wiki_slug'] ?? '' : '', 'extension metadata projector is exposed', $failures, $passes ); agents_api_smoke_assert_equals( array( 'researcher', 'writer' ), wp_get_agent( 'coordinator' ) ? wp_get_agent( 'coordinator' )->get_subagents() : array(), 'persisted config projects exact normalized subagent edges', $failures, $passes ); -echo "\n[1b] persisted agent config normalizes legacy model aliases:\n"; -$legacy_config = AgentConfigFactory::normalize( +echo "\n[1b] persisted agent config keeps canonical model defaults:\n"; +$canonical_config = AgentConfigFactory::normalize( array( - 'provider' => 'openai', - 'model' => 'gpt-5.5', - 'mode_models' => array( + 'default_provider' => 'openai', + 'default_model' => 'gpt-5.5', + 'provider' => 'anthropic', + 'mode_models' => array( 'agent' => array( 'provider' => 'openai', 'model' => 'gpt-5.5-agent', @@ -175,11 +176,10 @@ static function () use ( $repository ): void { ), ) ); -agents_api_smoke_assert_equals( 'openai', $legacy_config['default_provider'] ?? '', 'legacy provider becomes default_provider', $failures, $passes ); -agents_api_smoke_assert_equals( 'gpt-5.5', $legacy_config['default_model'] ?? '', 'legacy model becomes default_model', $failures, $passes ); -agents_api_smoke_assert_equals( false, array_key_exists( 'provider', $legacy_config ), 'legacy provider alias is not persisted', $failures, $passes ); -agents_api_smoke_assert_equals( false, array_key_exists( 'model', $legacy_config ), 'legacy model alias is not persisted', $failures, $passes ); -agents_api_smoke_assert_equals( 'gpt-5.5-agent', $legacy_config['mode_models']['agent']['model'] ?? '', 'mode_models remain canonical mode overrides', $failures, $passes ); +agents_api_smoke_assert_equals( 'openai', $canonical_config['default_provider'] ?? '', 'default_provider is preserved', $failures, $passes ); +agents_api_smoke_assert_equals( 'gpt-5.5', $canonical_config['default_model'] ?? '', 'default_model is preserved', $failures, $passes ); +agents_api_smoke_assert_equals( false, array_key_exists( 'default_provider', AgentConfigFactory::normalize( array( 'provider' => 'anthropic' ) ) ), 'scalar provider is not promoted to default_provider', $failures, $passes ); +agents_api_smoke_assert_equals( 'gpt-5.5-agent', $canonical_config['mode_models']['agent']['model'] ?? '', 'mode_models remain canonical mode overrides', $failures, $passes ); echo "\n[2] persisted projection preserves earlier declarative registrations:\n"; datamachine_persisted_agent_registry_reset();