Skip to content

Commit f37fd73

Browse files
committed
improvement(cli): make rerun-from-block a first-class run loop
- A failed run (workflows run, runs get, runs wait) whose failure names a block now carries `next`: `sim workflows run <workflowId> --from-block <blockId> --source-run <runId>`, so an agent fixes the block, applies, and reruns only the failing part on that run's upstream outputs. Parallel-branch ids and ids outside the issued format get no command. - The raw hidden `--run` JSON flag is gone; the run selection is built only from --manual, --trigger, --mock-payload, --from-block, --source-run and --stop-after. - `workflows run --help` and the --from-block/--source-run descriptions say what the rerun reuses; both source primers name the rerun flags in Run and debug, within the 4096-byte budget. - paused-run.ts becomes run-next.ts now that it names the next command for failed runs too.
1 parent 75894e2 commit f37fd73

10 files changed

Lines changed: 160 additions & 51 deletions

File tree

‎apps/docs/content/docs/cli/reference.mdx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8518,8 +8518,8 @@ sim workflows run <workflowId> [options]
85188518
| `--manual` | No | Run the current saved workflow state instead of the active deployment. |
85198519
| `--trigger <blockId>` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). |
85208520
| `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). |
8521-
| `--from-block <block>` | No | Run manually from this saved workflow block: its id, display name or key. |
8522-
| `--source-run <runId>` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). |
8521+
| `--from-block <block>` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. |
8522+
| `--source-run <runId>` | No | Earlier run of this workflow, deployed or draft, whose outputs the blocks before --from-block keep (requires --from-block). |
85238523
| `--stop-after <block>` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). Unless --select-output names others, blockOutputs holds the output of that block under its key (or id); output stays empty. |
85248524
| `--dir <dir>` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running. |
85258525
| `--wait-timeout <seconds>` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. |
@@ -8533,6 +8533,8 @@ Without --manual (or a flag that implies it) this runs the active deployment; a
85338533

85348534
The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output.
85358535

8536+
A run that failed in a block has next: the command that reruns the saved draft from that block with this run as --source-run, so after a fix only the failed block and those after it run again. Add --stop-after &lt;block&gt; to stop after a block; naming the failed block reruns only it.
8537+
85368538
Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed.
85378539

85388540
API request and response schemas: [executeWorkflow](/api-reference/workflows/executeWorkflowV2).

‎apps/docs/content/docs/cli/workflows.mdx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -835,8 +835,8 @@ sim workflows run <workflowId> [options]
835835
| `--manual` | No | Run the current saved workflow state instead of the active deployment. |
836836
| `--trigger <blockId>` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). |
837837
| `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). |
838-
| `--from-block <block>` | No | Run manually from this saved workflow block: its id, display name or key. |
839-
| `--source-run <runId>` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). |
838+
| `--from-block <block>` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. |
839+
| `--source-run <runId>` | No | Earlier run of this workflow, deployed or draft, whose outputs the blocks before --from-block keep (requires --from-block). |
840840
| `--stop-after <block>` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). Unless --select-output names others, blockOutputs holds the output of that block under its key (or id); output stays empty. |
841841
| `--dir <dir>` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running. |
842842
| `--wait-timeout <seconds>` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. |
@@ -850,6 +850,8 @@ Without --manual (or a flag that implies it) this runs the active deployment; a
850850

851851
The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output.
852852

853+
A run that failed in a block has next: the command that reruns the saved draft from that block with this run as --source-run, so after a fix only the failed block and those after it run again. Add --stop-after &lt;block&gt; to stop after a block; naming the failed block reruns only it.
854+
853855
Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed.
854856

855857
API request and response schemas: [executeWorkflow](/api-reference/workflows/executeWorkflowV2).

‎packages/sim-cli/src/commands/protocol/source-primer.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,21 +40,21 @@ const PARAMS_COMMAND = 'sim workflows source params'
4040

