Skip to content

Run a stage agent as the person who moved the post in, and let a failed run go again in place - #168

Merged
smithjw1 merged 13 commits into
mainfrom
fix/agent-runs-as-mover
Nov 16, 2026
Merged

smithjw1 merged 13 commits into
mainfrom
fix/agent-runs-as-mover

Conversation

@smithjw1

@smithjw1 smithjw1 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Intent

A stage agent always ran as the post's author. When the author couldn't edit posts (a subscriber, a removed account, an imported author), every run stopped with "The author cannot edit posts", and the advice to move the post back and forward again couldn't help: the retry ran as the same author and failed the same way. An editor who could plainly do the work had no way to have the agent do it.

This PR makes a run act as the person who started it, when they can still edit the post. It also adds a direct retry, Run again, so fixing a failed run no longer takes a trip out of the stage and back in.

Spec changes

  • Glossary, N4, REST and Abilities: a stage agent now runs as the person who moved the post in, falling back to the author, where the old text said it runs as the post author. N4's publish rule now names the user the run acts as. The route table adds agent-rerun.
  • Stage agents → How it works: a failed run now leads with Run again (a fresh run at the same stage, acting as whoever pressed it) and keeps Go back beside it. Two concurrent presses, or Run again racing Go back, resolve by compare-and-swap (409 agent_rerun_conflict). The state diagram gains the Failed → Pending edge.
  • Stage agents → Always true: check the rewritten "the run acts as who started it" line. That person is re-checked for edit_post when the run fires. A run nobody started still acts only as the author, and only if the author has edit_posts. The line saying started_by is used only for telemetry is gone, because started_by now decides who the run acts as. The exit transition and the agent-publish check are authorized against the user the run acts as. Run again resets the loop-guard counter.
  • Stage agents → Footguns: removed "Some screens say Re-run, but there is no re-run action."

What was done

Who a run acts as

  • StageAgentRunner::resolve_run_as_user() picks who a run acts as. It returns the person who started the run (started_by in the job marker) if user_can( $started_by, 'edit_post', $post_id ) is true when the run fires. Otherwise it falls back to resolve_agent_user(), the author check, unchanged.
  • The rights check happens at run time, not at dispatch, because capabilities can change between the move and the run.
  • A run nobody started (cron, a scheduled publish, a reseat with no one logged in) still uses only the author. It never borrows anyone else's rights.
  • Decisions made deliberately:
    • An agent-to-agent hop inherits the person who started the chain, for that post only. A dispatch under cron never takes whoever happens to be logged in (for example wp cron event run --user=…). Their rights are re-checked on every hop.
    • The run's exit transition is checked against that same person.
    • The revision an agent writes is credited to that person, and is still tagged with the agent that made the edit.
  • The failure when nobody can act now says why, rather than what to do, since the next step is on a button:
    • "This post moved here automatically, and its author can't edit posts, so the agent had no one to run as."
    • "The person who moved this post here can no longer edit it, and neither can its author."

Run again

  • New route POST /vip-workflows/v1/workflow/post/{id}/agent-rerun (WorkflowController::rerun_agent_stage(), StageAgentRunner::rerun()). It dispatches a fresh run for a post whose agent failed at its current stage. The run is started by the current user, so it acts as them. The post stays put, the go-back origin is kept, and the loop-guard chain restarts.
  • The route refuses with 409 no_agent_rerun when there's no failed run at the current stage, or when the stage no longer has an agent.
  • Run again replaces the failed job only if it's still exactly the one that was checked. If two people press it at once, or it races Go back, the loser gets 409 agent_rerun_conflict and nothing is written or scheduled. The replace is a single conditional UPDATE that never creates a row.
  • The failed agent_job in the status payload gains can_rerun.
  • The panel leads with Run again, with Go back to {stage} beside it as the secondary action. Go back leads when a re-run isn't offered. The header button offers Run again on a failed stage when it can.
  • Run again saves the author's unsaved edits first, exactly as a move into an AI stage does, because the agent reads the stored post. Both buttons hand Run again to the transition flow (requestRerun()), which waits out a save in flight, asks what decideSave() asks, saves, and stops if the save didn't take. That wait-decide-save-check sequence is now one helper, saveFirst(), shared by moves and Run again. Like entering an AI stage, Run again is refused while another editor has the post open.
  • When Run again is refused, the editor re-reads the post's status before showing the error, so the panel and header offer what the post allows now instead of a Run again that can't succeed.
  • A failed compare-and-swap query is logged as a database error, not passed off silently as a conflict.
  • Marker writing and scheduling moved into a shared private dispatch(), used by both entry and re-run.

