Skip to content

Commit f6b17b3

Browse files
committed
fix(workflow-code): review round 1 for apply --run and get by name
- get <name> reads every page of matches before deciding exact or ambiguous. - A create whose --run fails names the apply of the created workflow next. - A failed test run carries the server's rerun from its enterable block. - Starters are taught create, not apply (primer, AGENTS.md pointer, root help); --allow keeps its test-resources warning; the standalone test run includes --input. - A deploy answering lint: null prints no lint field. - Record the intended `source get <workflow>` usage change in the docs baseline.
1 parent 21955e0 commit f6b17b3

10 files changed

Lines changed: 103 additions & 25 deletions

File tree

‎apps/docs/scripts/fixtures/content-baseline.json‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13171,8 +13171,8 @@
1317113171
{
1317213172
"lang": "bash",
1317313173
"meta": null,
13174-
"sha256": "29cc30facfddd548aa5873383ac3d90a6b392cf120894fd73a735f266196540d",
13175-
"bytes": 47,
13174+
"sha256": "6428ea92c442ec004f650fa6da178d53c3163dcd4895e1a24beb07bb93da1928",
13175+
"bytes": 45,
1317613176
"line": 8602
1317713177
},
1317813178
{
@@ -17743,8 +17743,8 @@
1774317743
{
1774417744
"lang": "bash",
1774517745
"meta": null,
17746-
"sha256": "29cc30facfddd548aa5873383ac3d90a6b392cf120894fd73a735f266196540d",
17747-
"bytes": 47,
17746+
"sha256": "6428ea92c442ec004f650fa6da178d53c3163dcd4895e1a24beb07bb93da1928",
17747+
"bytes": 45,
1774817748
"line": 1359
1774917749
},
1775017750
{

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,14 @@ ${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any build
5454
- Tables: \`table.queryRows\` outputs \`rows\` (\`recent.rows[0].data.status\`), not \`row\`; \`table.upsertRow\` takes \`conflictColumn: 'orderId'\`.
5555
- Rejoin: before one \`response\`, a Function picks the branch that ran with \`??\`.${extra.patterns ?? ''}
5656
- **Credentials**: \`sim credentials connect <provider> --name "<Name>"\`, send the owner its link, then \`credential('<key>')\`.
57-
- **Run**: \`sim workflows run <workflowId>\` runs the active deployment (\`--deployment-version <n>\`: that version); \`--draft\` runs the draft for real (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders; a read given one too: \`placeholder\`); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow <block>\` sends its writes; \`--mock <block>='{…}'\` fixes its output (bare, with \`--mock-from <runId>\`: that run's); a child's block: \`<workflow>.<block>\`.
57+
- **Run**: \`sim workflows run <workflowId>\` runs the active deployment (\`--deployment-version <n>\`: that version); \`--draft\` runs the draft for real (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders; a read given one too: \`placeholder\`); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow <block>\` sends its writes (use test resources); \`--mock <block>='{…}'\` fixes its output (bare, with \`--mock-from <runId>\`: that run's); a child's block: \`<workflow>.<block>\`.
5858
- **Debug**: \`--dir .\` maps a failure to file:line; \`sim logs get <runId> --trace --no-include-workflow-state\`; rows: \`sim tables rows list <table>\`; rerun: \`--from-block <block> --source-run <runId>\`; \`--stop-after <block>\`.
5959
- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo in a fresh \`${group} get\`), ${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.`
6060
}
6161

6262
const WORKFLOW_PRIMER = `# Sim workflow source: primer
6363
64-
\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Commands here (table ones too) act on the workflow \`${SOURCE_BASE_FILE}\` names and its workspace (a starter's \`${SOURCE_STARTER_FILE}\` names the workspace; its loop ends in \`sim workflows source create --dir . --yes\`).
64+
\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Commands here (table ones too) act on the workflow \`${SOURCE_BASE_FILE}\` names and its workspace (a starter's \`${SOURCE_STARTER_FILE}\` names the workspace, and its loop runs \`create\` where the loop below runs \`apply\`: no workflow exists until then).
6565
6666
**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 --run '{…}' --deploy\` applies, dry-runs that input on the draft, and deploys only if the run completed (no \`--deploy\`: stays a draft). \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites \`${SOURCE_ENTRY_FILE}\`: reread it before the next edit.
6767
@@ -106,7 +106,7 @@ export function agentsPointer(kind: PrimerKind): string {
106106
107107
${kind === 'workflow' ? '`workflow.ts` is a Sim workflow as TypeScript that Sim compiles' : 'This directory is a Sim workspace as files that Sim applies'}; nothing in it runs. Read \`${SOURCE_AGENTS_FILE}\` before editing: the rules, the edit loop, patterns and exit codes.
108108
109-
Loop: write every file, then one chained command: \`${group} check --dir . && ${group} apply --dir . --yes${kind === 'workflow' ? " --run '{…}' --deploy" : ''}\`; fix what it reports next.
109+
Loop: write every file, then one chained command: \`${group} check --dir . && ${group} apply --dir . --yes${kind === 'workflow' ? " --run '{…}' --deploy" : ''}\`; fix what it reports next.${kind === 'workflow' ? ` A starter (\`${SOURCE_STARTER_FILE}\`, no workflow yet) runs \`create\` in place of \`apply\`.` : ''}
110110
Exit codes: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (get a fresh copy and redo the edit), ${SOURCE_DRIFT_EXIT_CODE} \`status\`: the server changed.
111111
`
112112
}

‎packages/sim-cli/src/commands/protocol/workflow-dir.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ const ADVANCED_GUIDE = `# Sim workflow source: advanced
249249
250250
## Edit loop in detail
251251
252-
Batch it: write every file first, then run steps 2 and 4 (with a test run and the deploy) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes --run '{…}' --deploy\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 (with its \`apply --dry\`, which only plans) is for a person, CI, or a change you want reviewed first. The test run (\`--run\`, or \`sim workflows run <workflowId> --dry\`) is another thing than \`apply --dry\`: it executes the saved draft, while a run without \`--dry\` or \`--draft\` runs the active deployment (\`--deployment-version <n>\`: that deployed version). A dry run answers every tool call not declared read (sends, table writes, HTTP requests other than GET, HEAD or OPTIONS, custom and MCP tools) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent; check those payloads instead of reading back or cleaning up data. Placeholders are distinctive (\`dry_run_row_1\`, numbers above 900000000), and a read that would send one (a tool read, an API GET, a Function's fetch, its headers included) is not sent either and is listed with \`reason: 'placeholder'\`. An MCP tool is stubbed even when its server declares it read-only, which Sim cannot verify: that entry has \`reason: 'mcp-read-only'\`, and \`--allow <block>\` sends it. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, code an Agent's model writes) runs: its GET, HEAD and OPTIONS fetches are sent (an API that writes on a GET is not stubbed, so point those at a test resource), and any other fetch, or one carrying a method-override header, gets an empty 200 and is listed under \`sideEffects.stubbed\`; code in a remote sandbox (shell, Python, imports) is listed under \`sideEffects.unchecked\`, so check that list too. Child workflows run dry too, and custom, Human in the loop and Wait blocks are answered whole. \`--mock <block>='{…}'\` answers a block with fixed output to steer a branch; a bare \`--mock <block>\` with \`--mock-from <runId>\` replays that block's output from the recorded run (this workflow's blocks, not a child's; not inside a loop or parallel unless that run mocked it). \`--allow <block>\` sends that block's writes for real (a Function's fetches included) and \`--draft\` runs the draft with every write sent, so point both at test resources. \`--allow\` and \`--mock\` name a child workflow's block as \`<workflow>.<block>\`.
252+
Batch it: write every file first, then run steps 2 and 4 (with a test run and the deploy) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes --run '{…}' --deploy\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 (with its \`apply --dry\`, which only plans) is for a person, CI, or a change you want reviewed first. The test run (\`--run\`, or \`sim workflows run <workflowId> --dry --input '{…}'\`) is another thing than \`apply --dry\`: it executes the saved draft, while a run without \`--dry\` or \`--draft\` runs the active deployment (\`--deployment-version <n>\`: that deployed version). A dry run answers every tool call not declared read (sends, table writes, HTTP requests other than GET, HEAD or OPTIONS, custom and MCP tools) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent; check those payloads instead of reading back or cleaning up data. Placeholders are distinctive (\`dry_run_row_1\`, numbers above 900000000), and a read that would send one (a tool read, an API GET, a Function's fetch, its headers included) is not sent either and is listed with \`reason: 'placeholder'\`. An MCP tool is stubbed even when its server declares it read-only, which Sim cannot verify: that entry has \`reason: 'mcp-read-only'\`, and \`--allow <block>\` sends it. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, code an Agent's model writes) runs: its GET, HEAD and OPTIONS fetches are sent (an API that writes on a GET is not stubbed, so point those at a test resource), and any other fetch, or one carrying a method-override header, gets an empty 200 and is listed under \`sideEffects.stubbed\`; code in a remote sandbox (shell, Python, imports) is listed under \`sideEffects.unchecked\`, so check that list too. Child workflows run dry too, and custom, Human in the loop and Wait blocks are answered whole. \`--mock <block>='{…}'\` answers a block with fixed output to steer a branch; a bare \`--mock <block>\` with \`--mock-from <runId>\` replays that block's output from the recorded run (this workflow's blocks, not a child's; not inside a loop or parallel unless that run mocked it). \`--allow <block>\` sends that block's writes for real (a Function's fetches included) and \`--draft\` runs the draft with every write sent, so point both at test resources. \`--allow\` and \`--mock\` name a child workflow's block as \`<workflow>.<block>\`.
253253
254254
1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`.
255255
2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and \`apply --dry\` do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. \`apply --dry\` is the authority: a type error on a printed line you did not edit that it accepts can be skipped with \`--no-types\`.

‎packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1864,6 +1864,37 @@ describe('sim workflows source create on a directory with no workflow.ts', () =>
18641864
}
18651865
})
18661866

1867+
it('after a create whose test run fails, names the apply of the created workflow, not a second create', async () => {
1868+
setTerminal(false)
1869+
vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config'))
1870+
const starter = join(dir, 'new')
1871+
answerStarterAndCreate()
1872+
await create('--dir', starter)
1873+
vi.mocked(console.log).mockClear()
1874+
contextMockFns.mockRequestRaw.mockResolvedValue(
1875+
new Response(
1876+
JSON.stringify({
1877+
data: {
1878+
workflowId: WORKFLOW_ID,
1879+
runId: 'run-1',
1880+
status: 'failed',
1881+
error: { message: 'bad' },
1882+
},
1883+
}),
1884+
{ headers: { 'content-type': 'application/json' } }
1885+
)
1886+
)
1887+
1888+
await expect(create('--dir', starter, '--yes', '--run', '{}', '--deploy')).rejects.toThrow(
1889+
`run \`sim workflows source apply --dir ${starter} --run '{}' --deploy --yes\``
1890+
)
1891+
1892+
expect(existsSync(join(starter, '.sim/base.json'))).toBe(true)
1893+
expect(stdoutJson()).toMatchObject({
1894+
next: { command: `sim workflows source apply --dir ${starter} --run '{}' --deploy --yes` },
1895+
})
1896+
})
1897+
18671898
it.each(['--dry', '--yes'])('refuses %s instead of scaffolding', async (flag) => {
18681899
setTerminal(false)
18691900
vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config'))

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

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
liveDeploymentStatus,
2222
} from '../../runtime/deployment-live'
2323
import { runFailureMessage } from '../../runtime/execute'
24+
import { withRunNext } from '../../runtime/run-next'
2425
import { searchTasks } from '../search'
2526
import {
2627
type DeployedUrl,
@@ -184,6 +185,11 @@ async function writeWorkflowSource<Operation extends SourceWriteOperation>(args:
184185
ifAnswerLost: string
185186
/** This write as a command, without `--yes`: what a `plan` run names next with it. */
186187
command: string
188+
/**
189+
* The write to run again once this one is saved, without `--yes`: an apply's own command; a
190+
* create's is an apply of the workflow it created, whose name a second create finds taken.
191+
*/
192+
savedCommand: string
187193
}): Promise<void> {
188194
const { options, creating } = args
189195
assertSendableCodeFiles(args.body.files)
@@ -302,14 +308,14 @@ async function writeWorkflowSource<Operation extends SourceWriteOperation>(args:
302308
if (record.status !== 'completed') {
303309
await printRunFailureSite(options.dir, data.workflowId, record.error)
304310
const next = {
305-
command: `${args.command} --yes`,
311+
command: `${args.savedCommand} --yes`,
306312
reason: 'applies your fix and tests it again',
307313
}
308314
report(data, { next }, run)
309315
const why =
310316
runFailureMessage('executeWorkflow', record) ?? `it ended ${String(record.status)}`
311317
throw new SimApiError(
312-
`The ${verb} was saved into ${options.dir}, but the test run ${String(record.status)}: ${why}${options.deploy ? ' Nothing was deployed.' : ''} Fix the source, then run the same command again.`,
318+
`The ${verb} was saved into ${options.dir}, but the test run ${String(record.status)}: ${why}${options.deploy ? ' Nothing was deployed.' : ''} Fix the source, then run \`${args.savedCommand} --yes\`.`,
313319
0
314320
)
315321
}
@@ -321,7 +327,9 @@ async function writeWorkflowSource<Operation extends SourceWriteOperation>(args:
321327
machine: findings.machine,
322328
// Read only without --deploy: an untested draft's next names the tested deploy too.
323329
testedDeploy:
324-
run === undefined && !creating ? `${args.command} --yes --run '{…}' --deploy` : undefined,
330+
run === undefined && !creating
331+
? `${args.savedCommand} --yes --run '{…}' --deploy`
332+
: undefined,
325333
})
326334
)
327335
report(data, deployment, run)
@@ -334,19 +342,23 @@ interface TestRun {
334342
error?: unknown
335343
output: unknown
336344
sideEffects?: unknown
345+
next?: unknown
337346
}
338347

339348
/**
340349
* A `--run` record as the write's result shows it: the run id, status, error message, the
341-
* workflow's output and the side effects the dry run held back.
350+
* workflow's output, the side effects the dry run held back and, for a run that failed in a
351+
* block, the dry rerun from where the server says a rerun can start (none when it names none).
342352
*/
343353
function testRunResult(record: Record<string, unknown>): TestRun {
354+
const { next } = toRecord(withRunNext('executeWorkflow', record))
344355
return {
345356
runId: record.runId,
346357
status: record.status,
347358
...(record.error ? { error: toRecord(record.error).message ?? record.error } : {}),
348359
output: record.output,
349360
...(record.sideEffects ? { sideEffects: record.sideEffects } : {}),
361+
...(next ? { next } : {}),
350362
}
351363
}
352364

@@ -568,6 +580,11 @@ function deployFailure(
568580
)
569581
}
570582

