diff --git a/docs/SPEC.md b/docs/SPEC.md index c02ca876..8e27ee91 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -27,7 +27,7 @@ Contents: [Glossary](#glossary) · [User stories](#user-stories) · [Platform su - **Reseat.** What the workflow does when something outside it, such as the Publish button, Quick Edit, REST, WP-CLI, cron or untrash, changes a post's status: it moves the post to the region entry stage of the new region and records the change with `cause: 'core'`. The overlay statuses `future` and `trash` never reseat. - **Region entry stage.** The one stage per used region marked `region_entry`. It is where a reseat lands a post and where a post is seated when it is first assigned to a sequence. - **Bypass list.** The `bypass_workflow_roles` setting (default `administrator`). Members see every transition, skip transition role limits and required metadata, and are not stopped by the publish boundary, but still need core capabilities. The separate **tool-check bypass list**, `bypass_tool_check_roles` (default `administrator`), only lets members skip required tool checks on a transition. -- **Stage agent.** An ability set on a stage through the stage's `agent` config, which makes that stage AI-owned. When a post enters the stage, the agent runs in the background on WP-Cron as the post's author, returns `pass` or `fail`, and the sequence's routes decide where the post goes next. +- **Stage agent.** An ability set on a stage through the stage's `agent` config, which makes that stage AI-owned. When a post enters the stage, the agent runs in the background on WP-Cron as the person who moved the post in (or as the post's author when nobody did), returns `pass` or `fail`, and the sequence's routes decide where the post goes next. - **Tool.** An ability that a transition can require or that people run from the command palette or MCP. Its `meta.type` (`check`, `validator` or `helper`) only groups it on the Tools page: checks such as `seo-check` report issues that can block a move, and helpers such as `smart-linking` and `headline-suggestions` make suggestions. On a transition, every required tool is judged by the issues it returns, whatever its type. - **Ability.** A unit of work registered through the WordPress Abilities API. Every Workflows operation is one, so the admin UI, command palette, REST and MCP all reach it with the same permission checks; extensions add their own with `vip_workflows_register_ability()`. - **Experiment.** An unfinished feature (`ideation`, `kanban`, `calendar`, `my_queue`) that is off by default and switched on per site. Turning one off removes its UI and stops its background work without deleting data. @@ -49,8 +49,8 @@ Each story ends with what is always true while the story holds. **N3. A transition enforces the desk's rules.** Moving a story from Editing to Ready runs the tools the transition requires: an SEO check, a checklist, a Parse.ly performance check. Hard failures stop the move, and soft warnings must be acknowledged before it goes through. Transitions can be limited to roles and can notify email or Slack when they fire. *Always true:* every move, from every surface (editor, Kanban drag, My Queue, MCP), goes through `StatusManager::transition()`, and its checks run on the server. A tool's configurable settings must also be declared in its input schema, or every run is rejected. → [Transitions and tools](#transitions-and-tools) -**N4. An AI agent owns a stage, and the sequence decides where the post goes next.** A commerce desk sets an AI agent on its "Affiliate Linking" stage. When a post arrives, the agent runs in the background as the post's author, inserts the links it can verify, and leaves a note on anything ambiguous (two catalog matches for one product) instead of guessing. It then returns pass or fail, and the routes the sequence author set send the post on. Fail can send it to a human review stage. -*Always true:* an agent returns only `pass` or `fail`, and anything else is treated as an error. An agent's content changes are saved as its own attributed revision. An agent can't publish or make a post private unless the sequence allows agent publishing and the post's author holds `publish_posts`. Agent-to-agent hops stop after 10 in a row. → [Stage agents](#stage-agents) +**N4. An AI agent owns a stage, and the sequence decides where the post goes next.** A commerce desk sets an AI agent on its "Affiliate Linking" stage. When a post arrives, the agent runs in the background as the person who moved it there, inserts the links it can verify, and leaves a note on anything ambiguous (two catalog matches for one product) instead of guessing. It then returns pass or fail, and the routes the sequence author set send the post on. Fail can send it to a human review stage. +*Always true:* an agent returns only `pass` or `fail`, and anything else is treated as an error. An agent's content changes are saved as its own attributed revision. An agent can't publish or make a post private unless the sequence allows agent publishing and the person it runs as holds `publish_posts`. Agent-to-agent hops stop after 10 in a row. → [Stage agents](#stage-agents) **N5. A person and an agent don't overwrite each other.** A person can't start an AI stage while others are co-editing the post. An agent's write is abandoned if the post changed after the agent read it, and the editor asks before saving over an agent's newer write. *Always true:* an agent never silently replaces a newer human save. → [Stage agents](#stage-agents) @@ -261,7 +261,7 @@ Routes are grouped by controller below. Paths are under `/vip-workflows/v1` unle | Route | Methods | Permission | | --- | --- | --- | | `/workflow/post/{id}/status`, `/workflow/post/{id}/history`, `/workflow/post/{id}/ideation` | GET | `edit_post` on `{id}` | -| `/workflow/post/{id}/transition`, `/workflow/post/{id}/agent-revert`, `/workflow/post/{id}/claim` | POST | `edit_post` on `{id}`, then the sequence's transition rules | +| `/workflow/post/{id}/transition`, `/workflow/post/{id}/agent-revert`, `/workflow/post/{id}/agent-rerun`, `/workflow/post/{id}/claim` | POST | `edit_post` on `{id}`, then the sequence's transition rules | | `/workflow/post/{id}/sequence` | POST (assign), DELETE (remove) | `edit_post` on `{id}`, then the sequence's transition rules | | `/workflow/post/{id}/unclaim` | DELETE | `edit_post` on `{id}`, then the sequence's transition rules | | `/workflow/my-work` | GET | `edit_posts`; rows filtered per post by `edit_post` | @@ -358,7 +358,7 @@ Where the abilities live: - Research assistants: `vip-workflows/includes/ideation/assistants/class-*.php`. - Extension abilities: each extension's main file or its `includes/` directory. -Stage agents run in the background (WP-Cron; see [Background work](#background-work)) and call `wp_set_current_user()` to act as the post's author (`vip-workflows/includes/workflow/class-stage-agent-runner.php`). If the author cannot edit the post, the run stops in place. Agent edits are therefore authored by that user and pass that user's capability checks. +Stage agents run in the background (WP-Cron; see [Background work](#background-work)) and call `wp_set_current_user()` to act as the person who started the run, if they can still edit the post, and otherwise as the post's author (`vip-workflows/includes/workflow/class-stage-agent-runner.php`). If neither can, the run stops in place. Agent edits are therefore authored by that user and pass that user's capability checks. **Footguns** @@ -1017,15 +1017,15 @@ flowchart TD **What it's for.** A stage agent lets an AI step own a stage: when a post arrives there, the agent does its job (a copy edit, a tag check, a link review) and then moves the post on by itself, to a destination the sequence set for each result. It lets a team put routine review into the workflow without anyone having to remember to run it, while keeping the AI's moves inside the same rules a person's moves follow. -**How it works.** A stage becomes AI-owned when its sequence config names an agent: an Ability, plus where to send the post on each result, plus optional settings. Every time a post enters that stage, the plugin writes a "pending" marker on the post and schedules a single WP-Cron event. When cron runs it, the agent's Ability runs as the post's author, and its result decides where the post goes next. +**How it works.** A stage becomes AI-owned when its sequence config names an agent: an Ability, plus where to send the post on each result, plus optional settings. Every time a post enters that stage, the plugin writes a "pending" marker on the post and schedules a single WP-Cron event. When cron runs it, the agent's Ability runs as the person who started the run, and its result decides where the post goes next. - **Configuring it.** The config is `agent: { ability_id, routing: { pass?, fail?, error? }, settings? }`. The Ability must be registered with `meta.stage_eligible = true`. Saving the sequence rejects an unknown or non-eligible Ability, any routing key other than `pass`, `fail` or `error`, and any routing target that isn't the destination (`to`) of one of that stage's own transitions. The settings are stored exactly as given and are not checked against the Ability's `settings_schema`. -- **What starts a run.** Any stage change into an AI stage: taking a transition, assigning a sequence, or a reseat driven by WordPress core. The pending marker records the stage, the Ability, when it was queued (`queued_at`), the `cause`, the stage the post came from (`from_stage`), and who started it (`started_by`). -- **What the agent gets.** The run executes the Ability through the plugin's Ability executor, in the `agent` context, with input `['post_id' => …] + settings`, acting as the post author. +- **What starts a run.** Any stage change into an AI stage: taking a transition, assigning a sequence, or a reseat driven by WordPress core. The pending marker records the stage, the Ability, when it was queued (`queued_at`), the `cause`, the stage the post came from (`from_stage`), and who started it (`started_by`). Every entry writes a fresh marker, even over a pending one left by an earlier entry; only the cron event is deduplicated. +- **What the agent gets.** The run executes the Ability through the plugin's Ability executor, in the `agent` context, with input `['post_id' => …] + settings`. It acts as the person who started the run if they can edit the post when it runs, and otherwise as the post author. - **Results.** The Ability's output `status` must be `pass` or `fail`. A `WP_Error`, a thrown exception, an unavailable or disabled Ability, or a successful run with any other `status` counts as `error`. - **Routing.** The post takes the route for its result if one is set; otherwise the `error` route if one is set; otherwise the run fails in place. The move out of the stage is a normal workflow transition made on the agent's behalf, and the plugin records the last run on the post. -- **Failing in place.** The marker changes to `failed`, with the error, and the editor offers one action: go back to the stage the post came from. There is no separate re-run. Going back and then forward again starts a new run. -- **Timeouts.** A pending marker older than 15 minutes is turned into a failure the next time anything reads it. +- **Failing in place.** The marker changes to `failed`, with the error. The editor leads with Run again, which starts a fresh run at the same stage started by whoever pressed it, and offers Go back to the stage the post came from beside it. Run again needs the sequence's role rules to allow the move that entered the stage (the authored move from `from_stage`, or any authored move in when the post didn't arrive along one; no rule applies to a stage no authored move leads into, and the bypass list skips this); otherwise 403 `forbidden_transition`, and `can_rerun` is false. Run again and Go back each take the failed marker by compare-and-swap, so of two concurrent presses, or Run again racing Go back, one is refused (409 `agent_rerun_conflict` or `agent_revert_conflict`). +- **Timeouts.** A pending marker older than 15 minutes is turned into a failure the next time anything reads it. Go back holds the failed marker as `reverting` while it moves the post, and puts it back if the move is refused, held for warnings, or throws. A `reverting` marker older than five minutes belongs to a request that died, and is put back to `failed` the next time Run again, Go back or the status payload reads it. ```mermaid stateDiagram-v2 @@ -1038,6 +1038,7 @@ stateDiagram-v2 Running --> FailedInPlace: no route, publish held,
loop guard (10 hops), co-editing,
exit transition refused Running --> WarningsPending: exit transition raised
soft warnings WarningsPending --> Routed: a person confirms the held move + FailedInPlace --> Pending: a person chooses Run again
(runs as them) FailedInPlace --> PreviousStage: a person chooses Go back Routed --> [*]: post moves through the normal transition checks PreviousStage --> [*] @@ -1050,13 +1051,12 @@ stateDiagram-v2 - Only `pass` and `fail` are verdicts. Anything else is `error`, never a guessed pass. → `outcome_from_result()` - A result with no route never invents a destination. It takes the `error` route or fails in place with a visible message. -- The run acts as the post author and only the author. If the author lacks `edit_posts`, the run fails in place (`no_actor`); it never falls back to another user. → `resolve_agent_user()` -- Agents get no extra permissions. The exit transition is authorized against the author (`agent_actor_user`), and the transition still checks `user_can( $actor, 'edit_post' )` and the capability for crossing regions, even for agents. Acting as an agent (`agent_actor`) skips only the sequence's own role table, never WordPress capabilities. -- Who started the run (`started_by`: the person whose move entered the stage, or whoever started the chain when one agent hands to another) is used only to attribute telemetry, never to authorize anything. -- An agent can't publish by default. An agent move from outside `publish`/`private` into either one is held and fails in place (`publish_held`), even through an `error` route, unless the sequence sets `settings.allow_agent_publish === true` (a real boolean). Even then, the author must hold `publish_posts`. While the agent owns the stage, people aren't offered a held route either. → `holds_publication()`, `publication_hold()`, `StatusManager::agent_routed_targets()` +- The run acts as who started it (`started_by`: the person whose move entered the stage, whoever started the chain when one agent hands to another, or whoever pressed Run again), re-checked for `edit_post` when it runs. A run nobody started (cron, a scheduled publish, a reseat with no one logged in) acts as the post author, only if the author has `edit_posts`. Otherwise the run fails in place (`no_actor`); it never borrows anyone else. → `resolve_run_as_user()`, `resolve_agent_user()` +- Agents get no extra permissions. The exit transition is authorized against the user the run acts as (`agent_actor_user`), and the transition still checks `user_can( $actor, 'edit_post' )` and the capability for crossing regions, even for agents. Acting as an agent (`agent_actor`) skips only the sequence's own role table, never WordPress capabilities. +- An agent can't publish by default. An agent move from outside `publish`/`private` into either one is held and fails in place (`publish_held`), even through an `error` route, unless the sequence sets `settings.allow_agent_publish === true` (a real boolean). Even then, the user the run acts as must hold `publish_posts`. While the agent owns the stage, people aren't offered a held route either. → `holds_publication()`, `publication_hold()`, `StatusManager::agent_routed_targets()` - From an AI stage, people can take only the routed destinations; any other move is refused (`unrouted_agent_exit`). While a run is pending, or has failed and is offering go-back, no transitions are offered at all. - A person who moves the post while a run is pending gets an `agent_in_progress` soft warning to confirm. If they confirm, the run is abandoned: its outcome is discarded, but any content it already wrote stays. -- A loop guard stops agents bouncing a post between them forever. The chain counter goes up once per run, right before the exit transition, and a run that doesn't move the post never writes it. Past 10 hops the run fails in place and never takes the `error` route. The counter resets when the post enters the AI stage from a stage with no agent, and on go-back. → `_vip_workflows_agent_chain`, `finish()`, `MAX_CHAIN` +- A loop guard stops agents bouncing a post between them forever. The chain counter goes up once per run, right before the exit transition, and a run that doesn't move the post never writes it. Past 10 hops the run fails in place and never takes the `error` route. The counter resets when the post enters the AI stage from a stage with no agent, on Run again, and on go-back. → `_vip_workflows_agent_chain`, `finish()`, `MAX_CHAIN` - A run whose stage changed under it (the post moved away, or left and came back with a newer marker) is abandoned without recording a failure. Deleting a marker is compare-and-delete, so it only clears a marker that belongs to the same stage. → `abandon_if_superseded()` - Agent moves never auto-acknowledge soft warnings. If the exit transition raises warnings, the marker becomes `warnings_pending` and a person confirms that exact held move. → `hold_for_warnings()` - A refused exit transition, a run that couldn't be scheduled, and the loop guard always fail in place, never through the `error` route. @@ -1077,20 +1077,19 @@ stateDiagram-v2 - **Verdicts aren't reproducible.** No temperature is sent, so a second run tells you nothing about an earlier one. - **Cron has to actually run.** With `DISABLE_WP_CRON` set and no system cron, every AI stage sits pending for 15 minutes and then reports "Agent run timed out." - **The 15-minute pending timeout must stay longer than the longest real run.** Each model call can take up to 180 seconds (`StageAgent::REQUEST_TIMEOUT`), and `PENDING_TTL` is the 15-minute limit. -- **Some screens say "Re-run," but there is no re-run action.** The only retry is going back and forward again. **Code** - `vip-workflows/includes/api/class-sequences-controller.php`: `SequencesController::validate_status_agents()` validates the `agent` config and `meta.stage_eligible`. -- `vip-workflows/includes/workflow/class-stage-agent-runner.php`: `StageAgentRunner`, with `maybe_dispatch()`, `finish()`, `outcome_from_result()`, `resolve_agent_user()`, `holds_publication()`, `publication_hold()`, `abandon_if_superseded()`, `hold_for_warnings()`, `stamp_agent_revision()`, `label_agent_revision()`, `log_token()`, and the constants `MAX_CHAIN` (10) and `PENDING_TTL` (15 minutes). +- `vip-workflows/includes/workflow/class-stage-agent-runner.php`: `StageAgentRunner`, with `maybe_dispatch()`, `rerun()`, `finish()`, `outcome_from_result()`, `resolve_run_as_user()`, `resolve_agent_user()`, `holds_publication()`, `publication_hold()`, `abandon_if_superseded()`, `hold_for_warnings()`, `stamp_agent_revision()`, `label_agent_revision()`, `log_token()`, and the constants `MAX_CHAIN` (10) and `PENDING_TTL` (15 minutes). - `vip-workflows/includes/workflow/class-status-manager.php`: `StatusManager::transition()` (takes `agent_actor` and `agent_actor_user`; refuses with `unrouted_agent_exit`), `get_available_transitions()`, `agent_routed_targets()`, `has_pending_agent_job()`, `revert_failed_agent_stage()`. - `vip-workflows/includes/abilities/agents/class-stage-agent.php`: `StageAgent` helpers `read_post()`, `generate()`, `verdict_token()`, `is_verdict()`, `wrap_untrusted()`, `write_content()`, block-anchored editorial notes, `check_rate_limit()`, and `REQUEST_TIMEOUT` (180 s). - `vip-workflows/includes/abilities/class-ability-executor.php`: `AbilityExecutor`, `AbilityExecutor::execute()`. `vip-workflows/includes/abilities/class-ability-settings.php`: `AbilitySettings::get_options()`. - `vip-workflows/includes/workflow/class-co-editing.php`: `CoEditing::is_shared()`, reading VIP Real-Time Collaboration's `RoomPresence`. - Cron event: `vip_workflows_run_stage_agent`. - Post meta: `_vip_workflows_agent_job` (the marker: `pending`, `failed` or `warnings_pending`, with stage, ability, `queued_at`, `cause`, `from_stage`, `started_by`), `_vip_workflows_agent_last_run`, `_vip_workflows_agent_chain`. Revision meta: `_vip_workflows_agent_actor`. -- REST: `POST /workflow/post/{id}/agent-revert` (go back). -- Error codes: `no_actor`, `publish_held`, `unrouted_agent_exit`, `agent_in_progress` (soft warning), `co_editing`, `concurrent_edit`. +- REST: `POST /workflow/post/{id}/agent-rerun` (Run again; the failed job's `can_rerun` says when it's offered) and `POST /workflow/post/{id}/agent-revert` (go back). +- Error codes: `no_actor`, `no_agent_rerun`, `agent_rerun_conflict`, `agent_revert_conflict`, `publish_held`, `unrouted_agent_exit`, `agent_in_progress` (soft warning), `co_editing`, `concurrent_edit`. - Sequence setting: `settings.allow_agent_publish`. Capabilities checked: `edit_posts`, `edit_post`, `publish_posts`. - Threat model: `docs/reference/stage-agent-verdict-threat-model.md`. diff --git a/vip-workflows/includes/api/class-workflow-controller.php b/vip-workflows/includes/api/class-workflow-controller.php index d577c7b0..b6686879 100644 --- a/vip-workflows/includes/api/class-workflow-controller.php +++ b/vip-workflows/includes/api/class-workflow-controller.php @@ -147,6 +147,27 @@ public function register_routes(): void { ) ); + // POST /workflow/post/{id}/agent-rerun - Run a post's failed stage agent + // again, in place, as the person asking. + register_rest_route( + $this->namespace, + '/' . $this->rest_base . '/post/(?P[\d]+)/agent-rerun', + array( + array( + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => array( $this, 'rerun_agent_stage' ), + 'permission_callback' => array( $this, 'transition_permissions_check' ), + 'args' => array( + 'id' => array( + 'description' => 'Post ID.', + 'type' => 'integer', + 'required' => true, + ), + ), + ), + ) + ); + // GET /workflow/post/{id}/history - Get transition history. // // Gated on `edit_post` for this post (get_post_status_permissions_check), @@ -719,7 +740,7 @@ public function transition_status( $request ) { * @return array|null */ private function get_agent_job_state( int $post_id, string $stage ): ?array { - $job = get_post_meta( $post_id, \VIPWorkflows\Workflow\StageAgentRunner::JOB_META, true ); + $job = \VIPWorkflows\Workflow\StageAgentRunner::read_job_marker( $post_id ); if ( ! is_array( $job ) || ( $job['stage_key'] ?? '' ) !== $stage ) { return null; } @@ -744,8 +765,16 @@ private function get_agent_job_state( int $post_id, string $stage ): ?array { $status_manager = Plugin::get_instance()->get_status_manager(); $revert_stage = $status_manager->get_agent_revert_stage( $post_id ); + // Run again in place (rerun_agent_stage()). This method is only + // reached for the current stage's job, so the other conditions + // StageAgentRunner::rerun() holds are that the stage still has an + // agent and that the sequence's role rules let this person in. + $sequence = $status_manager->get_sequence_for_post( $post_id ); + $stage_config = $sequence ? $sequence->get_status( $stage ) : null; + $state['can_rerun'] = ! empty( $stage_config['agent']['ability_id'] ) + && \VIPWorkflows\Workflow\StageAgentRunner::user_can_rerun( $sequence, $stage, (string) ( $job['from_stage'] ?? '' ), get_current_user_id() ); + if ( null !== $revert_stage ) { - $sequence = $status_manager->get_sequence_for_post( $post_id ); $revert_config = $sequence ? $sequence->get_status( $revert_stage ) : null; $state['revert_to'] = array( @@ -788,9 +817,8 @@ private function get_agent_last_run( int $post_id ): ?array { /** * Return a post whose stage agent failed in place to the stage it came from. * - * The failed state's one action. Going forward again through the AI stage is - * how a run is retried — entry re-dispatches the agent — so there is no - * separate re-run. + * The way out of a failed AI stage when the agent should not simply run + * again. Retrying in place is rerun_agent_stage(). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error @@ -817,6 +845,37 @@ public function revert_agent_stage( $request ) { return $response; } + /** + * Run a post's failed stage agent again, in place. + * + * The run is started by the person asking, so it acts as them when they can + * edit the post (StageAgentRunner::resolve_run_as_user()). That is what lets + * a re-run fix a failure the previous identity could not get past. + * + * @param WP_REST_Request $request Request object. + * @return WP_REST_Response|WP_Error + */ + public function rerun_agent_stage( $request ) { + $post_id = (int) $request->get_param( 'id' ); + + $sequence = Plugin::get_instance()->get_status_manager()->get_sequence_for_post( $post_id ); + $runner = Plugin::get_instance()->get_module( 'stage-agent-runner' ); + if ( ! $sequence || ! $runner instanceof \VIPWorkflows\Workflow\StageAgentRunner ) { + return new WP_Error( + 'no_agent_rerun', + __( 'This post has no failed AI agent to run again.', 'vip-workflows' ), + array( 'status' => 409 ) + ); + } + + $result = $runner->rerun( $post_id, $sequence ); + if ( is_wp_error( $result ) ) { + return $result; + } + + return $this->get_post_status( $request ); + } + /** * Get transition history for a post. * diff --git a/vip-workflows/includes/workflow/class-stage-agent-runner.php b/vip-workflows/includes/workflow/class-stage-agent-runner.php index 22f2d532..35d97673 100644 --- a/vip-workflows/includes/workflow/class-stage-agent-runner.php +++ b/vip-workflows/includes/workflow/class-stage-agent-runner.php @@ -80,6 +80,18 @@ class StageAgentRunner implements ModuleInterface { */ public const PENDING_TTL = 15 * 60; + /** + * How long a Go back may hold the marker as `reverting` (seconds). + * + * Go back holds it only for the length of one request. A `reverting` + * marker older than this belongs to a request that died before it could + * put the failed state back (a fatal in a hooked callback, a timeout), so + * read_job_marker() reads it as the failure it was. + * + * @var int + */ + public const REVERTING_TTL = 5 * 60; + /** * Post meta recording the last agent run that resolved and moved the post: * the stage it ran in, which of pass/fail/error fired, the stage it routed @@ -141,15 +153,17 @@ class StageAgentRunner implements ModuleInterface { private static string $acting_ability_id = ''; /** - * The person who started the run whose exit transition is in progress. + * The run whose exit transition is in progress: its post and its starter. * - * An agent's exit transition runs with nobody logged in, and its job marker is - * cleared before it, so a next AI stage dispatched by that transition reads its - * starter from here. Set around the exit transition only. + * A next AI stage that exit dispatches for the SAME post takes its starter + * from here. Keyed by post, because a callback inside that transition can + * move another post into an AI stage, and that post's run belongs to nobody + * the exiting run vouches for. Set around the exit transition only; null + * otherwise. A starter of 0 (nobody) is carried as nobody. * - * @var int + * @var array{post_id:int,started_by:int}|null */ - private static int $exiting_run_started_by = 0; + private static ?array $exiting_run = null; /** * Ability executor used to run stage agents. Injectable for testing. @@ -226,16 +240,13 @@ public function maybe_dispatch( int $post_id, string $new_status, string $old_st return; } - // Re-entrancy guard: never schedule a second job while one is already - // pending for this same post + stage. - $existing = get_post_meta( $post_id, self::JOB_META, true ); - if ( - is_array( $existing ) - && 'pending' === ( $existing['status'] ?? '' ) - && ( $existing['stage_key'] ?? '' ) === $new_status - ) { - return; - } + // Every real entry writes a fresh marker, even when a pending one for this + // stage is still there (a person confirmed a move out before the run + // fired, and the post has now come back). The marker carries who the run + // acts as and where Go back leads, and both belong to this entry, not the + // abandoned one. Only the cron event is deduplicated: an identical queued + // event serves the new marker (see dispatch()), and a run already in + // flight sees the new queued_at and abandons (abandon_if_superseded()). // Reset the loop-guard chain when a human (non-agent) stage moved the post // in; only consecutive agent→agent hops accumulate toward MAX_CHAIN. @@ -244,36 +255,212 @@ public function maybe_dispatch( int $post_id, string $new_status, string $old_st delete_post_meta( $post_id, self::CHAIN_META ); } - // Who caused this run, for telemetry: the person whose move entered the - // stage, or, for an agent-to-agent hop, whoever started the chain. - $started_by = get_current_user_id(); - if ( $started_by <= 0 ) { - $started_by = self::$exiting_run_started_by; + // Who caused this run: the person whose move entered the stage, or, for an + // agent-to-agent hop, whoever started the chain. Nobody (0) when no person + // is behind it — cron, a scheduled publish, a reseat with no one logged in. + // The run acts as this person when they can still edit the post (see + // resolve_run_as_user()), and its telemetry is recorded as them. + $started_by = $this->dispatching_person( $post_id ); + + $this->dispatch( + $post_id, + $new_status, + (string) $status['agent']['ability_id'], + $old_status, + (string) ( $context['cause'] ?? 'workflow' ), + $started_by + ); + } + + /** + * Who a dispatch for this post belongs to. + * + * The starter an agent's own exit carries, for that post's next stage. + * Otherwise the logged-in person whose request moved the post — but never + * under cron, where nobody moved anything: a user present there (cron run + * with `--user`, or one an earlier callback left set) authorized nothing. + * + * @param int $post_id Post being dispatched. + * @return int User ID, or 0 for nobody. + */ + private function dispatching_person( int $post_id ): int { + if ( null !== self::$exiting_run && self::$exiting_run['post_id'] === $post_id ) { + return self::$exiting_run['started_by']; } - update_post_meta( + if ( wp_doing_cron() ) { + return 0; + } + + return get_current_user_id(); + } + + /** + * Run a failed stage agent again, in place, as the person asking. + * + * The failed state's direct retry: the post stays at its AI stage and the + * agent is dispatched afresh, started by the current user. Because a run + * acts as the person who started it when they can edit the post (see + * resolve_run_as_user()), a re-run fixes the failures a different identity + * can fix, such as an author who cannot edit posts, without moving the post + * out of the stage and back in. + * + * Only a run that failed at the post's current stage can be run again, and + * only while that stage still has an agent. The loop-guard chain restarts, + * as it does whenever a person moves a post into an AI stage. + * + * @param int $post_id Post ID. + * @param Sequence $sequence Sequence for the post. + * @return true|\WP_Error True once the run is dispatched (a dispatch that + * cannot be scheduled fails in place, as on entry). + */ + public function rerun( int $post_id, Sequence $sequence ): true|\WP_Error { + $stage_key = (string) get_post_meta( $post_id, StatusManager::STAGE_META_KEY, true ); + $status = $sequence->get_status( $stage_key ); + $job = self::read_job_marker( $post_id ); + + if ( + empty( $status['agent']['ability_id'] ) + || ! is_array( $job ) + || 'failed' !== ( $job['status'] ?? '' ) + || ( $job['stage_key'] ?? '' ) !== $stage_key + ) { + return new \WP_Error( + 'no_agent_rerun', + __( 'This post has no failed AI agent to run again.', 'vip-workflows' ), + array( 'status' => 409 ) + ); + } + + if ( ! self::user_can_rerun( $sequence, $stage_key, (string) ( $job['from_stage'] ?? '' ), get_current_user_id() ) ) { + return new \WP_Error( + 'forbidden_transition', + __( 'Your role cannot move posts into this stage, so you cannot run its agent again.', 'vip-workflows' ), + array( 'status' => 403 ) + ); + } + + // Replace exactly the failed marker validated above, or nothing. Two + // people pressing Run again at once, or Run again racing Go back, must + // not both win: the loser finds the marker changed and is refused. + $dispatched = $this->dispatch( $post_id, - self::JOB_META, - array( - 'stage_key' => $new_status, - 'ability_id' => $status['agent']['ability_id'], - 'status' => 'pending', - 'queued_at' => current_time( 'mysql' ), - 'cause' => (string) ( $context['cause'] ?? 'workflow' ), - 'from_stage' => $old_status, - 'started_by' => $started_by, - ) + $stage_key, + (string) $status['agent']['ability_id'], + (string) ( $job['from_stage'] ?? '' ), + 'rerun', + get_current_user_id(), + $job ); + if ( ! $dispatched ) { + return new \WP_Error( + 'agent_rerun_conflict', + __( 'This agent run changed while you were starting it. Reload the post to see where it is now.', 'vip-workflows' ), + array( 'status' => 409 ) + ); + } + + delete_post_meta( $post_id, self::CHAIN_META ); + + return true; + } - $scheduled = wp_schedule_single_event( time(), self::RUN_HOOK, array( $post_id, $new_status ), true ); + /** + * Whether a person may run a failed stage agent again. + * + * Run again starts a run that acts as the person who presses it, so it is + * held to the sequence's role rules for entering the stage. When the post + * came in along an authored transition, they must be allowed to take that + * one. When it didn't (a reseat or a sequence assign put it here, so the + * recorded origin has no edge into the stage, or there is no origin), any + * authored move into the stage they may take will do. A stage no authored + * transition leads into has no role rule for entering it, so nothing is + * held back. The bypass list skips role rules here as everywhere. + * + * Role rules only. Core capabilities are checked separately: the route + * requires `edit_post`, and the run re-checks it when it fires. + * + * @param Sequence $sequence Sequence for the post. + * @param string $stage_key The failed AI stage. + * @param string $from_stage The stage the job records the post entering from. + * @param int $user_id The person asking. + * @return bool + */ + public static function user_can_rerun( Sequence $sequence, string $stage_key, string $from_stage, int $user_id ): bool { + if ( $user_id <= 0 ) { + return false; + } + + if ( \VIPWorkflows\Admin\Settings::can_user_bypass_workflow( $user_id ) ) { + return true; + } + + $incoming = array(); + foreach ( $sequence->get_statuses() as $status ) { + $key = (string) ( $status['key'] ?? '' ); + if ( '' !== $key && $sequence->is_transition_allowed( $key, $stage_key ) ) { + $incoming[] = $key; + } + } + + if ( empty( $incoming ) ) { + return true; + } + + $origins = in_array( $from_stage, $incoming, true ) ? array( $from_stage ) : $incoming; + + foreach ( $origins as $origin ) { + foreach ( $sequence->get_role_permitted_transitions( $origin, $user_id ) as $transition ) { + if ( ( $transition['to'] ?? '' ) === $stage_key ) { + return true; + } + } + } + + return false; + } + + /** + * Write a pending job marker and schedule the run that serves it. + * + * @param int $post_id Post ID. + * @param string $stage_key The AI stage the run belongs to. + * @param string $ability_id The stage's agent ability. + * @param string $from_stage The stage the post entered from, kept for go-back. + * @param string $cause What dispatched it: workflow, core or rerun. + * @param int $started_by The person who started the run, or 0. + * @param array|null $replacing The marker this one may only replace: when + * given, the write is conditional on the stored + * marker still being exactly this one. + * @return bool False only when `$replacing` no longer matched, and nothing + * was written or scheduled. + */ + private function dispatch( int $post_id, string $stage_key, string $ability_id, string $from_stage, string $cause, int $started_by, ?array $replacing = null ): bool { + $marker = array( + 'stage_key' => $stage_key, + 'ability_id' => $ability_id, + 'status' => 'pending', + 'queued_at' => current_time( 'mysql' ), + 'cause' => $cause, + 'from_stage' => $from_stage, + 'started_by' => $started_by, + ); + + if ( null === $replacing ) { + update_post_meta( $post_id, self::JOB_META, $marker ); + } elseif ( ! $this->replace_job_marker( $post_id, $replacing, $marker ) ) { + return false; + } + + $scheduled = wp_schedule_single_event( time(), self::RUN_HOOK, array( $post_id, $stage_key ), true ); if ( true !== $scheduled ) { // An identical event (same hook + args = same post + stage) is already // queued — e.g. a reseat round-trip (A→B→A) re-entered this stage while // its original run event was still pending. That queued event will serve // the freshly written pending marker when it fires: success, not failure. if ( $this->is_duplicate_event_error( $scheduled ) ) { - $this->log_duplicate_event( $post_id, $new_status ); - return; + $this->log_duplicate_event( $post_id, $stage_key ); + return true; } // The run was never queued — a pending marker with no scheduled event @@ -286,14 +473,132 @@ public function maybe_dispatch( int $post_id, string $new_status, string $old_st : __( 'The agent run could not be scheduled.', 'vip-workflows' ); $this->fail_in_place( $post_id, - $new_status, - $status['agent']['ability_id'], + $stage_key, + $ability_id, $message, - $old_status, + $from_stage, array( 'stop_reason' => 'dispatch_failed' ), is_wp_error( $scheduled ) ? (string) $scheduled->get_error_code() : '' ); } + + return true; + } + + /** + * Replace the job marker, only where it is still exactly `$expected`. + * + * Not update_post_meta()'s `$prev_value`: when the row is missing + * altogether, core adds it rather than failing, and a stale caller (one + * that read a marker a Go back has since deleted) would then queue a run + * for a stage the post has left. + * + * @param int $post_id Post ID. + * @param array $expected The marker the caller read and validated. + * @param array $marker The marker to write in its place. + * @return bool True when this caller replaced it. + */ + private function replace_job_marker( int $post_id, array $expected, array $marker ): bool { + return self::swap_job_marker( $post_id, $expected, $marker ); + } + + /** + * Take the job marker, only where it is still exactly `$expected`: replace + * it with `$replacement`, or delete it when that is null. + * + * Go back's half of the compare-and-swap Run again uses + * (replace_job_marker()), so when both race for the same failed marker, + * exactly one of them takes it and the other finds it changed. + * + * @param int $post_id Post ID. + * @param array $expected The marker the caller read and validated. + * @param array|null $replacement The marker to write in its place, or null to delete it. + * @return bool True when this caller changed it. + */ + public static function take_job_marker( int $post_id, array $expected, ?array $replacement = null ): bool { + return self::swap_job_marker( $post_id, $expected, $replacement ); + } + + /** + * Read the job marker, putting a Go back that never finished back to failed. + * + * Go back swaps the failed marker for a `reverting` one while it moves the + * post, and swaps it back if the move doesn't happen. A request that dies + * in between leaves `reverting` behind, and nothing else clears it: Run + * again and Go back both need `failed`, and only `pending` times out. Once + * it is older than REVERTING_TTL, this swaps it back to the failed marker + * by compare-and-swap, so a Go back still in flight is never overwritten + * by a stale reader. + * + * Every reader that decides whether a failed run can be retried or + * reverted goes through here. + * + * @param int $post_id Post ID. + * @return mixed The JOB_META value, as get_post_meta() returns it. + */ + public static function read_job_marker( int $post_id ): mixed { + $job = get_post_meta( $post_id, self::JOB_META, true ); + if ( ! is_array( $job ) || 'reverting' !== ( $job['status'] ?? '' ) ) { + return $job; + } + + $since = (int) ( $job['reverting_at'] ?? 0 ); + if ( $since > 0 && ( time() - $since ) <= self::REVERTING_TTL ) { + return $job; + } + + $failed = $job; + unset( $failed['reverting_at'] ); + $failed['status'] = 'failed'; + + if ( ! self::swap_job_marker( $post_id, $job, $failed ) ) { + // Someone else changed it first; read what they wrote. + return get_post_meta( $post_id, self::JOB_META, true ); + } + + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log + error_log( sprintf( '[VIP Workflows] Go back never finished; failed state restored: post=%d stage=%s', $post_id, self::log_token( (string) ( $job['stage_key'] ?? '' ) ) ) ); + + return $failed; + } + + /** + * Replace or delete the job marker, only where it is still exactly `$expected`. + * + * One UPDATE or DELETE whose WHERE names the expected value, so of two + * concurrent callers exactly one changes the row. + * + * @param int $post_id Post ID. + * @param array $expected The marker the caller read and validated. + * @param array|null $marker The marker to write in its place, or null to delete it. + * @return bool True when this caller changed the row. + */ + private static function swap_job_marker( int $post_id, array $expected, ?array $marker ): bool { + global $wpdb; + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- a compare-and-swap on one post's job marker, found by post_id (indexed); the post's meta cache is cleared below. + $where = array( + 'post_id' => $post_id, + 'meta_key' => self::JOB_META, + 'meta_value' => maybe_serialize( $expected ), + ); + $where_format = array( '%d', '%s', '%s' ); + + $changed = null === $marker + ? $wpdb->delete( $wpdb->postmeta, $where, $where_format ) + : $wpdb->update( $wpdb->postmeta, array( 'meta_value' => maybe_serialize( $marker ) ), $where, array( '%s' ), $where_format ); + // phpcs:enable + + wp_cache_delete( $post_id, 'post_meta' ); + + // false is a failed query, not a lost race: say so in the log, since + // the caller can only report both to the author as a conflict. + if ( false === $changed ) { + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log + error_log( sprintf( '[VIP Workflows] Agent job marker write failed: post=%d db_error=%s', $post_id, self::log_token( (string) $wpdb->last_error ) ) ); + } + + return 1 === $changed; } /** @@ -358,19 +663,34 @@ public function run_stage_agent( int $post_id, string $stage_key ): void { return; } + // A marker for this stage that has already resolved (failed, held for + // warnings, or being gone back from) has no run left to serve. Every entry writes a fresh + // marker and relies on cron to deduplicate the event, but cron only + // matches events within about ten minutes of each other, so a late cron + // can hold two events for one post and stage. The second must not + // execute the agent again against the first one's outcome. + $job_at_dispatch = get_post_meta( $post_id, self::JOB_META, true ); + if ( + is_array( $job_at_dispatch ) + && ( $job_at_dispatch['stage_key'] ?? '' ) === $stage_key + && 'pending' !== ( $job_at_dispatch['status'] ?? '' ) + ) { + return; + } + // This run's identity, read before the ability executes: the queued_at of // the marker it is serving. abandon_if_superseded() compares it afterwards // so an A→B→A round trip (which re-enters the SAME stage with a fresh job) // is not mistaken for "nothing moved". - $job_at_dispatch = get_post_meta( $post_id, self::JOB_META, true ); - $run_token = is_array( $job_at_dispatch ) ? (string) ( $job_at_dispatch['queued_at'] ?? '' ) : ''; + $run_token = is_array( $job_at_dispatch ) ? (string) ( $job_at_dispatch['queued_at'] ?? '' ) : ''; // Where the post came from — the failed state's go-back destination. // Carried through every fail-in-place so the marker a human sees still // knows the way back. $from_stage = is_array( $job_at_dispatch ) ? (string) ( $job_at_dispatch['from_stage'] ?? '' ) : ''; - // Who the run's telemetry is recorded as. See maybe_dispatch(). + // Who started the run, if anyone: who it acts as and who its telemetry is + // recorded as. See maybe_dispatch(). $started_by = is_array( $job_at_dispatch ) ? (int) ( $job_at_dispatch['started_by'] ?? 0 ) : 0; $status = $sequence->get_status( $stage_key ); @@ -450,16 +770,20 @@ public function run_stage_agent( int $post_id, string $stage_key ): void { // Stage agents run in an async (cron) context with no logged-in user, so // the ability's permission_callback (typically current_user_can('edit_posts')) - // would fail. Execute as the capable post author and restore afterward. - // The impersonated human owns the write for capability purposes, so any - // revision the agent produces is natively - // authored by them; self::$acting_ability_id lets stamp_agent_revision() - // tag that revision with the agent that actually made the edit, and the - // revisions UI is relabelled from there. + // would fail. Execute as a capable person and restore afterward: the + // person who moved the post in, else its author (resolve_run_as_user()). + // + // The impersonated person owns the write for capability purposes, so any + // revision the agent produces is natively authored by them. That is + // deliberate: when an editor moves someone else's post into an AI stage, + // the revision is the editor's, because the editor is who asked for it. + // self::$acting_ability_id lets stamp_agent_revision() tag that revision + // with the agent that actually made the edit, and the revisions UI is + // relabelled from there. $previous_user = get_current_user_id(); - $actor_user = $this->resolve_agent_user( $post_id ); + $actor_user = $this->resolve_run_as_user( $post_id, $started_by ); - // No capable owner means no identity this run may legitimately borrow. + // No capable person means no identity this run may legitimately borrow. // Stop in place regardless of the configured error route: an error-route // transition would require the same missing actor and would replace this // actionable failure with a generic transition error. @@ -468,7 +792,11 @@ public function run_stage_agent( int $post_id, string $stage_key ): void { $post_id, $stage_key, $ability_id, - __( 'The author cannot edit posts, so the agent didn’t run. Reassign the post or move it back.', 'vip-workflows' ), + // Why, not what to do: the failed state offers Run again, which + // acts as whoever presses it. + $started_by > 0 + ? __( 'The person who moved this post here can no longer edit it, and neither can its author.', 'vip-workflows' ) + : __( 'This post moved here automatically, and its author can’t edit posts, so the agent had no one to run as.', 'vip-workflows' ), $from_stage, array( 'stop_reason' => 'no_actor', @@ -679,11 +1007,38 @@ private function abandon_if_superseded( int $post_id, string $stage_key, string } /** - * Resolve a capable user to run the agent as, in the user-less cron context. + * Resolve who a run acts as, in the user-less cron context. + * + * The person who started the run, when there is one and they can still edit + * this post. Re-checked here rather than trusted from dispatch, because + * capabilities can change between the move and the run. Running as them is + * not an escalation: they authorized the move into this stage, and the + * check proves they hold the rights for this post right now. + * + * Otherwise the post author, as resolve_agent_user() decides. That is the + * only path for a run nobody started (cron, a scheduled publish, a reseat + * with no one logged in), which has no person whose rights it could borrow. + * + * @param int $post_id Post ID. + * @param int $started_by The person who started the run, or 0. + * @return int User ID, or 0 when neither can run the agent. + */ + private function resolve_run_as_user( int $post_id, int $started_by ): int { + if ( $started_by > 0 && user_can( $started_by, 'edit_post', $post_id ) ) { + return $started_by; + } + + return $this->resolve_agent_user( $post_id ); + } + + /** + * Resolve the post author as the user to run the agent as, when no capable + * person started the run. * * The post author, and only the post author — they own the content, so the * revision the agent produces is attributed to the right person and the - * agent can do nothing they could not have done by hand. + * agent can do nothing they could not have done by hand. Never a substitute + * for a person who started the run; see resolve_run_as_user(). * * This used to fall back to the first administrator when the author could * not edit posts, which inverted the intent: the run gained privilege @@ -1062,12 +1417,15 @@ private function finish( int $post_id, string $stage_key, string $ability_id, st $options['comment'] = $comment; } - $status_manager = \VIPWorkflows\Plugin::get_instance()->get_status_manager(); - self::$exiting_run_started_by = (int) ( $run['started_by'] ?? 0 ); + $status_manager = \VIPWorkflows\Plugin::get_instance()->get_status_manager(); + self::$exiting_run = array( + 'post_id' => $post_id, + 'started_by' => (int) ( $run['started_by'] ?? 0 ), + ); try { $transitioned = $status_manager->transition( $post_id, $target, $options ); } finally { - self::$exiting_run_started_by = 0; + self::$exiting_run = null; } // transition() answers with a warnings array rather than a WP_Error when diff --git a/vip-workflows/includes/workflow/class-status-manager.php b/vip-workflows/includes/workflow/class-status-manager.php index 917252fe..55092132 100644 --- a/vip-workflows/includes/workflow/class-status-manager.php +++ b/vip-workflows/includes/workflow/class-status-manager.php @@ -222,7 +222,7 @@ public function get_agent_revert_stage( int $post_id ): ?string { return null; } - $job = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + $job = StageAgentRunner::read_job_marker( $post_id ); if ( ! is_array( $job ) || 'failed' !== ( $job['status'] ?? '' ) @@ -250,13 +250,15 @@ public function get_agent_revert_stage( int $post_id ): ?string { * * Human intervention resets the agent-loop guard, exactly as a human * transition into an AI stage does — going back and forward again IS the - * re-run. The failed marker is cleared compare-and-delete after the move, so - * a job the origin stage's own dispatch just queued (the origin can itself - * be an AI stage) is never touched. + * re-run. The failed marker is taken by compare-and-swap before the move, so + * Go back and Run again can't both win, and a job the origin stage's own + * dispatch queues during the move (the origin can itself be an AI stage) is + * never touched. * * @param int $post_id Post ID. * @return bool|array|\WP_Error True on success, transition()'s warnings array * if one surfaces, WP_Error otherwise. + * @throws \Throwable Whatever transition() throws, once the failed state is back. */ public function revert_failed_agent_stage( int $post_id ): bool|array|\WP_Error { $revert_to = $this->get_agent_revert_stage( $post_id ); @@ -268,18 +270,60 @@ public function revert_failed_agent_stage( int $post_id ): bool|array|\WP_Error ); } + // Take the failed marker before moving anything, by swapping it for a + // `reverting` one. Run again replaces the same failed marker by + // compare-and-swap, so of the two racing, exactly one wins and the + // other is refused: a Go back that loses must not move the post, or it + // would leave it at the origin with a pending run queued for the stage + // it just left. Swapped rather than deleted, so a late run event that + // fires during the move still finds a resolved marker and doesn't run. + // Stamped, so a request that dies before putting it back leaves a + // marker read_job_marker() can tell has been abandoned. $failed_job = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + $reverting = is_array( $failed_job ) + ? array_merge( + $failed_job, + array( + 'status' => 'reverting', + 'reverting_at' => time(), + ) + ) + : array(); + if ( + ! is_array( $failed_job ) + || 'failed' !== ( $failed_job['status'] ?? '' ) + || ! StageAgentRunner::take_job_marker( $post_id, $failed_job, $reverting ) + ) { + return new \WP_Error( + 'agent_revert_conflict', + __( 'This agent run changed while you were going back. Reload the post to see where it is now.', 'vip-workflows' ), + array( 'status' => 409 ) + ); + } delete_post_meta( $post_id, StageAgentRunner::CHAIN_META ); - $result = $this->transition( $post_id, $revert_to, array( 'agent_revert' => true ) ); + try { + $result = $this->transition( $post_id, $revert_to, array( 'agent_revert' => true ) ); + } catch ( \Throwable $e ) { + // The move threw, so it didn't finish: put the failed state back + // before letting the error through, or Run again and Go back would + // both refuse until read_job_marker() times the marker out. + StageAgentRunner::take_job_marker( $post_id, $reverting, $failed_job ); + throw $e; + } + if ( true !== $result ) { + // The move didn't happen (refused, or held for soft warnings), so + // put the failed state back, unless something else has written a + // marker since. + StageAgentRunner::take_job_marker( $post_id, $reverting, $failed_job ); return $result; } - if ( is_array( $failed_job ) ) { - delete_post_meta( $post_id, StageAgentRunner::JOB_META, $failed_job ); - } + // Clear it, unless the move's own dispatch (the origin can itself be an + // AI stage) has already written a new marker over it. + StageAgentRunner::take_job_marker( $post_id, $reverting ); return true; } diff --git a/vip-workflows/src/editor/components/TransitionFlow.js b/vip-workflows/src/editor/components/TransitionFlow.js index 1b3d12b3..fcb5c327 100644 --- a/vip-workflows/src/editor/components/TransitionFlow.js +++ b/vip-workflows/src/editor/components/TransitionFlow.js @@ -212,6 +212,7 @@ export function TransitionFlow() { fetchWorkflowStatus, receiveWorkflowStatus, clearTransitionRequest, + rerunAgentStage, setTransitioningTo, setTransitionError, showWorkflowPanel, @@ -537,6 +538,106 @@ export function TransitionFlow() { return ( ! live || consent.metaBoxes ) && editor.isEditedPostSaveable(); }; + /** + * Save the post first when decideSave() says so, and confirm it took. + * + * Waits out a save core already has in flight rather than racing it, then + * decides (the post can become dirty during that wait), then saves. Every + * request that has the server act on the post — a move, or running a stage + * agent again — goes through here, so the server judges the work on screen. + * + * @param {string} failureMessage What to report when the save fails. + * @return {Promise} Resolves once the post is saved or needs no + * save. Rejects with MOVE_CANCELLED when the author + * backs out, or with an error to report. + */ + const saveFirst = ( failureMessage ) => { + const editor = registry.select( editorStore ); + let saved = false; + + return whenSaveSettles( registry ) + .then( decideSave ) + .then( ( shouldSave ) => { + saved = shouldSave; + + if ( ! saved ) { + return; + } + + // Core's own save controls stand down while saving is locked + // — an upload still in flight, a plugin's pre-publish check — + // but savePost() itself never asks. + if ( editor.isPostSavingLocked() ) { + throw { + code: 'save_locked', + message: __( + 'The post can’t be saved yet. Wait for uploads to finish, then try again.', + 'vip-workflows' + ), + }; + } + + return savePost(); + } ) + .then( () => { + // savePost() resolves even when the save request fails (the error + // is recorded in the editor store, meta boxes' included). If it + // failed, or the post is still dirty, the content never + // persisted, so bail rather than send a request the server will + // judge against a row that is not what the author is looking at. + if ( + saved && + ( editor.didPostSaveRequestFail() || + editor.isEditedPostDirty() ) + ) { + throw { code: 'save_failed', message: failureMessage }; + } + } ); + }; + + /** + * Run a failed stage agent again, in place. + * + * The agent reads the stored post, so the author's unsaved edits are saved + * first on exactly the terms a move into an AI stage uses — the edits on + * screen are the edits it works from. Refused, like entering the stage, + * while another editor has the post open. + */ + const handleRerun = () => { + consentRef.current = {}; + + if ( otherEditorsOpen ) { + reportError( getCoEditingRefusal() ); + return; + } + + clearErrors(); + setTransitioningTo( workflow?.current?.key ?? null ); + + saveFirst( + __( + 'Could not save the post before running the agent again. Try again.', + 'vip-workflows' + ) + ) + .then( () => rerunAgentStage() ) + .catch( ( err ) => { + setTransitioningTo( null ); + + if ( MOVE_CANCELLED === err?.code ) { + return; + } + + reportError( + err?.message || + __( + 'Could not run the agent again. Try again.', + 'vip-workflows' + ) + ); + } ); + }; + const handleTransition = ( toStatus, acknowledgeWarnings = false, @@ -587,62 +688,18 @@ export function TransitionFlow() { requestData.comment = comment; } - // Whether to save first is decided again here, not only when the move - // was pressed: a save core has in flight is waited out rather than - // raced, and the post can become dirty during that wait or while an - // assignee is picked. See decideSave. - let saved = false; - - whenSaveSettles( registry ) - .then( decideSave ) - .then( ( shouldSave ) => { - saved = shouldSave; - - if ( ! saved ) { - return; - } - - // Core's own save controls stand down while saving is locked - // — an upload still in flight, a plugin's pre-publish check — - // but savePost() itself never asks. - if ( editor.isPostSavingLocked() ) { - throw { - code: 'save_locked', - message: __( - 'The post can’t be saved yet. Wait for uploads to finish, then try again.', - 'vip-workflows' - ), - }; - } - - return savePost(); - } ) + saveFirst( + targetIsAiStage + ? __( + 'Could not save the post before starting the AI stage. Try again.', + 'vip-workflows' + ) + : __( + 'Could not save the post before the transition. Try again.', + 'vip-workflows' + ) + ) .then( () => { - // savePost() resolves even when the save request fails (the error - // is recorded in the editor store, meta boxes' included). If it - // failed, or the post is still dirty, the content never - // persisted, so bail rather than send a transition the server - // will judge against a row that is not what the author is - // looking at. - if ( - saved && - ( editor.didPostSaveRequestFail() || - editor.isEditedPostDirty() ) - ) { - throw { - code: 'save_failed', - message: targetIsAiStage - ? __( - 'Could not save the post before starting the AI stage. Try again.', - 'vip-workflows' - ) - : __( - 'Could not save the post before the transition. Try again.', - 'vip-workflows' - ), - }; - } - return apiFetch( { path: `/vip-workflows/v1/workflow/post/${ postId }/transition`, method: 'POST', @@ -918,6 +975,10 @@ export function TransitionFlow() { } sourceRef.current = request.source; + if ( request.rerun ) { + handleRerun(); + return; + } handleTransitionClick( request.transition, request.anchor ); // Only a new request starts a move; the handler is rebuilt every // render and reads the current state when it runs. diff --git a/vip-workflows/src/editor/components/WorkflowHeaderAction.js b/vip-workflows/src/editor/components/WorkflowHeaderAction.js index bcc73fc2..0009c741 100644 --- a/vip-workflows/src/editor/components/WorkflowHeaderAction.js +++ b/vip-workflows/src/editor/components/WorkflowHeaderAction.js @@ -100,8 +100,12 @@ export function WorkflowHeaderAction() { }; }, [] ); const { transitions } = useRequiredMetadataGate(); - const { fetchWorkflowStatus, requestTransition, revertAgentStage } = - useDispatch( STORE_NAME ); + const { + fetchWorkflowStatus, + requestTransition, + revertAgentStage, + requestRerun, + } = useDispatch( STORE_NAME ); const { createErrorNotice, removeNotice } = useDispatch( noticesStore ); // The header is on screen from the first paint, whether or not the @@ -132,18 +136,24 @@ export function WorkflowHeaderAction() { const primary = getPrimaryTransition( transitions ); // A stage whose agent failed withholds its exits, so it has no primary - // transition: its one way out is back where the post came from. The - // server names that stage exactly when it will honor the move. - const revertTo = - ! workflow?.agent_pending && 'failed' === workflow?.agent_job?.status - ? workflow.agent_job.revert_to - : null; + // transition. Its action is to run the agent again, in place, when the + // server says it can; otherwise to go back where the post came from, which + // the server names exactly when it will honor the move. + const agentFailed = + ! workflow?.agent_pending && 'failed' === workflow?.agent_job?.status; + const canRerun = agentFailed && !! workflow.agent_job.can_rerun; + const revertTo = agentFailed ? workflow.agent_job.revert_to : null; + + // While a stage agent runs, the stage withholds its exits too, so there is + // no move to offer. The button stays, busy, for the whole run, rather than + // vanishing between the press that started it and the outcome. + const agentWorking = !! workflow?.agent_pending && ! primary; const shown = onWorkflowPost && !! workflow?.has_workflow && ! workflow.orphaned && - ( !! primary || !! revertTo ); + ( !! primary || agentWorking || canRerun || !! revertTo ); const replaces = shown && replacesCorePublish( workflow, transitions, coreButtonSaves ); const hideCorePublish = replaces && mounted; @@ -164,6 +174,11 @@ export function WorkflowHeaderAction() { const locked = !! primary?._locked; + const runAgain = () => { + removeNotice( HEADER_NOTICE_ID ); + requestRerun( 'header' ); + }; + const goBack = async () => { removeNotice( HEADER_NOTICE_ID ); try { @@ -185,39 +200,76 @@ export function WorkflowHeaderAction() { // down to secondary so the two never compete. const variant = replaces ? 'primary' : 'secondary'; - const main = primary ? ( - - ) : ( - - ); + // The main half: the primary move; while a stage agent runs, a busy + // stand-in; on a failed AI stage, Run again when the server offers it and + // Go back otherwise. + let main; + if ( primary ) { + main = ( + + ); + } else if ( agentWorking ) { + main = ( + + ); + } else if ( canRerun ) { + main = ( + + ); + } else { + main = ( + + ); + } return ( diff --git a/vip-workflows/src/editor/components/WorkflowPanel.js b/vip-workflows/src/editor/components/WorkflowPanel.js index ac7f5fb7..832c22f9 100644 --- a/vip-workflows/src/editor/components/WorkflowPanel.js +++ b/vip-workflows/src/editor/components/WorkflowPanel.js @@ -198,6 +198,7 @@ export function WorkflowPanel() { fetchWorkflowStatus, requestTransition, revertAgentStage, + requestRerun, setWorkflowWriting, setTransitionError, } = useDispatch( STORE_NAME ); @@ -234,10 +235,13 @@ export function WorkflowPanel() { const handleTransitionClick = ( transition, anchor = null ) => requestTransition( transition, anchor, 'panel' ); - // The failed AI stage's one action: return the post to the stage it came - // from. Retrying the agent is going forward again — entering the stage - // re-dispatches it — so there is no separate re-run. The store runs it, so - // the header's own Go back and this one are the same move. + // The failed AI stage's two actions. Run again retries the agent in place, + // started by — and so acting as — whoever presses it; the transition flow + // runs it, saving unsaved edits first, as it does before any move into an + // AI stage. Go back returns the post to the stage it came from. Both are + // shared with the header's button, so they are the same moves. + const handleAgentRerun = () => requestRerun( 'panel' ); + const handleAgentRevert = async () => { clearErrors(); try { @@ -484,11 +488,12 @@ export function WorkflowPanel() { ) } - { /* AI stage failed: surface the error, and offer the one exit a - failed stage has — back the way the post came. The server names - the destination (agent_job.revert_to) exactly when it will honor - the move; without it the stage's routed transitions are released - instead and the rail below carries them, so no button here. */ } + { /* AI stage failed: surface the error and its two actions. Run + again retries in place when the job allows it (can_rerun). Go + back returns the post the way it came; the server names that + destination (agent_job.revert_to) exactly when it will honor the + move. Without either, the stage's routed transitions are + released and the rail below carries them. */ } { ! agentPending && agentFailed && ( // wpds-allow R7 -- error surface (background + border + radius) whose title, error line and button sit at three different distances; draws none of the three and has one uniform gap.
@@ -511,20 +516,42 @@ export function WorkflowPanel() { { agentJob.error } ) } - { agentJob?.revert_to && ( - + ) } + { agentJob?.revert_to && ( + ) } - + ) }
) } @@ -555,7 +582,8 @@ export function WorkflowPanel() { agent works AND while it sits failed with a go-back available (StatusManager::agent_owns_stage_exits) — the rail renders the sequence's routed outcomes in their place, and the failed - state's exit is the Go back button above. Only a failure whose + state's ways out are the Run again and Go back buttons above. + Only a failure whose origin cannot be resolved releases the routed transitions here, so a failed agent never strands the post. diff --git a/vip-workflows/src/editor/store.js b/vip-workflows/src/editor/store.js index 61cc5012..1e420463 100644 --- a/vip-workflows/src/editor/store.js +++ b/vip-workflows/src/editor/store.js @@ -198,6 +198,22 @@ const actions = { }; }, + /** + * Ask the transition flow to run this post's failed stage agent again. + * + * Through the flow rather than straight to the server, so the author's + * unsaved edits are saved first, as they are before a move into an AI + * stage: the agent reads the stored post. + * + * @param {string} source 'panel' or 'header' — where a refusal is reported. + */ + requestRerun( source = 'panel' ) { + return { + type: 'REQUEST_TRANSITION', + request: { rerun: true, source }, + }; + }, + /** * Mark the pending request as taken by the transition flow. */ @@ -392,6 +408,54 @@ const actions = { dispatch.receiveWorkflowStatus( status ); refreshPostEntity( registry, select.getPostType(), postId ); + } catch ( error ) { + // As with Run again: a refusal (someone else ran it again or + // took it back first) means the failed state on screen is + // stale, so re-read it before the caller reports the error. + await dispatch.fetchWorkflowStatus(); + throw error; + } finally { + dispatch.setTransitioningTo( null ); + } + }, + + /** + * Run this post's failed stage agent again, in place. + * + * Run by the transition flow (see requestRerun), after it has saved the + * post, for the workflow panel and the header button alike, whenever the + * failed job says it can run again (`agent_job.can_rerun`). The run is + * started by the person who asks, so it acts as them when they can edit + * the post. It holds the current stage's key as the move in flight, so + * both surfaces stand down together. On a refusal it re-reads the post, + * then rejects with the server's error. + */ + rerunAgentStage: + () => + async ( { dispatch, select } ) => { + const postId = select.getPostId(); + + dispatch.setTransitioningTo( + select.getWorkflowStatus()?.current?.key ?? null + ); + + try { + // The response is the status payload with the new pending + // job. The post stays where it is, so the editor's own record + // has nothing to re-read. + const status = await apiFetch( { + path: `/vip-workflows/v1/workflow/post/${ postId }/agent-rerun`, + method: 'POST', + } ); + + dispatch.receiveWorkflowStatus( status ); + } catch ( error ) { + // A refusal is news about the post: someone else ran it again + // or took it back, so the failed state on screen is stale. + // Re-read it, so the panel and header offer what the post + // allows now, then let the caller report the error. + await dispatch.fetchWorkflowStatus(); + throw error; } finally { dispatch.setTransitioningTo( null ); } diff --git a/vip-workflows/src/editor/style.css b/vip-workflows/src/editor/style.css index 2a43694f..b1934e02 100644 --- a/vip-workflows/src/editor/style.css +++ b/vip-workflows/src/editor/style.css @@ -240,7 +240,7 @@ the shared . */ /* Failure notice. A plain surface, not a Stack: its title, error line and - Go back button sit at three different distances. */ + actions (Run again, Go back) sit at three different distances. */ .vip-workflows-panel__agent-failed { padding: var(--wpds-dimension-padding-md); /* wpds-allow R3 -- sets this notice apart from the panel rows above and below, on top of the panel Stack's uniform gap. */ @@ -258,7 +258,7 @@ } .vip-workflows-panel__agent-failed-error { - /* wpds-allow R3 -- distance to the Go back button below; the notice is a plain surface, not a Stack (see above). */ + /* wpds-allow R3 -- distance to the actions below; the notice is a plain surface, not a Stack (see above). */ margin: 0 0 0.5rem; /* The on this element cannot deliver its own size here: the editor bundle has no counterpart to the `revert-layer` reset in diff --git a/vip-workflows/tests/e2e/agent-stages.spec.js b/vip-workflows/tests/e2e/agent-stages.spec.js index ee461cfc..2b323b62 100644 --- a/vip-workflows/tests/e2e/agent-stages.spec.js +++ b/vip-workflows/tests/e2e/agent-stages.spec.js @@ -17,12 +17,12 @@ * agent's AI call always fails. The suite's sequence routes * no `error` destination (the error path is opt-in), so the * post stays in the AI stage and the editor surfaces the - * error + a "Go back to Draft" action wired to the - * agent-revert endpoint — the stage's own transitions stay + * error + "Run again" (agent-rerun) and "Go back to Draft" + * (agent-revert) actions — the stage's own transitions stay * withheld. * 4. Go back — reverting a failed agent returns the post to the stage it - * entered from; re-entering the AI stage is how a run is - * retried. + * entered from. Running it again in place is the other + * way out. * 5. Error route — a stage that DOES route `error` sends the errored run * along it instead of failing in place. * @@ -120,8 +120,8 @@ test.describe( 'VIP Workflows — stage agents', () => { // the sequence's routed outcomes in their place — labelled, but never // clickable. Not offering an edge is not refusing it — transition() // still confirms for a caller who means it. If the run fails, the - // exits STAY withheld: the failed state's one action is the panel's - // "Go back" button. + // exits STAY withheld: the failed state's actions are the panel's + // "Run again" and "Go back" buttons. await expect( panel.locator( '.vip-workflows-rail__actions button:not([aria-disabled="true"])' diff --git a/vip-workflows/tests/phpunit/Integration/AgentRunsAsStarterIntegrationTest.php b/vip-workflows/tests/phpunit/Integration/AgentRunsAsStarterIntegrationTest.php new file mode 100644 index 00000000..6b3cc2c2 --- /dev/null +++ b/vip-workflows/tests/phpunit/Integration/AgentRunsAsStarterIntegrationTest.php @@ -0,0 +1,581 @@ +editor_id = (int) self::factory()->user->create( array( 'role' => 'editor' ) ); + wp_set_current_user( $this->editor_id ); + + // Every stage in the draft region, so no crossing or publication hold + // gets in the way of the question under test. + $this->sequence_id = (int) ( new SequenceRepository() )->create( + 'Agent Runs As Flow', + 'agent-runs-as-flow', + '', + array( + 'post_types' => array( 'post' ), + 'statuses' => array( + array( + 'key' => 'drafting', + 'label' => 'Drafting', + 'status' => 'draft', + 'transitions' => array( + array( + 'to' => 'ai_desk', + 'label' => 'Send to agent', + ), + ), + ), + array( + 'key' => 'ai_desk', + 'label' => 'AI Desk', + 'status' => 'draft', + 'agent' => array( + 'ability_id' => 'test/desk-agent', + 'routing' => array( 'pass' => 'review' ), + ), + 'transitions' => array( + array( + 'to' => 'review', + 'label' => 'Review', + ), + array( + 'to' => 'drafting', + 'label' => 'Back', + ), + ), + ), + array( + 'key' => 'review', + 'label' => 'Review', + 'status' => 'draft', + 'transitions' => array( + array( + 'to' => 'ai_desk', + 'label' => 'Back to the agent', + ), + ), + ), + ), + ), + get_current_user_id() + ); + } + + public function tear_down(): void + { + wp_clear_scheduled_hook( StageAgentRunner::RUN_HOOK ); + parent::tear_down(); + } + + /** + * A draft in Drafting, authored by a user with the given role. + * + * @param string $author_role Role of the post's author. + * @return array{0:int,1:int} Post ID and author ID. + */ + private function make_post( string $author_role ): array + { + $author_id = (int) self::factory()->user->create( array( 'role' => $author_role ) ); + $post_id = (int) self::factory()->post->create( + array( + 'post_status' => 'draft', + 'post_author' => $author_id, + ) + ); + update_post_meta( $post_id, StatusManager::SEQUENCE_META_KEY, $this->sequence_id ); + update_post_meta( $post_id, StatusManager::STAGE_META_KEY, 'drafting' ); + + return array( $post_id, $author_id ); + } + + /** + * An executor that records who it ran as and returns a pass verdict. + * + * @return AbilityExecutor + */ + private function recording_executor(): AbilityExecutor + { + return new class() extends AbilityExecutor { + /** + * The current user while execute() ran, or null if it never did. + * + * @var int|null + */ + public ?int $ran_as = null; + + public function execute( string $ability_name, array $input = array(), string $context = '', string $source = 'rest' ): AbilityResult { + $this->ran_as = get_current_user_id(); + + $result = new AbilityResult(); + $result->success = true; + $result->output = array( 'status' => 'pass' ); + return $result; + } + }; + } + + /** + * Run the queued agent the way cron does: with nobody logged in. + * + * @param AbilityExecutor $executor Executor to run with. + * @param int $post_id Post ID. + */ + private function run_as_cron( AbilityExecutor $executor, int $post_id ): void + { + wp_set_current_user( 0 ); + ( new StageAgentRunner( $executor ) )->run_stage_agent( $post_id, 'ai_desk' ); + } + + /** + * An editor moves a subscriber's post into an AI stage: the run acts as the + * editor, executes, and routes on its verdict instead of stopping for want + * of a capable author. + */ + public function test_an_editors_move_runs_the_agent_as_the_editor(): void + { + list( $post_id ) = $this->make_post( 'subscriber' ); + + $moved = Plugin::get_instance()->get_status_manager()->transition( $post_id, 'ai_desk' ); + $this->assertTrue( $moved, 'The editor may move the post into the AI stage.' ); + + $job = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + $this->assertSame( $this->editor_id, (int) $job['started_by'], 'The move records the editor as the run\'s starter.' ); + + $executor = $this->recording_executor(); + $this->run_as_cron( $executor, $post_id ); + + $this->assertSame( $this->editor_id, $executor->ran_as, 'The agent acts as the editor who moved the post in.' ); + $this->assertSame( 'review', get_post_meta( $post_id, StatusManager::STAGE_META_KEY, true ), 'The pass verdict routes the post on.' ); + $this->assertSame( 0, get_current_user_id(), 'The cron context is restored afterwards.' ); + } + + /** + * A starter who loses the right to edit the post before the run fires is not + * borrowed: the run falls back to an author who can edit posts. + */ + public function test_a_starter_who_lost_the_right_falls_back_to_the_author(): void + { + list( $post_id, $author_id ) = $this->make_post( 'author' ); + + $this->assertTrue( Plugin::get_instance()->get_status_manager()->transition( $post_id, 'ai_desk' ) ); + + // Demoted between the move and the run. + ( new \WP_User( $this->editor_id ) )->set_role( 'subscriber' ); + + $executor = $this->recording_executor(); + $this->run_as_cron( $executor, $post_id ); + + $this->assertSame( $author_id, $executor->ran_as, 'The run acts as the author, not the demoted starter.' ); + } + + /** + * A run nobody started, on a post whose author cannot edit posts, still + * refuses in place rather than borrowing anyone. + */ + public function test_a_run_nobody_started_still_refuses_for_an_incapable_author(): void + { + list( $post_id ) = $this->make_post( 'subscriber' ); + update_post_meta( $post_id, StatusManager::STAGE_META_KEY, 'ai_desk' ); + update_post_meta( + $post_id, + StageAgentRunner::JOB_META, + array( + 'stage_key' => 'ai_desk', + 'ability_id' => 'test/desk-agent', + 'status' => 'pending', + 'queued_at' => current_time( 'mysql' ), + 'cause' => 'core', + 'from_stage' => 'drafting', + 'started_by' => 0, + ) + ); + + $executor = $this->recording_executor(); + $this->run_as_cron( $executor, $post_id ); + + $this->assertNull( $executor->ran_as, 'The agent must not execute.' ); + $job = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + $this->assertSame( 'failed', $job['status'] ); + $this->assertSame( 'ai_desk', get_post_meta( $post_id, StatusManager::STAGE_META_KEY, true ), 'It stops in place.' ); + } + + /** + * The failure above is fixed in place: an editor presses Run again, the post + * never leaves its stage, and the fresh run acts as the editor and routes on + * its verdict. + */ + public function test_run_again_by_an_editor_fixes_a_run_nobody_could_act_for(): void + { + list( $post_id ) = $this->make_post( 'subscriber' ); + update_post_meta( $post_id, StatusManager::STAGE_META_KEY, 'ai_desk' ); + update_post_meta( + $post_id, + StageAgentRunner::JOB_META, + array( + 'stage_key' => 'ai_desk', + 'ability_id' => 'test/desk-agent', + 'status' => 'pending', + 'queued_at' => current_time( 'mysql' ), + 'cause' => 'core', + 'from_stage' => 'drafting', + 'started_by' => 0, + ) + ); + $this->run_as_cron( $this->recording_executor(), $post_id ); + $this->assertSame( 'failed', get_post_meta( $post_id, StageAgentRunner::JOB_META, true )['status'] ); + + // The editor presses Run again, through the route the editor calls. + wp_set_current_user( $this->editor_id ); + $request = new \WP_REST_Request( 'POST', "/vip-workflows/v1/workflow/post/{$post_id}/agent-rerun" ); + $response = rest_do_request( $request ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertTrue( (bool) $response->get_data()['agent_pending'], 'The status payload shows the new run pending.' ); + $this->assertSame( 'ai_desk', get_post_meta( $post_id, StatusManager::STAGE_META_KEY, true ), 'The post never left its stage.' ); + $job = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + $this->assertSame( $this->editor_id, $job['started_by'] ); + $this->assertSame( 'drafting', $job['from_stage'] ); + + $executor = $this->recording_executor(); + $this->run_as_cron( $executor, $post_id ); + + $this->assertSame( $this->editor_id, $executor->ran_as, 'The re-run acts as the editor who pressed it.' ); + $this->assertSame( 'review', get_post_meta( $post_id, StatusManager::STAGE_META_KEY, true ), 'And routes on its verdict.' ); + } + + /** + * Run again is refused when there is no failed run to retry. + */ + public function test_run_again_is_refused_without_a_failed_run(): void + { + list( $post_id ) = $this->make_post( 'editor' ); + + $request = new \WP_REST_Request( 'POST', "/vip-workflows/v1/workflow/post/{$post_id}/agent-rerun" ); + $response = rest_do_request( $request ); + + $this->assertSame( 409, $response->get_status() ); + $this->assertSame( 'no_agent_rerun', $response->get_data()['code'] ); + } + + /** + * Failed run in a stage, Go back, then a Run again request that read the + * failed marker before Go back deleted it. The stale write must not land: + * no marker is created and no run is queued, so re-entering the stage later + * cannot pick up a stale identity. + */ + public function test_a_stale_run_again_after_go_back_writes_and_queues_nothing(): void + { + list( $post_id ) = $this->make_post( 'subscriber' ); + update_post_meta( $post_id, StatusManager::STAGE_META_KEY, 'ai_desk' ); + $failed = array( + 'stage_key' => 'ai_desk', + 'ability_id' => 'test/desk-agent', + 'status' => 'failed', + 'error' => 'x', + 'failed_at' => current_time( 'mysql' ), + 'from_stage' => 'drafting', + ); + update_post_meta( $post_id, StageAgentRunner::JOB_META, $failed ); + $stale = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + + // Go back wins the race. + $back = rest_do_request( new \WP_REST_Request( 'POST', "/vip-workflows/v1/workflow/post/{$post_id}/agent-revert" ) ); + $this->assertSame( 200, $back->get_status() ); + $this->assertSame( '', get_post_meta( $post_id, StageAgentRunner::JOB_META, true ) ); + wp_clear_scheduled_hook( StageAgentRunner::RUN_HOOK ); + + // The stale Run again now tries its conditional write. + $dispatch = new \ReflectionMethod( StageAgentRunner::class, 'dispatch' ); + $written = $dispatch->invoke( new StageAgentRunner(), $post_id, 'ai_desk', 'test/desk-agent', 'drafting', 'rerun', $this->editor_id, $stale ); + + $this->assertFalse( $written ); + $this->assertSame( '', get_post_meta( $post_id, StageAgentRunner::JOB_META, true ), 'No marker was created.' ); + $this->assertFalse( wp_next_scheduled( StageAgentRunner::RUN_HOOK, array( $post_id, 'ai_desk' ) ), 'No run was queued.' ); + } + + /** + * Two Run again requests that read the same failed marker: one wins, the + * other is refused, against the real database. + */ + public function test_two_racing_run_agains_only_one_wins(): void + { + list( $post_id ) = $this->make_post( 'subscriber' ); + update_post_meta( $post_id, StatusManager::STAGE_META_KEY, 'ai_desk' ); + update_post_meta( + $post_id, + StageAgentRunner::JOB_META, + array( + 'stage_key' => 'ai_desk', + 'ability_id' => 'test/desk-agent', + 'status' => 'failed', + 'error' => 'x', + 'failed_at' => current_time( 'mysql' ), + 'from_stage' => 'drafting', + ) + ); + $read = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + + $dispatch = new \ReflectionMethod( StageAgentRunner::class, 'dispatch' ); + $first = $dispatch->invoke( new StageAgentRunner(), $post_id, 'ai_desk', 'test/desk-agent', 'drafting', 'rerun', $this->editor_id, $read ); + $second = $dispatch->invoke( new StageAgentRunner(), $post_id, 'ai_desk', 'test/desk-agent', 'drafting', 'rerun', 1, $read ); + + $this->assertTrue( $first ); + $this->assertFalse( $second ); + $job = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + $this->assertSame( 'pending', $job['status'] ); + $this->assertSame( $this->editor_id, $job['started_by'], 'The first writer stands.' ); + } + + /** + * An abandoned entry's identity does not survive a re-entry. An editor moves + * a contributor's post into the AI stage, then confirms a move out before + * the run fires. The contributor moves it back in: the fresh marker, and + * the run, belong to the contributor. + */ + public function test_re_entry_replaces_an_abandoned_entrys_identity(): void + { + list( $post_id, $author_id ) = $this->make_post( 'contributor' ); + $status_manager = Plugin::get_instance()->get_status_manager(); + + $this->assertTrue( $status_manager->transition( $post_id, 'ai_desk' ) ); + $this->assertTrue( + $status_manager->transition( $post_id, 'review', array( 'acknowledge_warnings' => true ) ), + 'The editor confirms a move out while the run is pending.' + ); + $this->assertSame( $this->editor_id, (int) get_post_meta( $post_id, StageAgentRunner::JOB_META, true )['started_by'], 'The abandoned marker is still there.' ); + + wp_set_current_user( $author_id ); + $this->assertTrue( $status_manager->transition( $post_id, 'ai_desk' ), 'The contributor moves it back in.' ); + + $job = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + $this->assertSame( 'pending', $job['status'] ); + $this->assertSame( $author_id, (int) $job['started_by'], 'The re-entry records the contributor, not the editor.' ); + $this->assertSame( 'review', $job['from_stage'], 'Go back now leads where this entry came from.' ); + + $executor = $this->recording_executor(); + $this->run_as_cron( $executor, $post_id ); + + $this->assertSame( $author_id, $executor->ran_as, 'The run acts as the contributor.' ); + } + + /** + * Run again keeps the sequence's role rules. Only editors may move posts + * into the AI stage; after an editor's run fails, a contributor who can + * edit the post is still refused, and is not offered the button. + */ + public function test_run_again_keeps_the_entry_moves_role_rules(): void + { + $sequence_id = (int) ( new SequenceRepository() )->create( + 'Editors Only Agent Flow', + 'editors-only-agent-flow', + '', + array( + 'post_types' => array( 'post' ), + 'statuses' => array( + array( + 'key' => 'drafting', + 'label' => 'Drafting', + 'status' => 'draft', + 'transitions' => array( + array( + 'to' => 'ai_desk', + 'label' => 'Send to agent', + 'allowed_roles' => array( 'editor' ), + ), + ), + ), + array( + 'key' => 'ai_desk', + 'label' => 'AI Desk', + 'status' => 'draft', + 'agent' => array( + 'ability_id' => 'test/desk-agent', + 'routing' => array( 'pass' => 'review' ), + ), + 'transitions' => array( + array( + 'to' => 'review', + 'label' => 'Review', + ), + ), + ), + array( + 'key' => 'review', + 'label' => 'Review', + 'status' => 'draft', + 'transitions' => array(), + ), + ), + ), + $this->editor_id + ); + + list( $post_id, $author_id ) = $this->make_post( 'contributor' ); + update_post_meta( $post_id, StatusManager::SEQUENCE_META_KEY, $sequence_id ); + update_post_meta( $post_id, StatusManager::STAGE_META_KEY, 'ai_desk' ); + update_post_meta( + $post_id, + StageAgentRunner::JOB_META, + array( + 'stage_key' => 'ai_desk', + 'ability_id' => 'test/desk-agent', + 'status' => 'failed', + 'error' => 'x', + 'failed_at' => current_time( 'mysql' ), + 'from_stage' => 'drafting', + ) + ); + + wp_set_current_user( $author_id ); + $status = rest_do_request( new \WP_REST_Request( 'GET', "/vip-workflows/v1/workflow/post/{$post_id}/status" ) ); + $this->assertSame( 200, $status->get_status() ); + $this->assertFalse( $status->get_data()['agent_job']['can_rerun'], 'The contributor is not offered Run again.' ); + + $response = rest_do_request( new \WP_REST_Request( 'POST', "/vip-workflows/v1/workflow/post/{$post_id}/agent-rerun" ) ); + $this->assertSame( 403, $response->get_status() ); + $this->assertSame( 'forbidden_transition', $response->get_data()['code'] ); + $this->assertSame( 'failed', get_post_meta( $post_id, StageAgentRunner::JOB_META, true )['status'], 'Nothing was dispatched.' ); + + // A reseat records the stage the post sat in, with no authored edge from + // it into the AI stage: any authored move in decides, so the role rule + // still holds rather than shutting everyone out. + $sequence = ( new SequenceRepository() )->find( $sequence_id ); + $this->assertTrue( StageAgentRunner::user_can_rerun( $sequence, 'ai_desk', 'review', $this->editor_id ), 'After a reseat, an editor may run it again.' ); + $this->assertFalse( StageAgentRunner::user_can_rerun( $sequence, 'ai_desk', 'review', $author_id ), 'After a reseat, a contributor still may not.' ); + $admin_id = (int) self::factory()->user->create( array( 'role' => 'administrator' ) ); + $this->assertTrue( StageAgentRunner::user_can_rerun( $sequence, 'ai_desk', 'drafting', $admin_id ), 'The bypass list skips the role rule.' ); + + wp_set_current_user( $this->editor_id ); + $status = rest_do_request( new \WP_REST_Request( 'GET', "/vip-workflows/v1/workflow/post/{$post_id}/status" ) ); + $this->assertTrue( $status->get_data()['agent_job']['can_rerun'], 'An editor is offered Run again.' ); + $this->assertSame( 200, rest_do_request( new \WP_REST_Request( 'POST', "/vip-workflows/v1/workflow/post/{$post_id}/agent-rerun" ) )->get_status() ); + } + + /** + * Run again wins the race against a Go back that read the same failed + * marker: Go back is refused and the post stays at the AI stage with the + * new run pending, rather than landing at the origin with a run queued for + * the stage it left. + */ + public function test_go_back_loses_to_a_run_again_that_took_the_marker_first(): void + { + list( $post_id ) = $this->make_post( 'subscriber' ); + update_post_meta( $post_id, StatusManager::STAGE_META_KEY, 'ai_desk' ); + update_post_meta( + $post_id, + StageAgentRunner::JOB_META, + array( + 'stage_key' => 'ai_desk', + 'ability_id' => 'test/desk-agent', + 'status' => 'failed', + 'error' => 'x', + 'failed_at' => current_time( 'mysql' ), + 'from_stage' => 'drafting', + ) + ); + $stale = get_post_meta( $post_id, StageAgentRunner::JOB_META, true ); + + $this->assertSame( 200, rest_do_request( new \WP_REST_Request( 'POST', "/vip-workflows/v1/workflow/post/{$post_id}/agent-rerun" ) )->get_status() ); + + // Go back's own compare-and-delete, with the marker it read before. + $this->assertFalse( StageAgentRunner::take_job_marker( $post_id, $stale ) ); + + // And through the route: nothing failed is left to go back from. + $back = rest_do_request( new \WP_REST_Request( 'POST', "/vip-workflows/v1/workflow/post/{$post_id}/agent-revert" ) ); + $this->assertSame( 409, $back->get_status() ); + $this->assertSame( 'ai_desk', get_post_meta( $post_id, StatusManager::STAGE_META_KEY, true ), 'The post stays at the AI stage.' ); + $this->assertSame( 'pending', get_post_meta( $post_id, StageAgentRunner::JOB_META, true )['status'], 'With the new run pending.' ); + } + + /** + * A late cron can hold two run events for one post and stage. The one that + * fires after the first has already failed in place must not execute the + * agent again. + */ + public function test_a_second_event_does_not_run_against_a_resolved_marker(): void + { + list( $post_id ) = $this->make_post( 'editor' ); + update_post_meta( $post_id, StatusManager::STAGE_META_KEY, 'ai_desk' ); + $failed = array( + 'stage_key' => 'ai_desk', + 'ability_id' => 'test/desk-agent', + 'status' => 'failed', + 'error' => 'x', + 'failed_at' => current_time( 'mysql' ), + 'from_stage' => 'drafting', + ); + update_post_meta( $post_id, StageAgentRunner::JOB_META, $failed ); + + $executor = $this->recording_executor(); + $this->run_as_cron( $executor, $post_id ); + + $this->assertNull( $executor->ran_as, 'The agent does not run again.' ); + $this->assertSame( $failed, get_post_meta( $post_id, StageAgentRunner::JOB_META, true ), 'The failed state is left as it was.' ); + $this->assertSame( 'ai_desk', get_post_meta( $post_id, StatusManager::STAGE_META_KEY, true ) ); + } + + /** + * Go back holds the marker as `reverting` while it moves the post, so a + * late run event firing in that window doesn't run the agent either. + */ + public function test_a_run_event_during_go_back_does_not_execute(): void + { + list( $post_id ) = $this->make_post( 'editor' ); + update_post_meta( $post_id, StatusManager::STAGE_META_KEY, 'ai_desk' ); + update_post_meta( + $post_id, + StageAgentRunner::JOB_META, + array( + 'stage_key' => 'ai_desk', + 'ability_id' => 'test/desk-agent', + 'status' => 'reverting', + 'from_stage' => 'drafting', + 'reverting_at' => time(), + ) + ); + + $executor = $this->recording_executor(); + $this->run_as_cron( $executor, $post_id ); + + $this->assertNull( $executor->ran_as ); + } +} diff --git a/vip-workflows/tests/phpunit/Unit/StageAgentRunnerDispatchTest.php b/vip-workflows/tests/phpunit/Unit/StageAgentRunnerDispatchTest.php index fe911e08..82fdef87 100644 --- a/vip-workflows/tests/phpunit/Unit/StageAgentRunnerDispatchTest.php +++ b/vip-workflows/tests/phpunit/Unit/StageAgentRunnerDispatchTest.php @@ -34,6 +34,9 @@ protected function setUp(): void // The person whose move entered the stage. Functions\when( 'get_current_user_id' )->justReturn( 5 ); + + // Not on the bypass list. + Functions\when( 'get_userdata' )->justReturn( false ); } /** @@ -49,6 +52,44 @@ private function sequence_with_status( ?array $status ): object return $sequence; } + /** + * Mark an agent exit transition as in progress for a post. + * + * @param int $post_id The exiting run's post. + * @param int $started_by The exiting run's starter. + */ + private function exiting_run( int $post_id, int $started_by ): void + { + ( new \ReflectionProperty( StageAgentRunner::class, 'exiting_run' ) )->setValue( + null, + array( + 'post_id' => $post_id, + 'started_by' => $started_by, + ) + ); + } + + /** + * Mock $wpdb for the rerun compare-and-swap. + * + * @param int|false $rows Rows the conditional UPDATE reports changed. + * @param array $seen Receives the update's data and where clauses. + */ + private function wpdb_replacing( $rows, ?array &$seen = null ): void + { + global $wpdb; + $wpdb = Mockery::mock( 'wpdb' ); + $wpdb->postmeta = 'wp_postmeta'; + $wpdb->shouldReceive( 'update' )->andReturnUsing( + function ( $table, $data, $where ) use ( $rows, &$seen ) { + $seen = array( 'table' => $table, 'data' => $data, 'where' => $where ); + return $rows; + } + ); + Functions\when( 'wp_cache_delete' )->justReturn( true ); + Functions\when( 'maybe_serialize' )->alias( 'serialize' ); + } + /** * Entering an AI stage writes a pending job marker and schedules the run hook. */ @@ -108,7 +149,7 @@ function ( $post_id, $key, $value ) use ( &$captured ) { ); Functions\when( 'wp_schedule_single_event' )->justReturn( true ); - ( new \ReflectionProperty( StageAgentRunner::class, 'exiting_run_started_by' ) )->setValue( null, 3 ); + $this->exiting_run( 42, 3 ); $sequence = $this->sequence_with_status( array( @@ -122,6 +163,133 @@ function ( $post_id, $key, $value ) use ( &$captured ) { $this->assertSame( 3, $captured['started_by'] ); } + /** + * A hop dispatched while some other user is logged in (cron run with + * `--user`, or a user an earlier callback left set) still belongs to the + * chain's starter. The ambient user authorized nothing. + */ + public function test_a_hop_ignores_an_ambient_user_and_keeps_the_chain_starter(): void + { + $captured = null; + Functions\when( 'get_current_user_id' )->justReturn( 1 ); // an administrator, ambient + Functions\when( 'get_post_meta' )->justReturn( '' ); + Functions\when( 'delete_post_meta' )->justReturn( true ); + Functions\when( 'update_post_meta' )->alias( + function ( $post_id, $key, $value ) use ( &$captured ) { + $captured = $value; + return true; + } + ); + Functions\when( 'wp_schedule_single_event' )->justReturn( true ); + + $this->exiting_run( 42, 3 ); + + $sequence = $this->sequence_with_status( + array( + 'key' => 'ai_desk', + 'agent' => array( 'ability_id' => 'test/agent', 'routing' => array() ), + ) + ); + + $this->runner->maybe_dispatch( 42, 'ai_desk', 'other_ai_desk', $sequence ); + + $this->assertSame( 3, $captured['started_by'], 'the chain starter, not the ambient administrator' ); + } + + /** + * A chain nobody started stays nobody's, even with an ambient user, so the + * next stage falls back to the author rather than borrowing that user. + */ + public function test_a_hop_from_a_chain_nobody_started_does_not_borrow_an_ambient_user(): void + { + $captured = null; + Functions\when( 'get_current_user_id' )->justReturn( 1 ); + Functions\when( 'get_post_meta' )->justReturn( '' ); + Functions\when( 'delete_post_meta' )->justReturn( true ); + Functions\when( 'update_post_meta' )->alias( + function ( $post_id, $key, $value ) use ( &$captured ) { + $captured = $value; + return true; + } + ); + Functions\when( 'wp_schedule_single_event' )->justReturn( true ); + + $this->exiting_run( 42, 0 ); + + $sequence = $this->sequence_with_status( + array( + 'key' => 'ai_desk', + 'agent' => array( 'ability_id' => 'test/agent', 'routing' => array() ), + ) + ); + + $this->runner->maybe_dispatch( 42, 'ai_desk', 'other_ai_desk', $sequence ); + + $this->assertSame( 0, $captured['started_by'] ); + } + + /** + * A callback inside one post's agent exit can move ANOTHER post into an AI + * stage. That post's run does not borrow the exiting run's starter. + */ + public function test_a_nested_dispatch_for_another_post_does_not_borrow_the_exiting_starter(): void + { + $captured = null; + Functions\when( 'get_current_user_id' )->justReturn( 0 ); + Functions\when( 'get_post_meta' )->justReturn( '' ); + Functions\when( 'delete_post_meta' )->justReturn( true ); + Functions\when( 'update_post_meta' )->alias( + function ( $post_id, $key, $value ) use ( &$captured ) { + $captured = $value; + return true; + } + ); + Functions\when( 'wp_schedule_single_event' )->justReturn( true ); + + $this->exiting_run( 7, 3 ); // post 7's agent is exiting, started by user 3 + + $sequence = $this->sequence_with_status( + array( + 'key' => 'ai_desk', + 'agent' => array( 'ability_id' => 'test/agent', 'routing' => array() ), + ) + ); + + $this->runner->maybe_dispatch( 42, 'ai_desk', 'draft', $sequence ); + + $this->assertSame( 0, $captured['started_by'], 'post 42 is not post 7; its run is nobody\'s' ); + } + + /** + * Under cron, nobody moved the post, whoever happens to be logged in. + */ + public function test_a_dispatch_under_cron_ignores_an_ambient_user(): void + { + $captured = null; + Functions\when( 'wp_doing_cron' )->justReturn( true ); + Functions\when( 'get_current_user_id' )->justReturn( 1 ); + Functions\when( 'get_post_meta' )->justReturn( '' ); + Functions\when( 'delete_post_meta' )->justReturn( true ); + Functions\when( 'update_post_meta' )->alias( + function ( $post_id, $key, $value ) use ( &$captured ) { + $captured = $value; + return true; + } + ); + Functions\when( 'wp_schedule_single_event' )->justReturn( true ); + + $sequence = $this->sequence_with_status( + array( + 'key' => 'ai_desk', + 'agent' => array( 'ability_id' => 'test/agent', 'routing' => array() ), + ) + ); + + $this->runner->maybe_dispatch( 42, 'ai_desk', 'draft', $sequence, array( 'cause' => 'core' ) ); + + $this->assertSame( 0, $captured['started_by'] ); + } + /** * When the run cannot be scheduled, the job is not left pending: it fails * in place so the editor surfaces the error and a Re-run action. @@ -271,20 +439,35 @@ public function test_dispatch_is_noop_when_status_unchanged(): void } /** - * Re-entering the same AI stage while a job is already pending does not - * schedule a second job. + * Re-entering the same AI stage while an earlier entry's job is still + * pending writes a fresh marker for this entry. The abandoned entry's + * starter and origin don't carry over; only the cron event is deduplicated. */ - public function test_dispatch_does_not_double_schedule_when_pending(): void + public function test_re_entry_over_a_pending_marker_writes_a_fresh_one(): void { Functions\when( 'get_post_meta' )->justReturn( array( 'stage_key' => 'ai_desk', 'status' => 'pending', 'ability_id' => 'workflow-agent-reformat-to-template/reformat-to-template', + 'from_stage' => 'review', + 'started_by' => 9, ) ); - Functions\expect( 'update_post_meta' )->never(); - Functions\expect( 'wp_schedule_single_event' )->never(); + Functions\when( 'wp_doing_cron' )->justReturn( false ); + $writes = array(); + Functions\when( 'update_post_meta' )->alias( + function ( $post_id, $key, $value ) use ( &$writes ) { + if ( StageAgentRunner::JOB_META === $key ) { + $writes[] = $value; + } + return true; + } + ); + Functions\when( 'delete_post_meta' )->justReturn( true ); + Functions\when( 'wp_schedule_single_event' )->justReturn( + new \WP_Error( 'duplicate_event', 'A duplicate event already exists.' ) + ); $sequence = $this->sequence_with_status( array( @@ -297,6 +480,269 @@ public function test_dispatch_does_not_double_schedule_when_pending(): void ); $this->runner->maybe_dispatch( 42, 'ai_desk', 'draft', $sequence ); - $this->addToAssertionCount( 1 ); + $this->assertCount( 1, $writes ); + $this->assertSame( 'pending', $writes[0]['status'] ); + $this->assertSame( 5, $writes[0]['started_by'], 'the person making this entry, not the earlier one' ); + $this->assertSame( 'draft', $writes[0]['from_stage'], 'Go back leads where this entry came from' ); + } + + /** + * Run again keeps the post at its stage and dispatches a fresh run started + * by the person asking, keeping the go-back origin and restarting the chain. + */ + public function test_rerun_dispatches_a_fresh_run_started_by_the_person_asking(): void + { + Functions\when( 'get_post_meta' )->alias( + static function ( $post_id, $key ) { + if ( '_vip_workflows_current_stage_key' === $key ) { + return 'ai_desk'; + } + if ( StageAgentRunner::JOB_META === $key ) { + return array( 'stage_key' => 'ai_desk', 'status' => 'failed', 'error' => 'x', 'from_stage' => 'draft' ); + } + return ''; + } + ); + Functions\expect( 'delete_post_meta' )->once()->with( 42, StageAgentRunner::CHAIN_META ); + $seen = null; + $this->wpdb_replacing( 1, $seen ); + Functions\expect( 'wp_schedule_single_event' ) + ->once() + ->with( Mockery::type( 'int' ), StageAgentRunner::RUN_HOOK, array( 42, 'ai_desk' ), true ) + ->andReturn( true ); + + $sequence = $this->sequence_with_status( + array( + 'key' => 'ai_desk', + 'agent' => array( 'ability_id' => 'test/agent', 'routing' => array() ), + ) + ); + $sequence->shouldReceive( 'get_statuses' )->andReturn( array( array( 'key' => 'draft' ), array( 'key' => 'ai_desk' ) ) ); + $sequence->shouldReceive( 'is_transition_allowed' )->andReturnUsing( static fn( $from, $to ): bool => 'draft' === $from && 'ai_desk' === $to ); + $sequence->shouldReceive( 'get_role_permitted_transitions' )->andReturn( array( array( 'to' => 'ai_desk' ) ) ); + + $this->assertTrue( $this->runner->rerun( 42, $sequence ) ); + $this->assertSame( 'wp_postmeta', $seen['table'] ); + $this->assertSame( StageAgentRunner::JOB_META, $seen['where']['meta_key'] ); + $this->assertSame( + serialize( array( 'stage_key' => 'ai_desk', 'status' => 'failed', 'error' => 'x', 'from_stage' => 'draft' ) ), + $seen['where']['meta_value'], + 'the update is conditional on the exact failed marker' + ); + $captured = unserialize( $seen['data']['meta_value'] ); + $this->assertSame( 'pending', $captured['status'] ); + $this->assertSame( 'ai_desk', $captured['stage_key'] ); + $this->assertSame( 'test/agent', $captured['ability_id'] ); + $this->assertSame( 'draft', $captured['from_stage'], 'go-back still knows where the post came from' ); + $this->assertSame( 'rerun', $captured['cause'] ); + $this->assertSame( 5, $captured['started_by'], 'the run belongs to whoever pressed Run again' ); + } + + /** + * Two people pressing Run again at once, or Run again racing Go back: the + * marker is replaced only if it is still the failed one that was checked. + * The loser is refused and schedules nothing. + */ + public function test_rerun_is_refused_when_the_failed_marker_changed_underneath_it(): void + { + $failed = array( 'stage_key' => 'ai_desk', 'status' => 'failed', 'error' => 'x', 'from_stage' => 'draft' ); + Functions\when( 'get_post_meta' )->alias( + static function ( $post_id, $key ) use ( $failed ) { + if ( '_vip_workflows_current_stage_key' === $key ) { + return 'ai_desk'; + } + return StageAgentRunner::JOB_META === $key ? $failed : ''; + } + ); + // Gone or changed: the conditional UPDATE matches no row. It never + // adds one, so a Go back that deleted the marker also refuses here. + $this->wpdb_replacing( 0 ); + Functions\expect( 'update_post_meta' )->never(); + Functions\expect( 'wp_schedule_single_event' )->never(); + Functions\expect( 'delete_post_meta' )->never(); + + $sequence = $this->sequence_with_status( + array( + 'key' => 'ai_desk', + 'agent' => array( 'ability_id' => 'test/agent', 'routing' => array() ), + ) + ); + $sequence->shouldReceive( 'get_statuses' )->andReturn( array( array( 'key' => 'draft' ), array( 'key' => 'ai_desk' ) ) ); + $sequence->shouldReceive( 'is_transition_allowed' )->andReturnUsing( static fn( $from, $to ): bool => 'draft' === $from && 'ai_desk' === $to ); + $sequence->shouldReceive( 'get_role_permitted_transitions' )->andReturn( array( array( 'to' => 'ai_desk' ) ) ); + + $result = $this->runner->rerun( 42, $sequence ); + + $this->assertInstanceOf( \WP_Error::class, $result ); + $this->assertSame( 'agent_rerun_conflict', $result->get_error_code() ); + $this->assertSame( 409, $result->get_error_data()['status'] ); + } + + /** + * Run again keeps the sequence's role rules: a person whose role can't take + * the move into the stage from where the job came is refused, and nothing + * is written or scheduled. + */ + public function test_rerun_is_refused_when_the_role_cannot_enter_the_stage(): void + { + Functions\when( 'get_post_meta' )->alias( + static function ( $post_id, $key ) { + if ( '_vip_workflows_current_stage_key' === $key ) { + return 'ai_desk'; + } + if ( StageAgentRunner::JOB_META === $key ) { + return array( 'stage_key' => 'ai_desk', 'status' => 'failed', 'error' => 'x', 'from_stage' => 'draft' ); + } + return ''; + } + ); + Functions\expect( 'update_post_meta' )->never(); + Functions\expect( 'wp_schedule_single_event' )->never(); + Functions\expect( 'delete_post_meta' )->never(); + + $sequence = $this->sequence_with_status( + array( + 'key' => 'ai_desk', + 'agent' => array( 'ability_id' => 'test/agent', 'routing' => array() ), + ) + ); + $sequence->shouldReceive( 'get_statuses' )->andReturn( array( array( 'key' => 'draft' ), array( 'key' => 'ai_desk' ) ) ); + $sequence->shouldReceive( 'is_transition_allowed' )->andReturnUsing( static fn( $from, $to ): bool => 'draft' === $from && 'ai_desk' === $to ); + $sequence->shouldReceive( 'get_role_permitted_transitions' ) + ->with( 'draft', 5 ) + ->andReturn( array( array( 'to' => 'review' ) ) ); + + $result = $this->runner->rerun( 42, $sequence ); + + $this->assertInstanceOf( \WP_Error::class, $result ); + $this->assertSame( 'forbidden_transition', $result->get_error_code() ); + $this->assertSame( 403, $result->get_error_data()['status'] ); + } + + /** + * Only a run that failed at the post's current stage can run again. + * + * @dataProvider not_rerunnable_jobs + * + * @param mixed $job The stored job marker. + */ + public function test_rerun_refuses_without_a_failed_run_at_the_current_stage( $job ): void + { + Functions\when( 'get_post_meta' )->alias( + static function ( $post_id, $key ) use ( $job ) { + if ( '_vip_workflows_current_stage_key' === $key ) { + return 'ai_desk'; + } + return StageAgentRunner::JOB_META === $key ? $job : ''; + } + ); + Functions\expect( 'update_post_meta' )->never(); + Functions\expect( 'wp_schedule_single_event' )->never(); + + $sequence = $this->sequence_with_status( + array( + 'key' => 'ai_desk', + 'agent' => array( 'ability_id' => 'test/agent', 'routing' => array() ), + ) + ); + + $result = $this->runner->rerun( 42, $sequence ); + + $this->assertInstanceOf( \WP_Error::class, $result ); + $this->assertSame( 'no_agent_rerun', $result->get_error_code() ); + } + + /** + * Job markers that do not allow a re-run. + * + * @return array + */ + public static function not_rerunnable_jobs(): array + { + return array( + 'no job' => array( '' ), + 'still pending' => array( array( 'stage_key' => 'ai_desk', 'status' => 'pending' ) ), + 'held for a person' => array( array( 'stage_key' => 'ai_desk', 'status' => 'warnings_pending' ) ), + 'failed at other stage' => array( array( 'stage_key' => 'other', 'status' => 'failed' ) ), + 'Go back in flight' => array( array( 'stage_key' => 'ai_desk', 'status' => 'reverting', 'reverting_at' => time() ) ), + ); + } + + /** + * A Go back whose request died leaves the marker `reverting`. Once that is + * older than REVERTING_TTL it is put back to the failure it was, and Run + * again goes ahead against that failed marker. + */ + public function test_rerun_goes_ahead_after_an_abandoned_go_back(): void + { + $failed = array( 'stage_key' => 'ai_desk', 'status' => 'failed', 'error' => 'x', 'from_stage' => 'draft' ); + $abandoned = array_merge( + $failed, + array( + 'status' => 'reverting', + 'reverting_at' => time() - StageAgentRunner::REVERTING_TTL - 1, + ) + ); + Functions\when( 'get_post_meta' )->alias( + static function ( $post_id, $key ) use ( $abandoned ) { + if ( '_vip_workflows_current_stage_key' === $key ) { + return 'ai_desk'; + } + return StageAgentRunner::JOB_META === $key ? $abandoned : ''; + } + ); + Functions\expect( 'delete_post_meta' )->once()->with( 42, StageAgentRunner::CHAIN_META ); + Functions\expect( 'wp_schedule_single_event' )->once()->andReturn( true ); + + global $wpdb; + $updates = array(); + $wpdb = Mockery::mock( 'wpdb' ); + $wpdb->postmeta = 'wp_postmeta'; + $wpdb->shouldReceive( 'update' )->andReturnUsing( + function ( $table, $data, $where ) use ( &$updates ) { + $updates[] = array( unserialize( $where['meta_value'] ), unserialize( $data['meta_value'] ) ); + return 1; + } + ); + Functions\when( 'wp_cache_delete' )->justReturn( true ); + Functions\when( 'maybe_serialize' )->alias( 'serialize' ); + + $sequence = $this->sequence_with_status( + array( + 'key' => 'ai_desk', + 'agent' => array( 'ability_id' => 'test/agent', 'routing' => array() ), + ) + ); + $sequence->shouldReceive( 'get_statuses' )->andReturn( array( array( 'key' => 'draft' ), array( 'key' => 'ai_desk' ) ) ); + $sequence->shouldReceive( 'is_transition_allowed' )->andReturnUsing( static fn( $from, $to ): bool => 'draft' === $from && 'ai_desk' === $to ); + $sequence->shouldReceive( 'get_role_permitted_transitions' )->andReturn( array( array( 'to' => 'ai_desk' ) ) ); + + $this->assertTrue( $this->runner->rerun( 42, $sequence ) ); + $this->assertCount( 2, $updates ); + $this->assertSame( array( $abandoned, $failed ), $updates[0], 'the abandoned marker is put back to the failed one first' ); + $this->assertSame( $failed, $updates[1][0], 'Run again then replaces that failed marker' ); + $this->assertSame( 'pending', $updates[1][1]['status'] ); + } + + /** + * A stage whose agent was removed from the sequence has nothing to run again. + */ + public function test_rerun_refuses_when_the_stage_no_longer_has_an_agent(): void + { + Functions\when( 'get_post_meta' )->alias( + static function ( $post_id, $key ) { + if ( '_vip_workflows_current_stage_key' === $key ) { + return 'ai_desk'; + } + return StageAgentRunner::JOB_META === $key + ? array( 'stage_key' => 'ai_desk', 'status' => 'failed' ) + : ''; + } + ); + Functions\expect( 'wp_schedule_single_event' )->never(); + + $result = $this->runner->rerun( 42, $this->sequence_with_status( array( 'key' => 'ai_desk' ) ) ); + + $this->assertInstanceOf( \WP_Error::class, $result ); } } diff --git a/vip-workflows/tests/phpunit/Unit/StageAgentRunnerExecuteTest.php b/vip-workflows/tests/phpunit/Unit/StageAgentRunnerExecuteTest.php index b49e1d0f..c21e8563 100644 --- a/vip-workflows/tests/phpunit/Unit/StageAgentRunnerExecuteTest.php +++ b/vip-workflows/tests/phpunit/Unit/StageAgentRunnerExecuteTest.php @@ -326,7 +326,99 @@ public function test_no_actor_fails_in_place_when_error_route_configured(): void ( new StageAgentRunner( $executor ) )->run_stage_agent( 42, 'ai_desk' ); $this->assertSame( 'failed', $job['status'] ); - $this->assertStringContainsString( 'author cannot edit posts', $job['error'] ); + $this->assertStringContainsString( 'moved here automatically', $job['error'] ); + } + + /** + * When a person started the run but can no longer edit the post, and the + * author cannot either, the failure says so rather than calling the move + * automatic. + */ + public function test_no_actor_names_a_starter_who_lost_the_right(): void + { + Functions\when( 'get_post_meta' )->alias( + function ( $post_id, $key ) { + if ( '_vip_workflows_current_stage_key' === $key ) { + return 'ai_desk'; + } + if ( StageAgentRunner::JOB_META === $key ) { + return array( 'stage_key' => 'ai_desk', 'status' => 'pending', 'queued_at' => 't', 'started_by' => 3 ); + } + return ''; + } + ); + Functions\when( 'user_can' )->justReturn( false ); + $job = array(); + $this->capture_job_meta( $job ); + + $status_manager = Mockery::mock( StatusManager::class ); + $status_manager->shouldReceive( 'get_sequence_for_post' ) + ->andReturn( $this->ai_sequence( array( 'pass' => 'review' ) ) ); + $status_manager->shouldReceive( 'transition' )->never(); + $this->seed_status_manager( $status_manager ); + + $executor = Mockery::mock( AbilityExecutor::class ); + $executor->shouldReceive( 'execute' )->never(); + + ( new StageAgentRunner( $executor ) )->run_stage_agent( 42, 'ai_desk' ); + + $this->assertSame( 'failed', $job['status'] ); + $this->assertStringContainsString( 'can no longer edit it', $job['error'] ); + } + + /** + * An editor who moves someone else's post into an AI stage is who the run + * acts as, so an author who cannot edit posts no longer stops it. + */ + public function test_a_run_started_by_an_editor_executes_as_them_when_the_author_cannot(): void + { + Functions\when( 'get_post_meta' )->alias( + function ( $post_id, $key ) { + if ( '_vip_workflows_current_stage_key' === $key ) { + return 'ai_desk'; + } + if ( StageAgentRunner::JOB_META === $key ) { + return array( 'stage_key' => 'ai_desk', 'status' => 'pending', 'queued_at' => 't', 'started_by' => 3 ); + } + return ''; + } + ); + // The author (7) cannot edit posts; the editor who moved it in (3) can edit this post. + Functions\when( 'user_can' )->alias( + static function ( $user_id, $capability ) { + return 3 === $user_id && 'edit_post' === $capability; + } + ); + $acted_as = array(); + Functions\when( 'wp_set_current_user' )->alias( + static function ( $user_id ) use ( &$acted_as ) { + $acted_as[] = $user_id; + return 1; + } + ); + + $seen = null; + $status_manager = Mockery::mock( StatusManager::class ); + $status_manager->shouldReceive( 'get_sequence_for_post' ) + ->andReturn( $this->ai_sequence( array( 'pass' => 'review' ) ) ); + $status_manager->shouldReceive( 'transition' )->once()->andReturnUsing( + function ( $post_id, $target, $options ) use ( &$seen ) { + $seen = $options; + return true; + } + ); + $this->seed_status_manager( $status_manager ); + + $executor = Mockery::mock( AbilityExecutor::class ); + $executor->shouldReceive( 'execute' ) + ->once() + ->andReturn( self::make_result( true, array( 'status' => 'pass', 'summary' => 'ok' ) ) ); + + ( new StageAgentRunner( $executor ) )->run_stage_agent( 42, 'ai_desk' ); + + $this->assertSame( 3, $acted_as[0] ?? null, 'the ability executes as the editor' ); + $this->assertSame( 0, end( $acted_as ), 'and the cron context is restored afterwards' ); + $this->assertSame( 3, $seen['agent_actor_user'], 'the exit transition is authorised against the editor too' ); } /** @@ -738,6 +830,61 @@ public function test_resolve_agent_user_prefers_author(): void $this->assertSame( 7, $method->invoke( new StageAgentRunner(), 99 ) ); } + /** + * A person who started the run and can still edit this post is who it runs + * as, ahead of the author. + */ + public function test_resolve_run_as_user_prefers_the_starter_who_can_edit_the_post(): void + { + Functions\when( 'get_post_field' )->justReturn( 7 ); + Functions\when( 'user_can' )->alias( + static function ( $user_id, $capability, ...$args ) { + // The starter may edit post 99; the author may not edit posts at all. + return 3 === $user_id && 'edit_post' === $capability && array( 99 ) === $args; + } + ); + + $method = new \ReflectionMethod( StageAgentRunner::class, 'resolve_run_as_user' ); + $this->assertSame( 3, $method->invoke( new StageAgentRunner(), 99, 3 ) ); + } + + /** + * A starter who can no longer edit this post (rights changed between the move + * and the run) is not borrowed: the run falls back to the author. + */ + public function test_resolve_run_as_user_falls_back_to_the_author_when_the_starter_lost_the_right(): void + { + Functions\when( 'get_post_field' )->justReturn( 7 ); + Functions\when( 'user_can' )->alias( + static function ( $user_id, $capability ) { + return 7 === $user_id && 'edit_posts' === $capability; + } + ); + + $method = new \ReflectionMethod( StageAgentRunner::class, 'resolve_run_as_user' ); + $this->assertSame( 7, $method->invoke( new StageAgentRunner(), 99, 3 ) ); + } + + /** + * A run nobody started borrows nobody: with an author who cannot edit posts, + * there is no actor at all. + */ + public function test_resolve_run_as_user_without_a_starter_yields_no_actor_for_an_incapable_author(): void + { + Functions\when( 'get_post_field' )->justReturn( 7 ); + $asked = array(); + Functions\when( 'user_can' )->alias( + static function ( $user_id ) use ( &$asked ) { + $asked[] = $user_id; + return false; + } + ); + + $method = new \ReflectionMethod( StageAgentRunner::class, 'resolve_run_as_user' ); + $this->assertSame( 0, $method->invoke( new StageAgentRunner(), 99, 0 ) ); + $this->assertSame( array( 7 ), $asked, 'only the author is considered when nobody started the run' ); + } + /** * When the author cannot edit posts the run yields no actor, rather than * substituting an administrator. @@ -1851,10 +1998,10 @@ function ( $post_id, $target, $passed ) use ( &$options ) { ( new StageAgentRunner( $executor ) )->run_stage_agent( 42, 'ai_desk' ); - // Not the post author (7) the agent acted as: Pendo would show the author - // doing something they did not do. + // Not the post author (7): Pendo would show the author doing something + // they did not do. $this->assertSame( 3, $this->run_event( $telemetry )['user'] ); - $this->assertSame( 7, $options['agent_actor_user'], 'the agent still acts as the author' ); + $this->assertSame( 3, $options['agent_actor_user'], 'the agent acts as the person who moved the post in, who can edit it' ); $this->assertSame( 3, $options['telemetry_user'] ); } diff --git a/vip-workflows/tests/phpunit/Unit/StatusManagerAgentGatingTest.php b/vip-workflows/tests/phpunit/Unit/StatusManagerAgentGatingTest.php index 0e7680a1..29fa4b57 100644 --- a/vip-workflows/tests/phpunit/Unit/StatusManagerAgentGatingTest.php +++ b/vip-workflows/tests/phpunit/Unit/StatusManagerAgentGatingTest.php @@ -1197,13 +1197,7 @@ public function test_get_agent_revert_stage_null_while_job_pending(): void */ public function test_revert_failed_agent_stage_transitions_back_and_clears_state(): void { - $failed_job = array( - 'stage_key' => 'ai_desk', - 'status' => 'failed', - 'ability_id' => 'x', - 'error' => 'boom', - 'from_stage' => 'draft', - ); + $failed_job = $this->failed_job(); $this->stub_post_in_ai_stage( $failed_job ); $deleted = array(); @@ -1213,6 +1207,7 @@ function ( $post_id, $key, $value = '' ) use ( &$deleted ) { return true; } ); + $calls = $this->wpdb_taking( 1 ); $manager = Mockery::mock( StatusManager::class )->makePartial(); $manager->shouldReceive( 'get_agent_revert_stage' )->with( 42 )->andReturn( 'draft' ); @@ -1224,7 +1219,218 @@ function ( $post_id, $key, $value = '' ) use ( &$deleted ) { $this->assertTrue( $manager->revert_failed_agent_stage( 42 ) ); $this->assertContains( array( StageAgentRunner::CHAIN_META, '' ), $deleted, 'The loop guard resets before the move.' ); - $this->assertContains( array( StageAgentRunner::JOB_META, $failed_job ), $deleted, 'The failed marker is cleared compare-and-delete.' ); + $reverting = $this->reverting_marker_written( $calls, $failed_job ); + $this->assertSame( + array( + array( 'update', serialize( $failed_job ), serialize( $reverting ) ), + array( 'delete', serialize( $reverting ), null ), + ), + $calls->log, + 'The failed marker is swapped for a reverting one before the move, and cleared after it.' + ); + } + + /** + * Go back loses to a Run again that already replaced the failed marker: + * the compare-and-swap matches nothing, so the post doesn't move. + */ + public function test_revert_failed_agent_stage_refuses_when_the_marker_was_taken(): void + { + $this->stub_post_in_ai_stage( $this->failed_job() ); + $this->wpdb_taking( 0 ); + + $manager = Mockery::mock( StatusManager::class )->makePartial(); + $manager->shouldReceive( 'get_agent_revert_stage' )->with( 42 )->andReturn( 'draft' ); + $manager->shouldReceive( 'transition' )->never(); + + $result = $manager->revert_failed_agent_stage( 42 ); + + $this->assertInstanceOf( 'WP_Error', $result ); + $this->assertSame( 'agent_revert_conflict', $result->get_error_code() ); + $this->assertSame( 409, $result->get_error_data()['status'] ); + } + + /** + * A Go back that doesn't happen, refused or held for soft warnings, puts + * the failed state back. + * + * @dataProvider provide_unfinished_moves + * + * @param mixed $outcome What transition() answers. + */ + public function test_revert_failed_agent_stage_restores_the_marker_when_the_move_does_not_happen( $outcome ): void + { + $failed_job = $this->failed_job(); + $this->stub_post_in_ai_stage( $failed_job ); + Functions\when( 'delete_post_meta' )->justReturn( true ); + $calls = $this->wpdb_taking( 1 ); + + $manager = Mockery::mock( StatusManager::class )->makePartial(); + $manager->shouldReceive( 'get_agent_revert_stage' )->with( 42 )->andReturn( 'draft' ); + $manager->shouldReceive( 'transition' )->once()->andReturn( $outcome ); + + $this->assertSame( $outcome, $manager->revert_failed_agent_stage( 42 ) ); + + $reverting = $this->reverting_marker_written( $calls, $failed_job ); + $this->assertSame( array( 'update', serialize( $reverting ), serialize( $failed_job ) ), end( $calls->log ) ); + } + + /** + * A Go back whose move throws puts the failed state back before the error + * goes on, so Run again and Go back are still on offer afterwards. + */ + public function test_revert_failed_agent_stage_restores_the_marker_when_the_move_throws(): void + { + $failed_job = $this->failed_job(); + $this->stub_post_in_ai_stage( $failed_job ); + Functions\when( 'delete_post_meta' )->justReturn( true ); + $calls = $this->wpdb_taking( 1 ); + + $manager = Mockery::mock( StatusManager::class )->makePartial(); + $manager->shouldReceive( 'get_agent_revert_stage' )->with( 42 )->andReturn( 'draft' ); + $manager->shouldReceive( 'transition' )->once()->andThrow( new \RuntimeException( 'a hooked callback blew up' ) ); + + try { + $manager->revert_failed_agent_stage( 42 ); + $this->fail( 'The exception should reach the caller.' ); + } catch ( \RuntimeException $e ) { + $this->assertSame( 'a hooked callback blew up', $e->getMessage() ); + } + + $reverting = $this->reverting_marker_written( $calls, $failed_job ); + $this->assertSame( array( 'update', serialize( $reverting ), serialize( $failed_job ) ), end( $calls->log ) ); + } + + /** + * A `reverting` marker left by a Go back whose request died reads as the + * failure it was once it is old enough, so Go back is offered again. + * + * @dataProvider provide_abandoned_reverting_markers + * + * @param array $extra Fields the abandoned marker carries beyond the failed one. + */ + public function test_get_agent_revert_stage_recovers_an_abandoned_go_back( array $extra ): void + { + $failed_job = $this->failed_job(); + $abandoned = array_merge( $failed_job, array( 'status' => 'reverting' ), $extra ); + $this->stub_post_in_ai_stage( $abandoned ); + $calls = $this->wpdb_taking( 1 ); + + $manager = $this->gated_status_manager( $this->sequence_with_unrouted_edge() ); + + $this->assertSame( 'draft', $manager->get_agent_revert_stage( 42 ) ); + $this->assertSame( + array( array( 'update', serialize( $abandoned ), serialize( $failed_job ) ) ), + $calls->log, + 'The abandoned marker is swapped back to the failed one, by compare-and-swap.' + ); + } + + /** + * @return array + */ + public function provide_abandoned_reverting_markers(): array + { + return array( + 'stamped long ago' => array( array( 'reverting_at' => time() - StageAgentRunner::REVERTING_TTL - 1 ) ), + 'never stamped' => array( array() ), + ); + } + + /** + * A fresh `reverting` marker is a Go back still in flight: nothing is + * offered and nothing is written over it. + */ + public function test_get_agent_revert_stage_leaves_a_go_back_in_flight_alone(): void + { + $this->stub_post_in_ai_stage( array_merge( $this->failed_job(), array( 'status' => 'reverting', 'reverting_at' => time() ) ) ); + $calls = $this->wpdb_taking( 1 ); + + $manager = $this->gated_status_manager( $this->sequence_with_unrouted_edge() ); + + $this->assertNull( $manager->get_agent_revert_stage( 42 ) ); + $this->assertSame( array(), $calls->log ); + } + + /** + * The reverting marker Go back wrote: the failed one, marked reverting and + * stamped with when. + * + * @param object $calls The wpdb call log. + * @param array $failed_job The failed marker it replaced. + * @return array + */ + private function reverting_marker_written( object $calls, array $failed_job ): array + { + $this->assertSame( 'update', $calls->log[0][0] ); + $this->assertSame( serialize( $failed_job ), $calls->log[0][1] ); + + $reverting = unserialize( $calls->log[0][2] ); + $this->assertIsInt( $reverting['reverting_at'] ?? null ); + $this->assertEqualsWithDelta( time(), $reverting['reverting_at'], 5 ); + $this->assertSame( + array_merge( $failed_job, array( 'status' => 'reverting', 'reverting_at' => $reverting['reverting_at'] ) ), + $reverting + ); + + return $reverting; + } + + /** + * @return array + */ + public function provide_unfinished_moves(): array + { + return array( + 'refused' => array( new \WP_Error( 'forbidden', 'no' ) ), + 'held for soft warnings' => array( array( 'warnings_pending' => true, 'soft_warnings' => array() ) ), + ); + } + + /** + * A failed job marker for the AI stage. + * + * @return array + */ + private function failed_job(): array + { + return array( + 'stage_key' => 'ai_desk', + 'status' => 'failed', + 'ability_id' => 'x', + 'error' => 'boom', + 'from_stage' => 'draft', + ); + } + + /** + * Mock $wpdb for Go back's compare-and-swap. + * + * @param int|false $rows Rows each conditional write reports changed. + * @return object Its `log` lists each write as [kind, expected value, new value]. + */ + private function wpdb_taking( $rows ): object + { + global $wpdb; + $calls = new \stdClass(); + $calls->log = array(); + $wpdb = Mockery::mock( 'wpdb' ); + $wpdb->postmeta = 'wp_postmeta'; + $wpdb->shouldReceive( 'update' )->andReturnUsing( + function ( $table, $data, $where ) use ( $rows, $calls ) { + $calls->log[] = array( 'update', $where['meta_value'], $data['meta_value'] ); + return $rows; + } + ); + $wpdb->shouldReceive( 'delete' )->andReturnUsing( + function ( $table, $where ) use ( $rows, $calls ) { + $calls->log[] = array( 'delete', $where['meta_value'], null ); + return $rows; + } + ); + Functions\when( 'wp_cache_delete' )->justReturn( true ); + Functions\when( 'maybe_serialize' )->alias( 'serialize' ); + return $calls; } /** diff --git a/vip-workflows/tests/phpunit/Unit/TestCase.php b/vip-workflows/tests/phpunit/Unit/TestCase.php index fe9bc805..07f62d6c 100644 --- a/vip-workflows/tests/phpunit/Unit/TestCase.php +++ b/vip-workflows/tests/phpunit/Unit/TestCase.php @@ -42,6 +42,10 @@ protected function set_up() $this->stubEscapeFunctions(); $this->stubTranslationFunctions(); + // Not a cron request unless a test says so. Code that treats cron as + // a context with no person behind it reads this on ordinary paths. + Functions\when( 'wp_doing_cron' )->justReturn( false ); + $this->setup_common_wp_functions(); } @@ -135,8 +139,8 @@ protected static function reset_process_state(): void // mis-attributes revisions in a later test. ( new \ReflectionProperty( \VIPWorkflows\Workflow\StageAgentRunner::class, 'acting_ability_id' ) ) ->setValue( null, '' ); - ( new \ReflectionProperty( \VIPWorkflows\Workflow\StageAgentRunner::class, 'exiting_run_started_by' ) ) - ->setValue( null, 0 ); + ( new \ReflectionProperty( \VIPWorkflows\Workflow\StageAgentRunner::class, 'exiting_run' ) ) + ->setValue( null, null ); // Re-entrancy guard keyed by post id; a leftover key makes a later // transition look already in progress and silently no-op. diff --git a/vip-workflows/tests/unit-js/workflow-header-action.test.js b/vip-workflows/tests/unit-js/workflow-header-action.test.js index 561a6ff4..8adb980d 100644 --- a/vip-workflows/tests/unit-js/workflow-header-action.test.js +++ b/vip-workflows/tests/unit-js/workflow-header-action.test.js @@ -475,6 +475,218 @@ describe( 'WorkflowHeaderAction', () => { ).toBeInTheDocument(); } ); + /** + * When the failed run can run again, that is the header's action: the post + * stays at its stage and a fresh run starts, instead of a trip back. + */ + it( 'offers Run again when the failed stage agent can run again', async () => { + const failed = statusResponse( { + transitions: [], + agent_job: { + status: 'failed', + error: 'Timed out.', + can_rerun: true, + revert_to: { key: 'draft', label: 'Draft' }, + }, + } ); + await renderHeader( failed ); + + apiFetch.mockImplementation( ( { path } ) => + Promise.resolve( + path.endsWith( '/agent-rerun' ) + ? statusResponse( { + transitions: [], + agent_pending: true, + agent_job: { status: 'pending', error: '' }, + } ) + : failed + ) + ); + + expect( + screen.queryByRole( 'button', { name: 'Go back to Draft' } ) + ).toBeNull(); + + await act( async () => { + ( + await screen.findByRole( 'button', { name: 'Run again' } ) + ).click(); + } ); + + expect( apiFetch ).toHaveBeenCalledWith( { + path: '/vip-workflows/v1/workflow/post/42/agent-rerun', + method: 'POST', + } ); + expect( apiFetch ).not.toHaveBeenCalledWith( + expect.objectContaining( { + path: expect.stringMatching( /agent-revert$/ ), + } ) + ); + + // The run is now pending. The header keeps its button, busy, rather + // than dropping it until the outcome arrives. + const working = await screen.findByRole( 'button', { + name: 'Agent working', + } ); + expect( working ).toHaveClass( 'is-busy' ); + expect( working ).toHaveAttribute( 'aria-disabled', 'true' ); + } ); + + /** + * Run again refused (another person ran it first): the header reports the + * server's reason, and re-reads the post so it shows what the post is + * doing now rather than a Run again that can no longer succeed. + */ + it( 'reports a refused Run again and re-reads the post', async () => { + const failed = statusResponse( { + transitions: [], + agent_job: { + status: 'failed', + error: 'Timed out.', + can_rerun: true, + revert_to: { key: 'draft', label: 'Draft' }, + }, + } ); + const runningNow = statusResponse( { + transitions: [], + agent_pending: true, + agent_job: { status: 'pending', error: '' }, + } ); + await renderHeader( failed ); + + let refused = false; + apiFetch.mockImplementation( ( { path } ) => { + if ( path.endsWith( '/agent-rerun' ) ) { + refused = true; + return Promise.reject( { + code: 'agent_rerun_conflict', + message: + 'This agent run changed while you were starting it. Reload the post to see where it is now.', + } ); + } + return Promise.resolve( + path === STATUS_PATH && refused ? runningNow : failed + ); + } ); + + await act( async () => { + ( + await screen.findByRole( 'button', { name: 'Run again' } ) + ).click(); + } ); + + await waitFor( () => + expect( createErrorNotice ).toHaveBeenCalledWith( + 'This agent run changed while you were starting it. Reload the post to see where it is now.', + expect.anything() + ) + ); + expect( + await screen.findByRole( 'button', { name: 'Agent working' } ) + ).toBeInTheDocument(); + } ); + + /** + * The agent reads the stored post, so Run again saves the author's + * unsaved edits first — as a move into an AI stage does — and only then + * asks the server to run it. + */ + it( 'saves unsaved edits before running the agent again', async () => { + setCoreEditor( { dirty: true } ); + const failed = statusResponse( { + transitions: [], + agent_job: { + status: 'failed', + error: 'Timed out.', + can_rerun: true, + revert_to: { key: 'draft', label: 'Draft' }, + }, + } ); + await renderHeader( failed ); + + const order = []; + savePost.mockImplementationOnce( () => ( { dispatch: editor } ) => { + order.push( 'save' ); + editor.setCoreEditor( { dirty: false } ); + } ); + apiFetch.mockImplementation( ( { path } ) => { + if ( path.endsWith( '/agent-rerun' ) ) { + order.push( 'rerun' ); + return Promise.resolve( + statusResponse( { + transitions: [], + agent_pending: true, + agent_job: { status: 'pending', error: '' }, + } ) + ); + } + return Promise.resolve( failed ); + } ); + + await act( async () => { + ( + await screen.findByRole( 'button', { name: 'Run again' } ) + ).click(); + } ); + + await waitFor( () => expect( order ).toEqual( [ 'save', 'rerun' ] ) ); + } ); + + it( 'does not run the agent again when the save fails', async () => { + setCoreEditor( { dirty: true } ); + const failed = statusResponse( { + transitions: [], + agent_job: { + status: 'failed', + error: 'Timed out.', + can_rerun: true, + revert_to: { key: 'draft', label: 'Draft' }, + }, + } ); + await renderHeader( failed ); + + savePost.mockImplementationOnce( () => ( { dispatch: editor } ) => { + editor.setCoreEditor( { saveFailed: true } ); + } ); + const reruns = []; + apiFetch.mockImplementation( ( { path } ) => { + if ( path.endsWith( '/agent-rerun' ) ) { + reruns.push( path ); + } + return Promise.resolve( failed ); + } ); + + await act( async () => { + ( + await screen.findByRole( 'button', { name: 'Run again' } ) + ).click(); + } ); + + await waitFor( () => + expect( createErrorNotice ).toHaveBeenCalledWith( + 'Could not save the post before running the agent again. Try again.', + expect.anything() + ) + ); + expect( reruns ).toHaveLength( 0 ); + } ); + + it( 'stays on screen, busy, while a stage agent runs', async () => { + await renderHeader( + statusResponse( { + transitions: [], + agent_pending: true, + agent_job: { status: 'pending', error: '' }, + } ) + ); + + const working = await screen.findByRole( 'button', { + name: 'Agent working', + } ); + expect( working ).toHaveClass( 'is-busy' ); + expect( working ).toHaveAttribute( 'aria-disabled', 'true' ); + } ); + it( 'asks before a primary transition that publishes', async () => { await renderHeader( statusResponse( { transitions: [ TO_LIVE, TO_REVIEW ] } ) diff --git a/vip-workflows/tests/unit-js/workflow-panel-agent-rerun.test.js b/vip-workflows/tests/unit-js/workflow-panel-agent-rerun.test.js new file mode 100644 index 00000000..b602e6cd --- /dev/null +++ b/vip-workflows/tests/unit-js/workflow-panel-agent-rerun.test.js @@ -0,0 +1,315 @@ +/** + * The failed AI stage in the Workflow panel: Run again and Go back. + * + * Run again retries the agent in place, started by whoever presses it, so it + * leads whenever the server says the run can go again. Go back stays beside it + * as the way out, and leads only when a re-run is not offered. + * + * @package + */ + +import { render, screen, waitFor, act } from './helpers/render-wp-component'; +import apiFetch from '@wordpress/api-fetch'; + +jest.mock( '@wordpress/api-fetch', () => jest.fn() ); +jest.mock( '@wordpress/core-data', () => ( { store: 'core' } ) ); +jest.mock( '@wordpress/editor', () => ( { store: 'core/editor' } ) ); +jest.mock( '@wordpress/edit-post', () => ( { store: 'core/edit-post' } ) ); +jest.mock( '@wordpress/notices', () => ( { store: 'core/notices' } ) ); +jest.mock( '@wordpress/a11y', () => ( { speak: jest.fn() } ) ); + +import { createReduxStore, register } from '@wordpress/data'; + +register( + createReduxStore( 'core', { + reducer: ( state = {} ) => state, + selectors: { getEntityRecord: () => null }, + actions: { invalidateResolution: () => ( { type: 'NOOP' } ) }, + } ) +); + +register( + createReduxStore( 'core/notices', { + reducer: ( state = {} ) => state, + actions: { + createSuccessNotice: () => ( { type: 'NOOP' } ), + createErrorNotice: () => ( { type: 'NOOP' } ), + removeNotice: () => ( { type: 'NOOP' } ), + }, + } ) +); + +register( + createReduxStore( 'core/editor', { + reducer: ( state = {} ) => state, + selectors: { + isEditorPanelRemoved: () => false, + isEditorPanelEnabled: () => true, + getEditedPostAttribute: () => 'draft', + getCurrentPostAttribute: () => 'draft', + getCurrentPostId: () => 42, + isEditedPostDirty: () => false, + isSavingPost: () => false, + }, + actions: { savePost: () => ( { type: 'NOOP' } ) }, + } ) +); + +import { seedEditorStore } from './helpers/editor-store'; +import { WorkflowPanel } from '../../src/editor/components/WorkflowPanel'; +import { TransitionFlow } from '../../src/editor/components/TransitionFlow'; + +const STATUS_PATH = '/vip-workflows/v1/workflow/post/42/status'; +const RERUN_PATH = '/vip-workflows/v1/workflow/post/42/agent-rerun'; +const REVERT_PATH = '/vip-workflows/v1/workflow/post/42/agent-revert'; + +const failedStatus = ( agentJob ) => ( { + has_workflow: true, + sequence: { id: 1, name: 'AI Flow' }, + current: { + key: 'ai_desk', + label: 'AI Desk', + color: '#666', + is_terminal: false, + }, + transitions: [], + agent_pending: false, + agent_job: { status: 'failed', error: 'Agent run timed out.', ...agentJob }, + can_remove: false, +} ); + +/** + * Render the panel against a status payload, recording every request. + * + * @param {Object} payload Status payload the panel reads. + * @return {Promise} The recorded requests. + */ +async function renderPanel( payload ) { + const calls = []; + apiFetch.mockImplementation( ( request ) => { + calls.push( request ); + if ( request.path === STATUS_PATH ) { + return Promise.resolve( payload ); + } + if ( request.path === RERUN_PATH ) { + return Promise.resolve( { + ...payload, + agent_pending: true, + agent_job: { status: 'pending', error: '' }, + } ); + } + if ( request.path.startsWith( '/vip-workflows/v1/abilities' ) ) { + return Promise.resolve( [] ); + } + return Promise.resolve( {} ); + } ); + + render( + <> + + + + ); + + await waitFor( () => + expect( + screen.getByText( 'The AI agent could not finish.' ) + ).toBeInTheDocument() + ); + + return calls; +} + +describe( 'WorkflowPanel failed agent actions', () => { + beforeEach( () => { + apiFetch.mockReset(); + seedEditorStore(); + } ); + + it( 'runs the agent again in place, ahead of Go back', async () => { + const calls = await renderPanel( + failedStatus( { + can_rerun: true, + revert_to: { key: 'drafting', label: 'Drafting' }, + } ) + ); + + const runAgain = screen.getByRole( 'button', { name: 'Run again' } ); + const goBack = screen.getByRole( 'button', { + name: 'Go back to Drafting', + } ); + expect( runAgain ).toHaveClass( 'is-primary' ); + expect( goBack ).toHaveClass( 'is-secondary' ); + + await act( async () => { + runAgain.click(); + } ); + + expect( + calls.some( ( c ) => c.path === RERUN_PATH && c.method === 'POST' ) + ).toBe( true ); + expect( + calls.some( ( c ) => c.path.endsWith( '/agent-revert' ) ) + ).toBe( false ); + + // The run is pending now: the failure and its actions are gone. + await waitFor( () => + expect( + screen.queryByText( 'The AI agent could not finish.' ) + ).toBeNull() + ); + expect( + screen.queryByRole( 'button', { name: 'Run again' } ) + ).toBeNull(); + } ); + + it( 'shows the refusal and re-reads the post when Run again is refused', async () => { + const failed = failedStatus( { + can_rerun: true, + revert_to: { key: 'drafting', label: 'Drafting' }, + } ); + let refused = false; + const calls = []; + apiFetch.mockImplementation( ( request ) => { + calls.push( request ); + if ( request.path === RERUN_PATH ) { + refused = true; + return Promise.reject( { + code: 'agent_rerun_conflict', + message: + 'This agent run changed while you were starting it. Reload the post to see where it is now.', + } ); + } + if ( request.path === STATUS_PATH ) { + // Someone else's re-run is now pending. + return Promise.resolve( + refused + ? { + ...failed, + agent_pending: true, + agent_job: { status: 'pending', error: '' }, + } + : failed + ); + } + if ( request.path.startsWith( '/vip-workflows/v1/abilities' ) ) { + return Promise.resolve( [] ); + } + return Promise.resolve( {} ); + } ); + + render( + <> + + + + ); + await waitFor( () => + expect( + screen.getByRole( 'button', { name: 'Run again' } ) + ).toBeInTheDocument() + ); + + await act( async () => { + screen.getByRole( 'button', { name: 'Run again' } ).click(); + } ); + + expect( + await screen.findByText( + 'This agent run changed while you were starting it. Reload the post to see where it is now.' + ) + ).toBeInTheDocument(); + await waitFor( () => + expect( + screen.queryByRole( 'button', { name: 'Run again' } ) + ).toBeNull() + ); + expect( + calls.filter( ( c ) => c.path === STATUS_PATH ).length + ).toBeGreaterThan( 1 ); + } ); + + it( 'shows the refusal and re-reads the post when Go back is refused', async () => { + const failed = failedStatus( { + can_rerun: true, + revert_to: { key: 'drafting', label: 'Drafting' }, + } ); + let refused = false; + const calls = []; + apiFetch.mockImplementation( ( request ) => { + calls.push( request ); + if ( request.path === REVERT_PATH ) { + refused = true; + return Promise.reject( { + code: 'agent_revert_conflict', + message: + 'This agent run changed while you were going back. Reload the post to see where it is now.', + } ); + } + if ( request.path === STATUS_PATH ) { + // Someone else's Run again won; its run is now pending. + return Promise.resolve( + refused + ? { + ...failed, + agent_pending: true, + agent_job: { status: 'pending', error: '' }, + } + : failed + ); + } + if ( request.path.startsWith( '/vip-workflows/v1/abilities' ) ) { + return Promise.resolve( [] ); + } + return Promise.resolve( {} ); + } ); + + render( + <> + + + + ); + await waitFor( () => + expect( + screen.getByRole( 'button', { name: 'Go back to Drafting' } ) + ).toBeInTheDocument() + ); + + await act( async () => { + screen + .getByRole( 'button', { name: 'Go back to Drafting' } ) + .click(); + } ); + + expect( + await screen.findByText( + 'This agent run changed while you were going back. Reload the post to see where it is now.' + ) + ).toBeInTheDocument(); + await waitFor( () => + expect( + screen.queryByRole( 'button', { name: 'Go back to Drafting' } ) + ).toBeNull() + ); + expect( + calls.filter( ( c ) => c.path === STATUS_PATH ).length + ).toBeGreaterThan( 1 ); + } ); + + it( 'leads with Go back when the run cannot go again', async () => { + await renderPanel( + failedStatus( { + can_rerun: false, + revert_to: { key: 'drafting', label: 'Drafting' }, + } ) + ); + + expect( + screen.queryByRole( 'button', { name: 'Run again' } ) + ).toBeNull(); + expect( + screen.getByRole( 'button', { name: 'Go back to Drafting' } ) + ).toHaveClass( 'is-primary' ); + } ); +} );