# Version a Running Temporal Workflow Safely

Yes. An agent wraps your workflow change in Temporal's patched() API so in-flight executions replay cleanly, adds replay tests on recorded histories and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-workflow-versioning/temporal/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent clones the repository into its own cloud sandbox and reads the workflow it is about to change. In a project like temporalio/money-transfer-project-template-ts, `src/workflows.ts` exports one workflow, `moneyTransfer(details: PaymentDetails)`, which proxies `withdraw`, `deposit` and `refund` from `src/activities.ts` with a retry policy (`initialInterval` of 1 second, `maximumInterval` of 1 minute, `backoffCoefficient` 2, `maximumAttempts` 500, `InvalidAccountError` and `InsufficientFundsError` non-retryable) and a `startToCloseTimeout` of 1 minute, then withdraws, deposits, and refunds when the deposit fails. `src/worker.ts` registers the workflows and activities on the `money-transfer` task queue from `src/shared.ts`; `src/client.ts` starts one with `workflowId: 'pay-invoice-801'`. Tests in `src/mocha/workflows.test.ts` use `TestWorkflowEnvironment.createLocal()` and `Worker.runUntil`, with the first test stubbing `withdraw` and `deposit` and the others running the real activities against the fake banks. The SDK packages are `@temporalio/*` at `~1.14.1` and the test runner is mocha through `npm test`.

The change the prompt names, say a `notify` activity after a successful deposit, is a new command in the workflow's event sequence. Deploying it plainly makes every execution that was started before the deploy and is still waiting on a retry fail to replay with a non-determinism error, because the recorded history has no notify step where the new code expects one. So the agent adds the activity to `src/activities.ts` and the proxy, then guards the call in `src/workflows.ts` with `patched('notify-after-deposit')` from `@temporalio/workflow`: executions that first reach that line on the new worker take the new path and record a marker; executions replaying a history recorded by the old code see no marker and skip it.

It then writes the rollout down so it actually completes. A comment next to the patch and a section in `README.md` describe the three deploys: ship with `patched()`; once no execution started before the first deploy is still running, which the Temporal CLI can list with a query on `WorkflowType` and `ExecutionStatus`, replace the guard with `deprecatePatch('notify-after-deposit')` and call the new code unconditionally; once no execution that recorded the marker remains, delete the `deprecatePatch` line. Without the written steps the `patched()` call tends to live forever, which is its own kind of debt.

To make the guarantee testable, the agent records a history from the pre-change workflow: it checks out the current `src/workflows.ts` as it was, runs an execution in `TestWorkflowEnvironment.createLocal()` with stubbed activities, fetches its history with the client's `fetchHistory`, and saves it as JSON under `src/mocha/histories/`. A new `src/mocha/replay.test.ts` feeds that file to `Worker.runReplayHistory` with the new `workflowsPath` and asserts no determinism error; a second history recorded from the patched code checks the marker path. The existing first test gets `notify` added to its stub map so it keeps passing, and `npm run lint`, `npm run build` and `npm test` run in the sandbox before the pull request opens.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add a notify activity that runs after a successful deposit in this Temporal TypeScript project, and make the change safe for executions already running. Read src/workflows.ts, src/activities.ts and the mocha tests first. Implement the activity, proxy it with the existing options, and guard the new call in the workflow with patched() from @temporalio/workflow under a named patch. Document the three-step rollout to deprecatePatch and removal in a comment and in the README. Record a workflow history from the pre-change code using the local test environment and the client's fetchHistory, save it under src/mocha/histories, and add a replay test that runs the new workflow code against it with Worker.runReplayHistory and asserts no determinism error, plus a second history and assertion for the patched path. Update the existing workflow tests for the new activity, run lint, build and the mocha suite, and open a pull request explaining what breaks without the patch.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `src/workflows.ts`, `src/activities.ts`, `src/mocha/workflows.test.ts` and `README.md`, and adds `src/mocha/replay.test.ts` with two recorded histories under `src/mocha/histories/`. The description explains, in terms of the recorded history, why an unguarded deploy would fail in-flight executions, and lists the three rollout steps with the CLI query that tells you when each is safe.

