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.