4141
/** The rules every source directory shares, after the kind's own edit loop. */
4242
function sharedRules(group: string, extraRenames = ''): string {
43-
return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, bound by its const or its display name. Rename display names (first argument) or consts, any number per apply, with any other edits: apply rewrites each reference, \`$ref.<key>\` in function files too. Renaming a block's const and its display name together (one such block per apply) keeps it only if settings, neighbours or references still match, else it is a delete (\`E_APPLY_BLOCK_DELETE\`).
44-
- **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), a child call \`runWorkflow('Name', { workflowId: childWorkflow('<key>') })\`'s response field as \`c.result.data.<field>\` (typed by its \`response\`), text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function file (\`codeFile('./functions/x.js')\`) read an output as \`$ref.<key>.<path>\`, the key: the display name lowercased, no whitespace or dots ("Triage Agent" → \`$ref.triageagent.content\`); in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\` (a parallel: \`$ref.parallel.…\`); env as \`$env.NAME\`. In \`.py\`/\`.sh\` files write \`<key.path>\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A \`$ref\` naming no block errors in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`).
43+
return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, bound by its const or display name. Rename display names (first argument) or consts, any number per apply, with other edits: apply rewrites every reference, \`$ref.<key>\` too. Renaming both a block's const and display name (one such block per apply) keeps it if settings, neighbours or references match, else it is a delete (\`E_APPLY_BLOCK_DELETE\`).
44+
- **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), a child call \`runWorkflow('Name', { workflowId: childWorkflow('<key>') })\`'s response field as \`c.result.data.<field>\` (typed by its \`response\`), text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function file (\`codeFile('./functions/x.js')\`) read an output as \`$ref.<key>.<path>\`, key: the display name lowercased, no whitespace or dots ("Triage Agent" → \`$ref.triageagent.content\`); in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\` (a parallel: \`$ref.parallel.…\`); env as \`$env.NAME\`. In \`.py\`/\`.sh\` files: \`<key.path>\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A \`$ref\` naming no block errors in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`).
4545
- **Renames**: one workflow variable per apply (two at once: delete + add).${extraRenames}
4646
- **Builders**: \`${PARAMS_COMMAND} <builder>\` (or a namespace).
4747
- **Credentials**: \`sim credentials connect <provider> --name "<Name>"\`, give the owner its link, then \`credential('<key>')\` (\`sim workflows source resources\`).
48-
- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, reading the message as \`x.error\` (a Function's \`x.errorMessage\` drops the line and code: reply with it). Retry is block meta (third argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\` reruns a failed block; an \`api\` block's \`retries\` repeat only the request (timeout, reset, 429, 5xx) inside each try. A reference to a block that did not run is \`null\` (a value, function code, a condition) or \`''\` in text. Branches may rejoin before one \`response\` (a function picks the value with \`??\`: \`.sim/examples/cookbook.ts\`); branches that end apart each need one.
49-
- **Run and debug**: \`--manual\` runs the saved draft, without it the deployed version. Runs write real data: use test resources. With \`--dir <workflow folder>\`, a failed run names the file and line; then \`sim logs get <runId> --trace --no-include-workflow-state\`; rows: \`sim tables rows list <table name>\`.
48+
- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, with the message in \`x.error\` (a Function's \`x.errorMessage\` lacks line and code: reply with it). Retry is block meta (third argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\` reruns a failed block; an \`api\` block's \`retries\` repeat only the request (timeout, reset, 429, 5xx) per try. A reference to a block that did not run is \`null\` (\`''\` in text). Branches may rejoin before one \`response\` (a function picks the value with \`??\`: \`.sim/examples/cookbook.ts\`); branches ending apart each need one.
49+
- **Run and debug**: \`--manual\` runs the saved draft, else the deployed version. Runs write real data: use test resources. With \`--dir <workflow folder>\` a failed run names its file and line; then \`sim logs get <runId> --trace --no-include-workflow-state\`; rows: \`sim tables rows list <table name>\`. Rerun from a block on a run's outputs: \`--from-block <block> --source-run <runId>\` (a failed run's \`next\`); \`--stop-after <block>\` stops after one.
5050
- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (\`${group} get --dir <fresh dir>\`, redo the edit there), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.`
5151
}
5252