The run's record keeps the `npm test` output, where the replay tests are visible as their own cases, and the commands that produced the histories, so a reviewer can see the old history really came from the pre-change workflow rather than from the new code with the patch disabled.

Before merging, a reviewer checks the patch id is one they are happy to see in the Temporal UI for a while, confirms that the worker deploy order in their environment matches the rollout the README describes, and decides whether the replay test should also cover a history where the deposit failed and the refund ran, since the patch sits on the success path.

## Run it on every pull request that changes src/workflows.ts

In the console, an automation in the Project that has the repository, with a `github` trigger on `pull_request.opened`, starts one run per pull request with the event after the prompt. The prompt asks the run to finish at once unless a file under `src/workflows` changed, and otherwise to run every history under `src/mocha/histories/` through `Worker.runReplayHistory` with the branch's workflow code and to post a review comment naming each history that fails to replay and the line that introduced the new command, which is the review a human rarely has time to do by hand.

From your own tooling, a handler that receives GitHub's `pull_request` webhook sends one `POST /o/{org}/sessions` with the pull request URL in `resources` so the run checks out that branch, with a `request_id` that is a UUID v5 of the pull request id so a redelivery never starts a second run.

## Why run it on Rush?

Workflow versioning mistakes do not show up in unit tests or on a laptop; they show up in production, days later, as non-determinism errors on the executions that happened to be mid-retry during the deploy. The only honest test is a replay of a real recorded history against the new code, and producing that history means running the old code in a Temporal dev server, exporting the history, and keeping it with the tests. The agent does that in a sandbox where the local test environment can download and start the dev server, and every step is in the record.

The same request runs against every workflow change in every service that uses Temporal, each in its own sandbox, each producing its own replay histories, so the discipline of recording a history before changing a workflow stops depending on one engineer remembering it.

## Frequently asked questions

### Why not just deploy the change and let old executions fail?

Because a failed replay does not fail cleanly: the execution's workflow task errors and retries on every worker poll until someone resets or terminates it. With a retry policy of up to 500 attempts over a minute-long backoff, a transfer that was waiting on a flaky bank when you deployed can be stuck for a long time. The patch costs one marker event per new execution and avoids all of that.

### What exactly happens to executions started before the deploy?

When the new worker picks one up it replays the recorded history. `patched()` sees no marker for its id in that history, returns false, and the workflow takes the old path, so the replay matches the recording. Only executions that reach the patched line for the first time on the new worker record the marker and run the new code.

### When can the patched() call be removed?

In two steps. Switch to `deprecatePatch` once no execution that started on the old code is still running, which a `WorkflowType` and `ExecutionStatus` query on the CLI answers. Delete that line once no execution that recorded the marker is still running. The README section the pull request adds states both conditions.

### How is this different from Worker Versioning with build ids?

Worker Versioning pins each execution to the worker build that started it, so old code keeps running old executions and no patch is needed, at the cost of running two worker fleets until the old executions drain. `patched()` keeps one fleet and one codebase. They solve the same problem at different layers, and the pull request works either way.

### Do the recorded histories go stale?

They represent the code at the moment they were recorded, which is the point: they are the executions you could still have in flight. When a patch is fully removed, the history that exercised it can be deleted along with it. Histories from a stubbed test environment are small JSON files and the replay test over all of them runs in seconds.

## More Temporal jobs

- [Dockerize a Temporal TypeScript Worker](https://getrush.ai/run/dockerize-app/temporal/)
- [Prevent Duplicate Workflow Starts in a Temporal TypeScript App](https://getrush.ai/run/prevent-duplicate-workflows/temporal/)
- [Review Pull Requests to Temporal Go Workflows for Determinism](https://getrush.ai/run/review-pull-requests/temporal/)

## More jobs like this: Hand off a long task

- [Set Up Workload Identity on GKE with Terraform](https://getrush.ai/run/add-workload-identity/gke/)
- [Add zizmor to CI for Your GitHub Actions Workflows](https://getrush.ai/run/add-zizmor-to-ci/github-actions/)
- [Turn an Asana Task into a Pull Request for a Laravel App](https://getrush.ai/run/asana-task-to-pr/laravel/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