API changes for callers

  • New route: POST /workflow/post/{id}/agent-rerun.
  • New field: agent_job.can_rerun on failed jobs.
  • agent_job.cause can now be rerun.

Also in this PR: header button stays on screen while an agent runs

This is separate from the fix above and is in its own commit (Keep the header button on screen while a stage agent runs).

The header's split button was drawn only when there was a move to offer. While a stage agent runs, the stage holds back its exits, so the button disappeared between the press that started the run and the outcome. Run again showed busy, vanished, then came back. Moving a post into an AI stage did the same. While a run is pending, the main half now stays as a busy, disabled Agent working button until the outcome arrives. Only WorkflowHeaderAction.js and its test change.

Screenshots

Before After
Failed run, Workflow panel Before: failed run panel with only Go back After: failed run panel with Run again and Go back
Failed run, header Before: header offers Go back to Drafting After: header offers Run again
Header while the agent runs Before: the workflow button is gone while the agent runs
Our button is gone.
After: header shows Agent working while the agent runs
Header right after Run again — After: header stays busy as Agent working after Run again

How to test

The preview has no AI provider configured, so a real agent can't run in it. A failed run also needs a seeded job marker. The quickest full check is on wp-env with a stub agent. Adding a stub agent and a failed-run post to .playground/blueprint.json would make this testable in the preview; that's a possible follow-up, not done here.

  1. npm run build (root) compiles clean.
  2. cd vip-workflows && composer test: unit tests pass (2,031, 1 skipped).
  3. npm --prefix vip-workflows run test:unit:js: JS unit tests pass (1,869). They include Run again saving unsaved edits before it runs, stopping when that save fails, and its refusal path in the header and the panel.
  4. With the tests environment running, npm run test:php:integration: integration tests pass (580). They include AgentRunsAsStarterIntegrationTest, which covers an editor's move on a subscriber's post, a demoted starter falling back to the author, a run nobody started refusing in place, and Run again by an editor fixing that refusal through the REST route.
  5. Manually, on wp-env, as an admin:
    • Register an always-passing stage agent and put it on a stage of a sequence (for example Drafting → AI check → Review).
    • Create a post authored by a subscriber, set it to the AI stage, and write a pending job marker with started_by 0. Run the agent with nobody logged in (wp eval calling StageAgentRunner::run_stage_agent() after wp_set_current_user( 0 )). Expect it to fail with "This post moved here automatically…".
    • Open the post. The Workflow panel (Post settings tab) shows the failure with Run again as primary and Go back to Drafting as secondary. The header button says Run again.
    • Press Run again with WP-Cron running (wp cron event run --due-now in a loop). The header button stays busy as Agent working for the whole run. The post moves on to Review, and the run is credited to you.
    • Create another subscriber-authored post in Drafting and move it into the AI stage yourself. It runs as you and moves on, with no failure.

The preview can show the header and panel layout for any post in a workflow, but not the failed or running agent states.

Follow-ups

  • Two runner comments and the co-editing message still say "Re-run". With this PR that's accurate again, so they're left as they are.
  • Seeding a stub agent and a failed run into the Playground blueprint is tracked separately.

🤖 Generated with Claude Code

Open WordPress Playground Preview

@smithjw1
smithjw1 force-pushed the fix/agent-runs-as-mover branch 2 times, most recently from 7375e02 to d0045e2 Compare November 13, 2026 07:54
@smithjw1
smithjw1 marked this pull request as ready for review November 13, 2026 08:01