5353
const WORKFLOW_PRIMER = `# Sim workflow source: primer
5454
55-
\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Run commands here: they read the workflow id from \`${SOURCE_BASE_FILE}\` (a starter has none: \`${SOURCE_STARTER_FILE}\` names its workspace, and its loop ends in \`sim workflows source create --dir . --yes\`, not \`apply\`, which makes the workflow), and each (table commands too) acts on its workspace; source commands refuse a \`-w\` naming another, the rest follow it.
55+
\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Run commands here: they read the workflow id from \`${SOURCE_BASE_FILE}\` (a starter has none: \`${SOURCE_STARTER_FILE}\` names its workspace, and its loop ends in \`sim workflows source create --dir . --yes\`, not \`apply\`, which makes the workflow), and each (table commands too) acts on its workspace; source commands refuse a \`-w\` naming another; others follow it.
5656
57-
**Edit loop**: write every file, then run one chained command and fix what it reports: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run <workflowId> --manual --input '{…}'\`. A non-zero exit stops the chain. \`check\` also type-checks (no \`tsc\`). Apply re-checks, so \`apply --dry-run\` is only for review. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit.
57+
**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run <workflowId> --manual --input '{…}'\`. A non-zero exit stops the chain. \`check\` also type-checks (no \`tsc\`). Apply re-checks: \`apply --dry-run\` only reviews. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit.
5858
5959
- **Deletes**: removing a block or a variable needs \`apply --allow-delete\` (\`E_APPLY_BLOCK_DELETE\` / \`E_APPLY_VARIABLE_DELETE\`).
6060
- **Deploy**: apply saves a draft; \`apply --deploy\` also deploys it, or \`sim workflows deploy <workflowId>\` publishes the saved draft later.
@@ -67,13 +67,13 @@ const WORKSPACE_RENAMES =
6767

6868
const WORKSPACE_PRIMER = `# Sim workspace source: primer
6969
70-
A Sim workspace as files (\`tables/\`, \`workflows/<key>/\`); nothing here runs. Run commands here: each (table commands too) acts on the workspace \`${SOURCE_BASE_FILE}\` names; source commands refuse a \`-w\` naming another, the rest follow it. Every \`.ts\` file starts with \`// @sim-sdk ${SDK_MAJOR}\`.
70+
A Sim workspace as files (\`tables/\`, \`workflows/<key>/\`); nothing here runs. Commands run here (table commands too) act on the workspace \`${SOURCE_BASE_FILE}\` names; source commands refuse a \`-w\` naming another; others follow it. Every \`.ts\` file starts with \`// @sim-sdk ${SDK_MAJOR}\`.
7171
72-
**Edit loop**: write every file, then run one chained command and fix what it reports: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`; test with \`sim workflows run <workflowId> --manual --input '{…}'\`. \`check\` also type-checks (no \`tsc\`). Apply re-checks, so \`apply --dry-run\` is only for review. Apply rewrites files: reread before editing.
72+
**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`; test with \`sim workflows run <workflowId> --manual --input '{…}'\`. \`check\` also type-checks (no \`tsc\`). Apply re-checks: \`apply --dry-run\` only reviews. Apply rewrites files: reread before editing.
7373
7474
- **Deletes**: removing a file, folder, column, block or variable needs \`apply --allow-delete\` and is permanent.
7575
- **Deploy**: \`deployments/<workflow key>.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys it on apply; without one, no deploy.
76-
- **Exit ${SOURCE_HELD_EXIT_CODE}**: partly written; changes needing an unset secret or unbound credential were held: set it, apply again.
76+
- **Exit ${SOURCE_HELD_EXIT_CODE}**: partly written; changes needing an unset secret or unbound credential are held: set it, reapply.
7777
${sharedRules('sim workspaces source', WORKSPACE_RENAMES)}
7878
`
7979

‎packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,12 +270,17 @@ describe('sim workflows run --wait-timeout', () => {
270270

271271
function program(): Command {
272272
const root = new Command()
273-
root.exitOverride()
274273
for (const command of buildGeneratedCommands()) root.addCommand(command)
275274

276275
const workflows = root.commands.find((command) => command.name() === 'workflows')
277276
if (!workflows) throw new Error('workflows group missing')
278277
attachWorkflowRunFollow(workflows)
278+
// On every leaf, not just the root: a parse error raised by `run` exits the process otherwise.
279+
const override = (command: Command) => {
280+
command.exitOverride().configureOutput({ writeErr: () => {} })
281+
command.commands.forEach(override)
282+
}
283+
override(root)
279284
return root
280285
}
281286

@@ -424,6 +429,41 @@ describe('sim workflows run --follow', () => {
424429
expect(requestRaw).not.toHaveBeenCalled()
425430
})
426431

432+
it('selects a run only through its flags, not as raw JSON', async () => {
433+
await expect(run(WORKFLOW_ID, '--run', '{"source":"manual"}')).rejects.toThrow(
434+
"unknown option '--run'"
435+
)
436+
expect(requestRaw).not.toHaveBeenCalled()
437+
})
438+
439+
it('prints with a failed run the command that reruns it from the failed block', async () => {
440+
requestRaw.mockResolvedValueOnce(
441+
ndjsonResponse({
442+
type: 'final',
443+
data: {
444+
runId: 'run-1',
445+
workflowId: WORKFLOW_ID,
446+
status: 'failed',
447+
output: {},
448+
error: { message: 'Agent failed', code: 'BLOCK_EXECUTION_FAILED', blockId: 'agent-1' },
449+
},
450+
})
451+
)
452+
const stdout = vi.spyOn(console, 'log').mockImplementation(() => {})
453+
454+
await expect(run(WORKFLOW_ID, '--manual')).rejects.toThrow('Agent failed')
455+
const next = JSON.parse(String(stdout.mock.calls[0][0])).next
456+
expect(next).toBe(`sim workflows run ${WORKFLOW_ID} --from-block agent-1 --source-run run-1`)
457+
458+
await run(...next.split(' ').slice(3))
459+
expect(requestRaw.mock.calls[1][1].body).toEqual({
460+
run: {
461+
source: 'manual',
462+
entry: { type: 'block', blockId: 'agent-1', sourceRunId: 'run-1' },
463+
},
464+
})
465+
})
466+
427467
it('prints then fails for a failed NDJSON run just like the JSON path', async () => {
428468
requestRaw.mockResolvedValue(
429469
ndjsonResponse({

0 commit comments

Comments
 (0)