583+
/** `sim workflows source apply` with the write flags `options` holds, without `--yes`. */
584+
function applyCommand(options: SourceWriteOptions): string {
585+
return `sim workflows source apply --dir ${shellWord(options.dir)}${options.allowDelete ? ' --allow-delete' : ''}${runFlag(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`
586+
}
587+
571588
/** Refuses `--deploy` or `--run` beside `--dry`: a dry run stores nothing to deploy or run. */
572589
function assertNotDry(options: SourceWriteOptions): void {
573590
if (!options.dry) return
@@ -658,7 +675,8 @@ export function attachWorkflowSourceApply(source: Command): void {
658675
mode,
659676
creating: false,
660677
question: `Apply these changes to workflow ${workflowId}?`,
661-
command: `sim workflows source apply --dir ${shellWord(options.dir)}${options.allowDelete ? ' --allow-delete' : ''}${runFlag(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`,
678+
command: applyCommand(options),
679+
savedCommand: applyCommand(options),
662680
output: profile.output,
663681
client,
664682
workspaceId: base.workspaceId,
@@ -776,6 +794,7 @@ export function attachWorkflowSourceCreate(source: Command): void {
776794
creating: true,
777795
question: 'Create this workflow?',
778796
command: `${createCommand(shellWord(options.dir), workspaceId)}${options.name !== undefined ? ` --name ${shellWord(options.name)}` : ''}${options.folder !== undefined ? ` --folder ${shellWord(options.folder)}` : ''}${runFlag(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`,
797+
savedCommand: applyCommand(options),
779798
output: profile.output,
780799
client,
781800
operation: 'createWorkflowFromSource',

‎packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,29 @@ describe('sim workflows source get <name>', () => {
201201
)
202202
})
203203

204+
it('reads every page of substring hits before deciding, so an exact match after the first is found', async () => {
205+
const hits = Array.from({ length: 100 }, (_, index) => ({
206+
id: `00000000-0000-4000-8000-${String(index).padStart(12, '1')}`,
207+
name: `Lead Scorer ${index}`,
208+
folderPath: '',
209+
}))
210+
serve({
211+
[LIST_PATH]: () => {
212+
const cursor = callsTo(LIST_PATH).at(-1)?.[1].query?.cursor
213+
return cursor
214+
? { data: [{ id: WORKFLOW_ID, name: 'Lead Scorer', folderPath: '' }], nextCursor: null }
215+
: { data: hits, nextCursor: 'page-2' }
216+
},
217+
})
218+
219+
expect(await getNamed('Lead Scorer')).toBeNull()
220+
221+
expect(callsTo(LIST_PATH)).toHaveLength(2)
222+
expect(JSON.parse(readFileSync(join(outDir, '.sim/base.json'), 'utf8')).workflowId).toBe(
223+
WORKFLOW_ID
224+
)
225+
})
226+
204227
it.each([
205228
[
206229
'several workflows hold the name',

0 commit comments

Comments
 (0)