@chriszarate chriszarate left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. P1: Re-entry retains the previous mover’s authority. resolve_run_as_user() (class-stage-agent-runner.php:867) now trusts started_by, but the pending-job guard preserves it across re-entry.

    An editor moved a contributor’s post into the AI stage, then confirmed a move out before execution. The contributor changed the content and moved it back. The agent still ran as the editor. With allow_agent_publish=true, it published the contributor’s new content despite the contributor lacking publish_posts.

    Refresh the job identity and origin on each actual stage entry. Deduplicate the cron event without retaining authorization from an abandoned entry.

  2. P2: Run again bypasses sequence role restrictions. rerun_agent_stage() (class-workflow-controller.php:869) requires edit_post but does not enforce an applicable sequence permission.

    An editor-only entry rejected the contributor with forbidden_transition. After an editor entered the stage and the run failed, the contributor’s retry returned HTTP 200. The agent ran as the contributor and advanced the post. The contributor could also trigger this through the panel. SPEC.md promises sequence transition rules for this route.

    Enforce an explicit retry permission that preserves the sequence’s role restrictions. Apply the same check to can_rerun.

  3. P2: Run again and Go back can both succeed. The conditional update in rerun() (class-stage-agent-runner.php:326) does not coordinate with revert_failed_agent_stage() (class-status-manager.php:275).

    I paused Go back immediately before its stage write and executed a retry through REST. Both requests returned HTTP 200. The post ended in Drafting with a pending job for the AI stage. That retry cannot execute at its requested stage.

    Make both operations conditionally claim the failed job before changing state. Return a conflict to the losing request.

@smithjw1

Copy link
Copy Markdown
Contributor Author

Thanks, Chris, all three were real, and fixing them turned up two more.

  1. Re-entry: every entry now writes a fresh marker, so the run acts as whoever made this entry and "Go back" leads where this entry came from. Only the cron event is still deduplicated. Your contributor scenario is now an integration test, and it fails on the old guard.
  2. Run again checks the sequence's role rule for entering the stage, in the route (403 forbidden_transition) and in can_rerun. It uses the authored move from the job's origin, or any authored move in when the post arrived by reseat or assignment, and the bypass list skips it as usual.
  3. Go back now takes the failed marker by compare-and-swap before it moves anything, holding it as reverting until the move is done, so it and Run again can't both win and no late run can slip in mid-move. The loser gets a 409 (agent_revert_conflict for Go back).

SPEC.md's stage-agent section is updated to match. One thing I noticed and left alone, because it predates this PR: a Go back that a soft-warning tool holds comes back to the editor as a plain success. Filed as #193.

smithjw1 and others added 12 commits November 13, 2026 16:10
A stage agent ran as the post author and nobody else. When an editor moved
someone else's post into an AI stage and the author could not edit posts, the
run stopped in place, and moving the post back and in again failed the same
way: the editor's identity was recorded on the job as `started_by` and then
used only for telemetry.

The run now acts as that person when they can still edit this post, re-checked
when the run fires, and falls back to the author otherwise. A run nobody
started (cron, a scheduled publish, a reseat with no one logged in) still has
only the author to act as, and still refuses rather than borrow anyone.

Revisions the agent writes are therefore authored by whoever moved the post in,
and still tagged with the agent. The no-actor message now says who has to move
the post for the agent to run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A failed AI stage offered one action, Go back, so retrying meant moving the
post out of its stage and back in. Now that a run acts as the person who
started it, a retry started by whoever is looking at the failure fixes the
failures a different identity can fix, so it no longer needs the round trip.

POST /workflow/post/{id}/agent-rerun dispatches a fresh run for a post whose
agent failed at its current stage, started by the current user. The post
stays put, the go-back origin is kept, and the loop-guard chain restarts.
The failed job payload carries can_rerun, and the panel and header lead with
Run again when it is set; Go back stays beside it in the panel.

