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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions plugins/data-machine/docs/core-system/tool-result-finder.md
Original file line number Diff line number Diff line change
Expand Up @@ -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} │
└─────────────────────────────────────────────────────┘
│
▼
Expand Down Expand Up @@ -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,
Expand All @@ -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;

Expand Down Expand Up @@ -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
}
```
Expand All @@ -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,
Expand Down Expand Up @@ -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'
Expand All @@ -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/']
]
Expand Down
82 changes: 0 additions & 82 deletions plugins/data-machine/inc/Cli/Commands/AgentsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 ) );
}
}
31 changes: 2 additions & 29 deletions plugins/data-machine/inc/Core/Agents/AgentConfigFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string,mixed> $config Raw agent config.
* @return array<string,mixed>
*/
public static function normalize( array $config ): array {
$config = self::normalize_model_defaults( $config );
$config = self::normalize_mode_models( $config );

return $config;
}

/** @param array<string,mixed> $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<string,mixed> $config */
Expand Down
150 changes: 0 additions & 150 deletions plugins/data-machine/inc/Core/Database/Agents/Agents.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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<string,array{unique:bool,columns:string[]}> */
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 <col>` 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.
*
Expand Down
Loading
Loading