From 1da9865a24eb9e79226cc35fa6406a645a3d6b48 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 19:39:28 -0800 Subject: [PATCH 1/3] fix(sim-cli): release audit follow-ups for the source loop - Mothership's chat gets workflow guides without apply --run/--deploy, and no tested-deploy hint - workspaces source apply --run holds deployments/ back when it would publish an untested draft - apply --run checks its input is JSON before anything is saved - source get by name refuses a blank name and searches at most 200 characters - list flags refuse an unparsable [..] value and an empty array, and keep a /files/ path whole - the merged --run apply reports the failing write's applyId --- apps/docs/content/docs/cli/reference.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- .../protocol/source-exit-codes.test.ts | 10 ++-- .../src/commands/protocol/source-tree.ts | 14 ++++-- .../src/commands/protocol/workflow-dir.ts | 48 +++++++++++++++---- .../protocol/workflow-source-apply.test.ts | 11 +++++ .../protocol/workflow-source-apply.ts | 34 +++++++++---- .../protocol/workflow-source-get.test.ts | 24 +++++++++- .../commands/protocol/workflow-source-get.ts | 14 +++++- .../protocol/workspace-source-apply.test.ts | 41 +++++++++++++++- .../protocol/workspace-source-apply.ts | 41 +++++++++++++++- .../commands/protocol/workspace-source-dir.ts | 4 +- packages/sim-cli/src/contract/types.ts | 5 +- .../src/runtime/file-references.test.ts | 13 +++++ packages/sim-cli/src/runtime/request.ts | 11 +++-- 15 files changed, 232 insertions(+), 42 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 171fccd38e6..922c4e3d0e6 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -10125,7 +10125,7 @@ sim workspaces source apply [options] | `--delete-target-only` | No | With --to and --allow-delete, also delete the target's resources this directory never declared and no promotion from it left there (prod-only tables and their rows, skills made in prod). Without it a promotion keeps them, naming each with a warning. | | `--only ` | No | Apply only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--to ` | No | Promote the directory to another workspace (dev to prod): its resources bind by key to that workspace's own and are updated in place. Only .sim/targets/<workspaceId>.json changes, the record the next promotion compares with: a resource changed there since is kept, or refused as stale (exit 5) when the directory changed it too. | -| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed; a run that does not complete exits 1 and leaves the applied drafts in place. | +| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. | diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index becf7a09a34..217965fcb56 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -759,7 +759,7 @@ sim workspaces source apply [options] | `--delete-target-only` | No | With --to and --allow-delete, also delete the target's resources this directory never declared and no promotion from it left there (prod-only tables and their rows, skills made in prod). Without it a promotion keeps them, naming each with a warning. | | `--only ` | No | Apply only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--to ` | No | Promote the directory to another workspace (dev to prod): its resources bind by key to that workspace's own and are updated in place. Only .sim/targets/<workspaceId>.json changes, the record the next promotion compares with: a resource changed there since is kept, or refused as stale (exit 5) when the directory changed it too. | -| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed; a run that does not complete exits 1 and leaves the applied drafts in place. | +| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. | diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts index d8352182f2a..e1f22537921 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import * as exitCodes from '../../exit-codes' import { sourceExitCodesHelp, sourceExitCodesTable } from './source-exit-codes' +import type { PrimerSurface } from './source-primer' import { WORKFLOW_TREE } from './workflow-dir' import { WORKSPACE_TREE } from './workspace-source-dir' @@ -17,13 +18,14 @@ const SOURCE_EXIT_CODES = [ ].sort((a, b) => a - b) /** Everything a get writes beside the primer for an agent to read: `.sim/AGENTS.md` and the guides. */ -const guidesOf = (tree: typeof WORKFLOW_TREE) => - [tree.agents, ...(tree.guides ?? []).map(([, text]) => text)].join('\n') +const guidesOf = (tree: typeof WORKFLOW_TREE, surface: PrimerSurface) => + [tree.agents(surface), ...(tree.guides?.(surface) ?? []).map(([, text]) => text)].join('\n') describe('the exit-code tables an agent or a reader relies on', () => { it.each([ - ['the workflow directory guides', guidesOf(WORKFLOW_TREE)], - ['the workspace directory guides', guidesOf(WORKSPACE_TREE)], + ['the workflow directory guides', guidesOf(WORKFLOW_TREE, 'cli')], + ["the workflow directory guides Mothership's chat reads", guidesOf(WORKFLOW_TREE, 'chat')], + ['the workspace directory guides', guidesOf(WORKSPACE_TREE, 'cli')], ])('%s list every code a source command exits with', (_name, text) => { const listed = [...text.matchAll(/^\| (\d+) \|/gm)].map((match) => Number(match[1])) expect(listed).toEqual(SOURCE_EXIT_CODES) diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index d078b94f023..fffd0e19a5f 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -57,6 +57,7 @@ import { AGENTS_POINTER_MARKER, agentsPointer, type PrimerKind, + type PrimerSurface, primerFor, primerSurface, } from './source-primer' @@ -633,10 +634,13 @@ export function editLoop(kind: PrimerKind, dir: string): string[] { export interface SourceTreeProfile { /** Which primer opens `.sim/AGENTS.md`. */ kind: PrimerKind - /** The reference in `.sim/AGENTS.md`, below the primer. */ - agents: string + /** + * The reference in `.sim/AGENTS.md`, below the primer, for the surface that reads it: a guide + * Mothership's chat reads never names a flag its shell refuses. + */ + agents: (surface: PrimerSurface) => string /** More guides beside `.sim/AGENTS.md` (path → text), rewritten every time like it. */ - guides?: ReadonlyArray + guides?: (surface: PrimerSurface) => ReadonlyArray /** * A `tsconfig.json` the CLI writes, starting with {@link TSCONFIG_MARKER}, that type-checks the * source with the SDK declarations `sdkFiles` (directory-relative paths). @@ -839,8 +843,8 @@ export async function sourceTreeChange( const surface = primerSurface() const primer = primerFor(profile.kind, surface, catalog, sources) const write: Array = [ - [SOURCE_AGENTS_FILE, `${primer}\n${profile.agents}`], - ...(profile.guides ?? []), + [SOURCE_AGENTS_FILE, `${primer}\n${profile.agents(surface)}`], + ...(profile.guides?.(surface) ?? []), ...Object.entries(COOKBOOK_EXAMPLES).map( ([file, text]) => [`${SOURCE_EXAMPLES_DIR}/${file}`, text] as const ), diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 31999489f5c..78b9aaaccf6 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -37,6 +37,7 @@ import { writeBack, } from './source-dir' import { sourceExitCodesTable } from './source-exit-codes' +import type { PrimerSurface } from './source-primer' import { STRICT_FINDINGS_CLAUSE } from './source-strict' import { assertSdkMajor, @@ -214,19 +215,20 @@ const WORKFLOW_ADVANCED_FILE = '.sim/GUIDE-advanced.md' /** * The reference below the primer in `.sim/AGENTS.md`: the flags of the edit loop and the file - * shape. The rest, by task, is in {@link ADVANCED_GUIDE}, which agents read only when a step + * shape. The rest, by task, is in {@link advancedGuide}, which agents read only when a step * needs it, and the docs page has everything. */ -const AGENTS_GUIDE = `# Reference +function agentsGuide(surface: PrimerSurface): string { + return `# Reference The primer above is enough to edit. \`${WORKFLOW_ADVANCED_FILE}\` has the rest, by task: the edit loop step by step and what a dry run stubs, a new workflow or a fork, finding a builder and its types, the rules, and every diagnostic and exit code. The full guide: ${SOURCE_DOCS_URL} ## Flags - \`check\`: \`--strict\` fails on the warnings that name a real problem in every block, not only in a block you added; \`--no-types\` skips the type-check. -- \`apply\`: \`--yes\` writes (without it and a terminal, it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}); \`--dry\` only plans; \`--allow-delete\`; \`--deploy\`. +- \`apply\`: \`--yes\` writes (without it and a terminal, it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}); \`--dry\` only plans; \`--allow-delete\`${surface === 'cli' ? '; `--deploy`' : ''}. - \`get\`: \`--force\` replaces edits no apply has saved, or another workflow's source. -- \`sim workflows run\`: the primer's **Run** and **Debug**. +- ${surface === 'cli' ? "`sim workflows run`: the primer's **Run** and **Debug**." : "Test runs and deploys go through sim_cli, as the shell refuses runs: the primer's edit loop, **Run** and **Debug**."} ## File shape @@ -244,18 +246,45 @@ export default workflow('Workflow name', {}, () => { The \`// @sim-sdk ${SDK_MAJOR}\` header must be the first line, and the file has exactly one \`export default workflow(name, options, () => { ... })\`; \`options\` holds \`description\` and \`variables\` and may be \`{}\`. ` +} + +/** + * How a test run and the deploy follow the apply in {@link advancedGuide}: chained onto it in a + * coding agent's shell, through `sim_cli` in Mothership's, whose shell refuses runs. + */ +const ADVANCED_TEST_AND_DEPLOY: Record< + PrimerSurface, + { batch: string; testRun: string; applyStep: string } +> = { + cli: { + batch: + "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.", + testRun: "`--run`, or `sim workflows run --dry --input '{…}'`", + applyStep: + "`--run '{…}'` then dry-runs that input on the saved draft (`run` in the result: status, output, side effects; a failed run exits 1 and maps the failing block to file:line), and `--deploy` deploys it only if that run completed (alone, it deploys right after the apply). Without `--deploy`, a deployed workflow's next is `sim workflows deploy --expected-draft-fingerprint `, which deploys only the draft this apply saved; after an apply without `--run` its reason names the same apply with `--run '{…}' --deploy`, which tests and deploys in one step.", + }, + chat: { + batch: + "Batch it: write every file first, then run steps 2 and 4 as one chained command in run_code's shell, `sim workflows source check --dir . && sim workflows source apply --dir . --yes`, and fix what it reports in the next step.", + testRun: "sim_cli's `workflows run --dry --input '{…}' --dir `", + applyStep: + "Then test it with sim_cli, as the shell refuses runs: `workflows run --dry --input '{…}' --dir ` (`--dir` maps a failure to file:line), and deploy only the draft that run tested with `workflows deploy --expected-draft-fingerprint ` (the fingerprint in `.sim/base.json`).", + }, +} /** The workflow guide's deep dives, which `.sim/AGENTS.md` points to in one line. */ -const ADVANCED_GUIDE = `# Sim workflow source: advanced +function advancedGuide(surface: PrimerSurface): string { + const { batch, testRun, applyStep } = ADVANCED_TEST_AND_DEPLOY[surface] + return `# Sim workflow source: advanced ## Edit loop in detail -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 --dry --input '{…}'\`) is another thing than \`apply --dry\`: it executes the saved draft, while a run without \`--dry\`, \`--draft\` or a flag that implies the draft (\`--trigger\`, \`--sample\`, \`--stop-after\`, \`--from-block\`) runs the active deployment (\`--deployment-version \`: 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, when present (each list keeps a bounded number of entries and counts the rest in \`sideEffects.omitted\`, so check it before treating a list as complete); 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 \` 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 ='{…}'\` answers a block with fixed output to steer a branch; a bare \`--mock \` with \`--mock-from \` 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 \` 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 \`.\`. +${batch} 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 (${testRun}) is another thing than \`apply --dry\`: it executes the saved draft, while a run without \`--dry\`, \`--draft\` or a flag that implies the draft (\`--trigger\`, \`--sample\`, \`--stop-after\`, \`--from-block\`) runs the active deployment (\`--deployment-version \`: 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, when present (each list keeps a bounded number of entries and counts the rest in \`sideEffects.omitted\`, so check it before treating a list as complete); 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 \` 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 ='{…}'\` answers a block with fixed output to steer a branch; a bare \`--mock \` with \`--mock-from \` 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 \` 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 \`.\`. 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}\`. 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\`. 3. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry\` until it exits 0. -4. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--run '{…}'\` then dry-runs that input on the saved draft (\`run\` in the result: status, output, side effects; a failed run exits 1 and maps the failing block to file:line), and \`--deploy\` deploys it only if that run completed (alone, it deploys right after the apply). Without \`--deploy\`, a deployed workflow's next is \`sim workflows deploy --expected-draft-fingerprint \`, which deploys only the draft this apply saved; after an apply without \`--run\` its reason names the same apply with \`--run '{…}' --deploy\`, which tests and deploys in one step. Its first line, \`summary\`, gives the counts, findings, test run and what is live; its last lines repeat \`errors\`, \`warnings\` and \`live\`, which says what serves: \`not deployed\`, \`version N, matches the draft\`, \`version N, draft has undeployed changes\`, or after \`--deploy\` \`version N still serving; version M activating\` until the deploy is live (\`sim workflows deployment status \` shows when). It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). +4. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). ${applyStep} Its first line, \`summary\`, gives the counts, findings, test run and what is live; its last lines repeat \`errors\`, \`warnings\` and \`live\`, which says what serves: \`not deployed\`, \`version N, matches the draft\`, \`version N, draft has undeployed changes\`, or after a deploy \`version N still serving; version M activating\` until the deploy is live (\`sim workflows deployment status \` shows when). It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). 5. Exit ${SOURCE_STALE_EXIT_CODE} (\`SOURCE_STALE\`, HTTP 409, or \`E_APPLY_STALE\` on a dry run): the workflow changed and nothing was saved. Run \`sim workflows source get --dir \`, reapply your edit there, dry-run, apply. A get into this directory refuses to overwrite your unapplied edits unless you pass \`--force\`. Exit ${SOURCE_STALE_EXIT_CODE} right after an apply that ended without an answer (a timeout, a dropped connection) means the draft changed, by that apply or by someone else: get into a fresh directory and compare. Only when it holds your edit, run \`sim workflows source get --dir . --force\`; otherwise reapply your edit in the fresh directory. Editing the \`workflow('…')\` name or description renames or redescribes the workflow; a name another workflow in its folder holds is refused with \`E_NAME_TAKEN\`. Lines starting \`note:\` explain something the write did differently than the source says; read them. @@ -289,6 +318,7 @@ ${sourceExitCodesTable('sim workflows source')} The full guide: ${SOURCE_DOCS_URL} ` +} /** The printed source a tree write saves: a get's answer, or an applied create's. */ export type PrintedSource = Pick< @@ -373,8 +403,8 @@ function printedReads(compiled: CompileResult | null): PrintedReads { /** The workflow directory's tree beside the printed source. */ export const WORKFLOW_TREE: SourceTreeProfile = { kind: 'workflow', - agents: AGENTS_GUIDE, - guides: [[WORKFLOW_ADVANCED_FILE, ADVANCED_GUIDE]], + agents: agentsGuide, + guides: (surface) => [[WORKFLOW_ADVANCED_FILE, advancedGuide(surface)]], tsconfig: workflowTsconfig, } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index c73be919692..471e2e469e1 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -1148,6 +1148,17 @@ describe('sim workflows source apply', () => { expect(request).not.toHaveBeenCalled() expect(contextMockFns.mockRequestRaw).not.toHaveBeenCalled() }) + + it('refuses an input that is not JSON before saving anything', async () => { + setTerminal(false) + serveDeploy() + + const failure = apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', '{bad', '--deploy') + + await expect(failure).rejects.toThrow(/--run: its input is not JSON. Nothing was saved./) + expect(request).not.toHaveBeenCalled() + expect(contextMockFns.mockRequestRaw).not.toHaveBeenCalled() + }) }) it('deploys through the deploy operation once the apply is saved', async () => { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index 52fb0916c6a..fcaba47f35f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -21,6 +21,7 @@ import { liveDeploymentStatus, } from '../../runtime/deployment-live' import { runFailureMessage } from '../../runtime/execute' +import { readArgumentSource } from '../../runtime/request' import { searchTasks } from '../search' import { type DeployedUrl, @@ -48,6 +49,7 @@ import { writeBack, } from './source-dir' import { sourceExitCodesHelp } from './source-exit-codes' +import { primerSurface } from './source-primer' import { cachedCatalogByHash, printTreeResult, refreshWorkflowWorkspaceTypes } from './source-tree' import { type CreatedResource, @@ -325,8 +327,9 @@ async function writeWorkflowSource(args: verb, machine: findings.machine, // Read only without --deploy: an untested draft's next names the tested deploy too. + // Mothership's shell refuses runs: its chat tests through sim_cli, then deploys by fingerprint. testedDeploy: - run === undefined && !creating + run === undefined && !creating && primerSurface() === 'cli' ? `${args.savedCommand} --yes --run '{…}' --deploy` : undefined, }) @@ -557,19 +560,30 @@ function applyCommand(options: SourceWriteOptions): string { return `sim workflows source apply --dir ${shellWord(options.dir)}${options.allowDelete ? ' --allow-delete' : ''}${runFlag(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}` } -/** Refuses `--deploy` or `--run` beside `--dry`: a dry run stores nothing to deploy or run. */ -function assertNotDry(options: SourceWriteOptions): void { - if (!options.dry) return - if (options.deploy) { +/** + * The write options with `--run`'s input read and checked as JSON, before anything is saved: a + * bad input never leaves a saved draft behind an error. Refuses `--deploy` or `--run` beside + * `--dry`, as a dry run stores nothing to deploy or run. + */ +async function checkedWriteOptions(options: SourceWriteOptions): Promise { + if (options.dry && options.deploy) { throw new CliUsageError( '--deploy deploys what the write saves, and --dry saves nothing: drop one of them.' ) } - if (options.run !== undefined) { + if (options.dry && options.run !== undefined) { throw new CliUsageError( '--run test-runs what the write saves, and --dry saves nothing: drop one of them.' ) } + if (typeof options.run !== 'string') return options + const { text } = await readArgumentSource(options.run, 'run') + try { + JSON.parse(text) + } catch { + throw new CliUsageError('--run: its input is not JSON. Nothing was saved.') + } + return { ...options, run: text } } /** `--run [input]` and `--deploy` on a write: test the saved draft, then deploy it. */ @@ -631,7 +645,7 @@ export function attachWorkflowSourceApply(source: Command): void { await withSourceCommandLock( options.dir, async () => { - assertNotDry(options) + const checked = await checkedWriteOptions(options) await assertSourceDirKind(options.dir, 'workflow') const { client, profile } = connectApply() const lock = await readLock(options.dir) @@ -643,7 +657,7 @@ export function attachWorkflowSourceApply(source: Command): void { } const childResults = isReadOnly(mode) ? undefined : await folderChildResults(options.dir) await writeWorkflowSource<'applyWorkflowSource'>({ - options, + options: checked, mode, creating: false, question: `Apply these changes to workflow ${workflowId}?`, @@ -744,7 +758,7 @@ export function attachWorkflowSourceCreate(source: Command): void { }) return } - assertNotDry(options) + const checked = await checkedWriteOptions(options) const { client, profile } = connectCreate() // A directory is bound to the workspace it records: a starter to the one its types were // written for (--workspace still chooses another), a workspace folder to its workspace. @@ -761,7 +775,7 @@ export function attachWorkflowSourceCreate(source: Command): void { } const childResults = isReadOnly(mode) ? undefined : await folderChildResults(options.dir) await writeWorkflowSource<'createWorkflowFromSource'>({ - options, + options: checked, mode, creating: true, question: 'Create this workflow?', diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts index 24a1fadde01..317cac54211 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts @@ -267,6 +267,24 @@ describe('sim workflows source get ', () => { expect(existsSync(join(outDir, '.sim/base.json'))).toBe(false) } ) + + it('refuses a blank name before listing anything', async () => { + serve({ [LIST_PATH]: listed({ id: WORKFLOW_ID, name: 'Lead Scorer' }) }) + + for (const name of ['', ' ']) { + expect(await getNamed(name)).toMatchObject({ code: 'WORKFLOW_NOT_FOUND' }) + } + expect(callsTo(LIST_PATH)).toHaveLength(0) + }) + + it('finds a name longer than the list search takes by its first 200 characters', async () => { + const long = `${'Lead Scorer '.repeat(20)}final` + serve({ [LIST_PATH]: listed({ id: WORKFLOW_ID, name: long }) }) + + expect(await getNamed(long)).toBeNull() + + expect(callsTo(LIST_PATH)[0][1].query?.search).toBe(long.slice(0, 200)) + }) }) describe('sim workflows source get --dir', () => { @@ -522,7 +540,9 @@ describe('sim workflows source get --dir', () => { it('writes the chat primer and pointer inside Mothership, and the coding-agent ones elsewhere', async () => { const guides = () => - ['.sim/AGENTS.md', 'AGENTS.md'].map((file) => readFileSync(join(outDir, file), 'utf8')) + ['.sim/AGENTS.md', 'AGENTS.md', '.sim/GUIDE-advanced.md'].map((file) => + readFileSync(join(outDir, file), 'utf8') + ) serve() await get('--dir', outDir) for (const guide of guides()) { @@ -534,7 +554,7 @@ describe('sim workflows source get --dir', () => { await get('--dir', outDir, '--force') for (const guide of guides()) { - expect(guide).not.toMatch(/ --run(?![\w-])/) + expect(guide).not.toMatch(/--run '|(^|[\s`])--deploy(?![\w-])/m) expect(guide).toContain('with sim_cli') } }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts index 1f5bc161bbb..8cf5c02eb77 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -62,6 +62,12 @@ async function assertNoLocalEdits(dir: string, source: PrintedSource): Promise { if (isValidUuid(workflow)) return workflow + const search = workflow.trim().slice(0, SEARCH_MAX_LENGTH) + if (search === '') { + throw new CliUsageError('Name a workflow: its id or exact name.', { + code: 'WORKFLOW_NOT_FOUND', + }) + } const workspaceId = client.requireWorkspace(inWorkspace) // Every page: an exact match or a second one can sort after the first page of substring hits. const found = await client.requestAllPages( 'listWorkflows', - { query: { workspaceId, search: workflow }, pageSize: DEFAULT_PAGE_SIZE } + { query: { workspaceId, search }, pageSize: DEFAULT_PAGE_SIZE } ) const exact = found.filter(({ name }) => name === workflow) if (exact.length === 1) return exact[0].id diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index df5e7a3afa3..6098e0b684d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -2162,7 +2162,9 @@ describe('workspaces source apply', () => { new Response(JSON.stringify({ data: { workflowId: 'wf_1', runId: 'run-1', ...record } }), { headers: { 'content-type': 'application/json' }, }) - const applies = () => request.mock.calls.filter((call) => call[0] === APPLY_PATH) + /** The writes: an apply sent without `?dry`. */ + const applies = () => + request.mock.calls.filter((call) => call[0] === APPLY_PATH && !call[1]?.query?.dry) /** Answers the first write with the workflow saved, the second with the deployment. */ const serveApplies = () => request.mockImplementation(async (path: string, options: { body?: { kinds?: string[] } }) => { @@ -2264,6 +2266,43 @@ describe('workspaces source apply', () => { }) }) + it('applies nothing of deployments/ when it would also publish a draft no run tested', async () => { + write('deployments/other.ts', DEPLOYMENT) + request.mockImplementation(async (path: string, options: { body?: { kinds?: string[] } }) => { + if (path === '/api/v2/workflows/wf_1/deployment') return deploymentStatus(1) + const base = { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } } + return options.body?.kinds?.includes('deployment') + ? answer({ + plan: [ + { kind: 'deployment', key: 'ingest', action: 'update', fields: ['live version'] }, + { kind: 'deployment', key: 'other', action: 'update', fields: ['live version'] }, + ], + applied: [], + base, + }) + : answer({ + plan: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + applied: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + files: { 'workflows/ingest/workflow.ts': `${INGEST}// stored\n` }, + base, + }) + }) + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'completed', output: {} }) + ) + + const failure = apply('--yes', '--run', 'ingest={}') + + await expect(failure).rejects.toThrow( + /would also publish the untested draft of workflows\/other\/, so deployments\/ was not applied/ + ) + expect(applies()).toHaveLength(1) + const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect(printed.next.command).toBe( + `sim workspaces source apply --dir ${dir} --run 'ingest={}' --run 'other={…}' --yes` + ) + }) + it('exits as written in part when the deployments write holds every deployment back', async () => { request.mockImplementation(async (path: string, options: { body?: { kinds?: string[] } }) => { if (path === '/api/v2/workflows/wf_1/deployment') return deploymentStatus(1) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index a878d8f9310..c18579ca07a 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -738,7 +738,7 @@ export function attachWorkspaceSourceApply(source: Command): void { ) .option( '--run ', - "After the apply, dry-run workflows//'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed; a run that does not complete exits 1 and leaves the applied drafts in place", + "After the apply, dry-run workflows//'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place", collectRepeated ) .allowExcessArguments(false) @@ -1068,6 +1068,20 @@ export function attachWorkspaceSourceApply(source: Command): void { ) } if (!before) return finish(data) + const untested = await afterWrite(async () => + untestedPublishes(await send(before.read, true, before.read.kinds), tested) + ) + if (untested.length > 0) { + const next = { + command: `${applyCommand(options)}${untested.map((key) => ` --run ${shellWord(`${key}={…}`)}`).join('')} --yes`, + reason: 'tests every draft deployments/ publishes, then deploys them', + } + await finish(data, next) + throw new SimApiError( + `The apply was written into ${options.dir} and every test run completed, but ${KIND_DIRS.deployment}/ would also publish the untested draft of ${untested.map((key) => `${workflowFolder(key)}/`).join(', ')}, so ${KIND_DIRS.deployment}/ was not applied. Test each with --run, then run \`${next.command}\`.`, + 0 + ) + } const deployed = await afterWrite(async () => { const after = (await readDeploymentWrite()).read const tested = before.read.files @@ -1183,6 +1197,26 @@ async function readRunInputs(runs: readonly RunRequest[]): Promise ) } +/** + * The workflow keys whose draft the deployments write `preview` would publish (a first deploy, or + * `live: 'draft'` taking a differing draft live) without a completed test run: `--run` deploys + * only drafts it tested, so these hold the whole deployments write back. + */ +function untestedPublishes(preview: ApplyData, tested: readonly WorkflowTestRun[]): string[] { + const testedKeys = new Set( + tested.filter((run) => run.status === 'completed').map((run) => run.workflow) + ) + return preview.plan + .filter( + (change) => + isDeployment(change) && + !testedKeys.has(change.key) && + (change.fields ?? []).some((field) => field === 'deploy' || field === 'live version') + ) + .map((change) => change.key) + .sort(compareStrings) +} + /** The `paths` whose text in `actual` is not the text in `expected`. */ function changedPaths( expected: Readonly>, @@ -1224,6 +1258,9 @@ function withoutDeployments(submission: WorkspaceSubmission): WorkspaceSubmissio * its findings on them repeat the first's. */ function mergedApply(first: ApplyData, deployed: ApplyData): ApplyData { + // The write whose id support looks up: the deployments write's when its `E_APPLY_FAILED` hint + // names it (it failed part-way), else the first's. + const applyId = deployed.failed ? deployed.applyId : first.applyId return { ...deployed, plan: [...first.plan, ...deployed.plan.filter(isDeployment)], @@ -1233,7 +1270,7 @@ function mergedApply(first: ApplyData, deployed: ApplyData): ApplyData { ...first.diagnostics, ...deployed.diagnostics.filter((finding) => finding.kind !== 'workflow'), ], - ...(first.applyId ? { applyId: first.applyId } : {}), + ...(applyId ? { applyId } : {}), } } diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 2d75468b89c..33f15336798 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -210,8 +210,8 @@ Keep \`${WORKSPACE_BASE_FILE}\` and each workflow's \`.sim/\` files as written. /** The workspace directory's tree beside the printed source. */ export const WORKSPACE_TREE: SourceTreeProfile = { kind: 'workspace', - agents: AGENTS_GUIDE, - guides: [[WORKSPACE_ADVANCED_FILE, ADVANCED_GUIDE]], + agents: () => AGENTS_GUIDE, + guides: () => [[WORKSPACE_ADVANCED_FILE, ADVANCED_GUIDE]], tsconfig: workspaceTsconfig, // Workspace files and knowledge base documents are bytes, kept as they are (`-text`, after the // LF lines it overrides): a commit that rewrote their line endings would change their hashes. diff --git a/packages/sim-cli/src/contract/types.ts b/packages/sim-cli/src/contract/types.ts index 698fad3954d..b82f0fea167 100644 --- a/packages/sim-cli/src/contract/types.ts +++ b/packages/sim-cli/src/contract/types.ts @@ -59,7 +59,10 @@ export interface FlagSpec { * selector naming a block `Draft, Review`), so a comma never splits it. A folder path list * reads this way without saying so. * - `fileReferences`: workspace file ids or `files/…` paths. A comma splits ids, never a value - * that is a `files/` path, so a path keeps a comma in its name. + * holding a `/`, so a path (`files/…`, `/files/…`) keeps a comma in its name. + * + * Outside `text`, a value starting `[` that is not a JSON array of strings is refused, so a + * shell that stripped the quotes never sends `[a,b]` as one id. */ listValues?: 'text' | 'fileReferences' /** diff --git a/packages/sim-cli/src/runtime/file-references.test.ts b/packages/sim-cli/src/runtime/file-references.test.ts index 9d95acc30d6..4a4d7a4a14c 100644 --- a/packages/sim-cli/src/runtime/file-references.test.ts +++ b/packages/sim-cli/src/runtime/file-references.test.ts @@ -54,6 +54,19 @@ describe('files batch-delete reads the references a caller writes', () => { expect(await sentFileIds(['--paths', 'files/qc/a,b.png', 'files/c.png'])).toEqual([ ['files/qc/a,b.png', 'files/c.png'], ]) + expect(await sentFileIds(['--paths', '/files/Reports/Q1, Q2.pdf'])).toEqual([ + ['/files/Reports/Q1, Q2.pdf'], + ]) + }) + + it('refuses an empty JSON array, or a bracketed value that is not one, before any request', async () => { + const empty = await run(['files', 'batch-delete', '--ids', '[]', '--yes']) + expect(empty.exitCode).toBe(1) + expect(empty.stderr).toContain('--file-ids values cannot be empty') + const unquoted = await run(['files', 'batch-delete', '--ids', '[wf_a,wf_b]', '--yes']) + expect(unquoted.exitCode).toBe(1) + expect(unquoted.stderr).toContain('--file-ids must be a JSON array of strings: [wf_a,wf_b]') + expect([...empty.bodies, ...unquoted.bodies]).toEqual([]) }) it('refuses two spellings at once, before any request', async () => { diff --git a/packages/sim-cli/src/runtime/request.ts b/packages/sim-cli/src/runtime/request.ts index 1ff2dc51d64..ba29fdec1a3 100644 --- a/packages/sim-cli/src/runtime/request.ts +++ b/packages/sim-cli/src/runtime/request.ts @@ -335,7 +335,7 @@ export function listValuesOf(flag: FlagSpec): 'ids' | 'text' | 'fileReferences' /** Whether `value`, read as `listValues`, is a comma-joined run of entries. */ function splitsOnCommas(value: string, listValues: ReturnType): boolean { if (!value.includes(',')) return false - if (listValues === 'fileReferences') return !value.startsWith('files/') + if (listValues === 'fileReferences') return !value.includes('/') return listValues === 'ids' } @@ -353,9 +353,14 @@ function listEntries( : splitsOnCommas(value, listValues) ? value.split(',') : undefined - if (!entries) return [value] + if (!entries) { + if (value.startsWith('[') && listValues !== 'text') { + throw new SimApiError(`--${flagName} must be a JSON array of strings: ${value}`, 0) + } + return [value] + } const trimmed = entries.map((entry) => entry.trim()) - if (trimmed.some((entry) => !entry)) { + if (trimmed.length === 0 || trimmed.some((entry) => !entry)) { throw new SimApiError(`--${flagName} values cannot be empty: ${value}`, 0) } return trimmed From 9a5156c0962f775db58fda9a2522fb626d0c26ad Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 19:49:54 -0800 Subject: [PATCH 2/3] fix(sim-cli): validate --run before a starter, cut long name searches on a character, gate deployment creates --- .../commands/protocol/workflow-source-apply.test.ts | 11 +++++++++++ .../src/commands/protocol/workflow-source-apply.ts | 2 +- .../src/commands/protocol/workflow-source-get.test.ts | 9 +++++++++ .../src/commands/protocol/workflow-source-get.ts | 6 +++++- .../src/commands/protocol/workspace-source-apply.ts | 7 ++++--- 5 files changed, 30 insertions(+), 5 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index 471e2e469e1..074e2748a46 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -1748,6 +1748,17 @@ describe('sim workflows source create on a directory with no workflow.ts', () => await program().parseAsync(['node', 'sim', 'workflows', 'source', 'create', ...argv]) } + it('refuses a --run input that is not JSON before writing a starter', async () => { + const empty = join(dir, 'new') + + await expect(create('--dir', empty, '--run', '{bad')).rejects.toThrow( + /--run: its input is not JSON/ + ) + + expect(existsSync(join(empty, 'workflow.ts'))).toBe(false) + expect(request).not.toHaveBeenCalled() + }) + it('writes a starter workflow.ts, the types, tsconfig and the guide, and creates nothing', async () => { setTerminal(false) vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config')) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index fcaba47f35f..85c0e56218c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -735,6 +735,7 @@ export function attachWorkflowSourceCreate(source: Command): void { options.dir, async () => { await assertSourceDirKind(options.dir, 'workflow') + const checked = await checkedWriteOptions(options) if ((await readSourceText(options.dir, ENTRY_FILE)) === null) { if (options.dry || options.yes) { throw new SourceDirError( @@ -758,7 +759,6 @@ export function attachWorkflowSourceCreate(source: Command): void { }) return } - const checked = await checkedWriteOptions(options) const { client, profile } = connectCreate() // A directory is bound to the workspace it records: a starter to the one its types were // written for (--workspace still chooses another), a workspace folder to its workspace. diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts index 317cac54211..ca6d4be1c02 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts @@ -285,6 +285,15 @@ describe('sim workflows source get ', () => { expect(callsTo(LIST_PATH)[0][1].query?.search).toBe(long.slice(0, 200)) }) + + it('never cuts the search inside a character a long name holds', async () => { + const long = `${'a'.repeat(199)}😀 scorer` + serve({ [LIST_PATH]: listed({ id: WORKFLOW_ID, name: long }) }) + + expect(await getNamed(long)).toBeNull() + + expect(callsTo(LIST_PATH)[0][1].query?.search).toBe('a'.repeat(199)) + }) }) describe('sim workflows source get --dir', () => { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts index 8cf5c02eb77..a992a686d04 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -80,7 +80,11 @@ async function resolveWorkflow( inWorkspace?: string ): Promise { if (isValidUuid(workflow)) return workflow - const search = workflow.trim().slice(0, SEARCH_MAX_LENGTH) + // Cut on a character boundary: half an emoji would search for a name no workflow holds. + const search = workflow + .trim() + .slice(0, SEARCH_MAX_LENGTH) + .replace(/[\uD800-\uDBFF]$/, '') if (search === '') { throw new CliUsageError('Name a workflow: its id or exact name.', { code: 'WORKFLOW_NOT_FOUND', diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index c18579ca07a..5d5b5e3bec6 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -1198,8 +1198,8 @@ async function readRunInputs(runs: readonly RunRequest[]): Promise } /** - * The workflow keys whose draft the deployments write `preview` would publish (a first deploy, or - * `live: 'draft'` taking a differing draft live) without a completed test run: `--run` deploys + * The workflow keys whose draft the deployments write `preview` would publish (a deployment + * created: a first deploy, or `live: 'draft'` taking a differing draft live) without a completed test run: `--run` deploys * only drafts it tested, so these hold the whole deployments write back. */ function untestedPublishes(preview: ApplyData, tested: readonly WorkflowTestRun[]): string[] { @@ -1211,7 +1211,8 @@ function untestedPublishes(preview: ApplyData, tested: readonly WorkflowTestRun[ (change) => isDeployment(change) && !testedKeys.has(change.key) && - (change.fields ?? []).some((field) => field === 'deploy' || field === 'live version') + (change.action === 'create' || + (change.fields ?? []).some((field) => field === 'deploy' || field === 'live version')) ) .map((change) => change.key) .sort(compareStrings) From 8d3812fd2beffb24aa552d3007ff4ed38a4199be Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 19:59:51 -0800 Subject: [PATCH 3/3] fix(sim-cli): chat redeploy hint names the sim_cli test run; chat guide deploys only after a completed run --- .../sim-cli/src/commands/protocol/workflow-dir.ts | 2 +- .../commands/protocol/workflow-source-apply.test.ts | 12 ++++++++++++ .../src/commands/protocol/workflow-source-apply.ts | 8 +++++--- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 78b9aaaccf6..0dc4a6945da 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -268,7 +268,7 @@ const ADVANCED_TEST_AND_DEPLOY: Record< "Batch it: write every file first, then run steps 2 and 4 as one chained command in run_code's shell, `sim workflows source check --dir . && sim workflows source apply --dir . --yes`, and fix what it reports in the next step.", testRun: "sim_cli's `workflows run --dry --input '{…}' --dir `", applyStep: - "Then test it with sim_cli, as the shell refuses runs: `workflows run --dry --input '{…}' --dir ` (`--dir` maps a failure to file:line), and deploy only the draft that run tested with `workflows deploy --expected-draft-fingerprint ` (the fingerprint in `.sim/base.json`).", + "Then test it with sim_cli, as the shell refuses runs: `workflows run --dry --input '{…}' --dir ` (`--dir` maps a failure to file:line), and only if that run completed, deploy the draft it tested with `workflows deploy --expected-draft-fingerprint ` (the fingerprint in `.sim/base.json`).", }, } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index 074e2748a46..78dbf8f49c2 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -1270,6 +1270,18 @@ describe('sim workflows source apply', () => { ) }) + it('inside Mothership, names the test run through sim_cli, never --run or --deploy, in the reason', async () => { + setTerminal(false) + vi.stubEnv('SIM_CLI_HOST', 'mothership') + request.mockResolvedValue(outcome()) + + await apply(WORKFLOW_ID, '--dir', dir, '--yes') + + const reason = String(toRecord(stdoutJson().next).reason) + expect(reason).toContain(`sim_cli (\`workflows run ${WORKFLOW_ID} --dry`) + expect(reason).not.toMatch(/--run|--deploy/) + }) + it.each([ [null, false, 'not deployed'], [3, false, 'version 3, matches the draft'], diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index 85c0e56218c..4ea768dc846 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -327,9 +327,8 @@ async function writeWorkflowSource(args: verb, machine: findings.machine, // Read only without --deploy: an untested draft's next names the tested deploy too. - // Mothership's shell refuses runs: its chat tests through sim_cli, then deploys by fingerprint. testedDeploy: - run === undefined && !creating && primerSurface() === 'cli' + run === undefined && !creating ? `${args.savedCommand} --yes --run '{…}' --deploy` : undefined, }) @@ -462,7 +461,10 @@ async function deployStep( return { next: { command: deployCommand, - reason: `The workflow is deployed and its draft now differs from the live version: deploy to make the change live (or ${options.verb} with --deploy).${options.testedDeploy ? ` The draft is untested: \`${options.testedDeploy}\` tests and deploys it in one step.` : ''}`, + reason: + primerSurface() === 'chat' + ? `The workflow is deployed and its draft now differs from the live version: test the draft with sim_cli (\`workflows run ${data.workflowId} --dry --input '{…}'\`), then deploy it if that run completed.` + : `The workflow is deployed and its draft now differs from the live version: deploy to make the change live (or ${options.verb} with --deploy).${options.testedDeploy ? ` The draft is untested: \`${options.testedDeploy}\` tests and deploys it in one step.` : ''}`, }, } }