The no-actor failure now says why the run stopped rather than what to do,
since the action is on the button: either the post moved in automatically
and its author can't edit posts, or the person who moved it here has lost
the right to edit it, and so has its author.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The header drew its button only when there was a move to offer. While a
stage agent runs, the stage withholds its exits, so the button vanished
between the press that started the run and the outcome: Run again showed
busy, disappeared, then came back. Moving a post into an AI stage did the
same.

While a run is pending, the main half now stays as a busy, disabled
"Agent working" button until the outcome arrives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…onal

An agent-to-agent hop took its starter from get_current_user_id() first
and fell back to the chain's starter only when nobody was logged in. A
cron run with an ambient user (wp cron event run --user=…, or a user an
earlier callback left set) made that user the next stage's starter, and
the run then acted with their rights. While an exit transition is in
progress, the carried starter now always wins, and a chain nobody started
stays nobody's.

Run again replaced the failed marker unconditionally, so two people
pressing it at once, or Run again racing Go back, could both succeed. The
pending marker now replaces the failed one only if it is still exactly the
marker that was checked; the loser gets 409 agent_rerun_conflict and
schedules nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…are-and-swap

The starter an agent exit carries was process-wide while the exit ran, so
a callback inside that transition that moved a different post into an AI
stage gave that post the exiting run's starter. It is now keyed by post and
applies only to the exiting post's own next stage. Separately, a dispatch
under cron no longer takes the logged-in user at all: nobody moved the post
there, whoever cron runs as.

Run again's conditional write used update_post_meta()'s $prev_value, which
adds the row when none exists. A Run again that read the failed marker
before a Go back deleted it could therefore still create a marker and queue
a run. The replace is now one UPDATE whose WHERE names the exact failed
marker; it never adds a row, so the stale request is refused with
agent_rerun_conflict and queues nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A refused Run again (409 agent_rerun_conflict when someone else ran it
first or took it back, or no_agent_rerun) reported the error but kept the
stale failed state on screen, so the panel and header went on offering a
Run again that could not succeed. The store action now re-reads the post's
status before rejecting, so both surfaces show what the post allows now.

Tests cover the refusal in the header (error notice, then the re-read
state) and the panel (the error, the re-read, Run again gone), and the
panel's success test now checks the failure and its actions leave.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Run again posted straight to /agent-rerun, so the agent read the stored
post and never saw what was on screen. That is the likeliest moment for
the editor to be dirty: the natural response to a failed run is to fix the
copy and press Run again. The agent then worked from the old text, and
when it routed the post on, the author's edits were lost on reload.

Run again now goes through the transition flow (requestRerun), which saves
first on exactly the terms a move into an AI stage uses: it waits out a
save in flight, asks what decideSave() asks, saves, and stops if the save
did not take. The wait-decide-save-verify sequence is one helper,
saveFirst(), shared by moves and Run again. Like entering an AI stage, Run
again is refused while another editor has the post open.

Also: a failed compare-and-swap query is now logged as a database error
rather than passing silently as a conflict, and comments in the panel,
the stylesheet and the agent-stages e2e spec no longer describe the failed
state as having only Go back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The spec said a stage agent runs as the post author only, that started_by
is used only for telemetry, and that a failed run offers only Go back.
It now says a run acts as whoever started it when they can still edit the
post, falling back to the author for runs nobody started; that a failed
run offers Run again (POST /workflow/post/{id}/agent-rerun) beside Go
back; and that Run again restarts the loop-guard chain. The footgun about
screens saying "Re-run" with no re-run action is removed.

This replaces the change this branch made to transition-rail.md, which
main has since deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Every entry into an AI stage writes a fresh job marker, even over a
  pending one left by an entry a person abandoned. The run acts as the
  person who made this entry, and Go back leads where this entry came
  from. Only the cron event is still deduplicated.
- Run again requires the sequence's role rules to allow the move that
  entered the stage (from the job's origin, or any move in when it has
  none). Otherwise 403 forbidden_transition, and can_rerun is false.
- Go back takes the failed marker by compare-and-delete before it moves
  the post, so it and Run again can't both succeed. The loser gets 409
  agent_revert_conflict; a refused move puts the failed marker back.
  The editor re-reads the post when Go back is refused, as it already
  did for Run again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the review of the previous commit:
- A marker for the run's stage that has already resolved (failed, or
  held for warnings) has no run left to serve, so a second cron event
  for the same post and stage returns without executing the agent.
  Cron only deduplicates events about ten minutes apart, inside the
  15-minute pending window.
- A reseat records the stage the post sat in, which has no authored
  edge into the AI stage, so nobody could run it again. When the
  recorded origin isn't an authored edge, any authored move in decides;
  a stage no edge leads into has no role rule to keep; the bypass list
  skips the check, as everywhere.
- The compare-and-swap and compare-and-delete share one helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the second review pass:
- Go back swapped the failed marker out by deleting it before the move,
  leaving the post at the AI stage with no marker for the length of the
  request; a late run event fired then would run the agent. It now swaps
  the marker for a `reverting` one, which the run guard treats as
  resolved, then clears it after the move or swaps `failed` back if the
  move doesn't happen (refused, or held for soft warnings).
- The Go back conflict test checks the refusal is shown.
- SPEC.md says a stage no authored move leads into has no Run again rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@smithjw1
smithjw1 force-pushed the fix/agent-runs-as-mover branch from 0f05314 to 18b6f81 Compare November 14, 2026 00:19

@alecgeatches alecgeatches left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Chris's three points above look fixed to me. One thing on top of those:

A crash during Go back can leave the post stuck in reverting

revert_failed_agent_stage() changes the marker from failed to reverting, then calls transition(). The marker is only put back when transition() returns something other than true:

$result = $this->transition( $post_id, $revert_to, array( 'agent_revert' => true ) );
if ( true !== $result ) {
        StageAgentRunner::take_job_marker( $post_id, $reverting, $failed_job );
        return $result;
}

If transition() throws, or the request dies before the stage is written (a fatal in a hooked callback, a timeout), nothing restores the marker. The post stays in the AI stage with status: reverting, and from there:

  • Run again refuses, because rerun() needs failed.
  • Go back refuses, because get_agent_revert_stage() needs failed.
  • Nothing expires it. The timeout only covers pending.

The only way out is one of the stage's normal moves. If the stage has none the person can take, someone has to fix the post meta by hand.

A try/finally that restores the failed marker would cover the exception case. Treating an old reverting marker as failed would also cover a request that dies outright. A test for the throwing case would be good, since I don't see one for this path.

Go back swaps the failed marker for a `reverting` one, moves the post,
and swaps it back if the move doesn't happen. If transition() threw, or
the request died before the move finished, nothing put it back: Run
again and Go back both need `failed`, and only `pending` times out, so
the post sat in the AI stage with neither on offer.

- A throw from transition() puts the failed marker back by
  compare-and-swap, then rethrows.
- The reverting marker is stamped with `reverting_at`. Read through
  StageAgentRunner::read_job_marker(), one older than REVERTING_TTL (five
  minutes) is swapped back to the failed marker, so a request that died
  outright recovers too. Go back's origin, Run again and the status
  payload all read through it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@smithjw1

Copy link
Copy Markdown
Contributor Author

Thanks, good catch. Fixed in e76cd6a, taking both of your suggestions. A throw from transition() now puts the failed marker back by compare-and-swap before rethrowing. The reverting marker is also stamped with the time, and a reverting marker older than five minutes reads as failed again. That covers a request that dies outright, and it's checked everywhere that offers Run again or Go back, including the status payload. Unit tests cover the throwing case, an abandoned marker for both Go back and Run again, and a fresh marker being left alone.

@smithjw1
smithjw1 requested a review from chriszarate November 16, 2026 18:04
@smithjw1
smithjw1 merged commit 92810c9 into main Nov 16, 2026
17 checks passed
@smithjw1
smithjw1 deleted the fix/agent-runs-as-mover branch November 16, 2026 18:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants