From bca093dd27ef53a191ddd3151ac04fa4b0af4ca3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:58:32 -0800 Subject: [PATCH 1/2] fix(sim-cli): consistent source command flags and refusals - workflows source resources and catalog take --dir (the directory's workspace, and for catalog its workflow); catalog --workflow-id takes an exact name like get - --json (same as --output json, errors included) on every workflows/workspaces source subcommand; an unknown --json elsewhere suggests --output json - SOURCE_DIR_KIND_MISMATCH names the command run, says 'would replace its base' only for get, and points at the workflow folder or the matching command - the not-found hint says -w , which the wire-name rewording no longer turns into -w <--workspace> - writing a source answer back skips files whose text on disk is already the answer's, so a no-op apply moves no mtimes --- apps/docs/content/docs/cli/reference.mdx | 34 +++++-- apps/docs/content/docs/cli/workflows.mdx | 27 +++++- apps/docs/content/docs/cli/workspaces.mdx | 7 +- .../sim-cli/src/commands/protocol/index.ts | 11 ++- .../commands/protocol/source-dir/dir-kind.ts | 30 ++++-- .../protocol/source-dir/write-back.ts | 54 +++++++++-- .../src/commands/protocol/workflow-dir.ts | 11 ++- .../protocol/workflow-source-apply.ts | 6 +- .../protocol/workflow-source-check.test.ts | 2 +- .../protocol/workflow-source-check.ts | 2 +- .../protocol/workflow-source-find.test.ts | 16 ++++ .../commands/protocol/workflow-source-find.ts | 2 +- .../commands/protocol/workflow-source-get.ts | 6 +- .../protocol/workflow-source-reads.ts | 70 ++++++++++++++ .../workflow-source-roundtrip.test.ts | 26 +++++ .../protocol/workflow-source-status.ts | 16 ++-- .../protocol/workspace-source-apply.ts | 2 +- .../protocol/workspace-source-check.test.ts | 2 +- .../protocol/workspace-source-check.ts | 2 +- .../commands/protocol/workspace-source-dir.ts | 4 +- .../commands/protocol/workspace-source-get.ts | 2 +- .../protocol/workspace-source-status.ts | 17 ++-- packages/sim-cli/src/context.ts | 23 +++-- packages/sim-cli/src/contract/commands.ts | 8 +- packages/sim-cli/src/runtime/build.ts | 4 +- packages/sim-cli/src/runtime/execute.test.ts | 4 +- packages/sim-cli/src/runtime/execute.ts | 6 +- packages/sim-cli/src/terminal.test.ts | 96 ++++++++++++++++++- packages/sim-cli/src/terminal.ts | 13 ++- 29 files changed, 407 insertions(+), 96 deletions(-) create mode 100644 packages/sim-cli/src/commands/protocol/workflow-source-reads.ts diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 7a79c0a3ed7..30f1fece6ee 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8596,7 +8596,9 @@ sim workflows source catalog [options] | Option | Required | Description | | --- | --- | --- | -| `--workflow-id ` | No | Return the source catalog for this workflow: the workspace catalog plus every block type already placed in it, the ones the caller could not add marked `addable: false`. | +| `--workflow-id ` | No | Workflow id, or its exact name: adds every block type already placed in it, the ones the caller could not add marked `addable: false`. | +| `--dir ` | No | Source directory whose workspace and workflow to read (default: the one the command runs in). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -8607,9 +8609,20 @@ API request and response schemas: [getSourceCatalog](/api-reference/catalog/getS List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names source can name ```bash -sim workflows source resources +sim workflows source resources [options] ``` +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--dir ` | No | Source directory whose workspace to read (default: the one the command runs in). | +| `--json` | No | Print machine-readable JSON (same as --output json). | + + + API request and response schemas: [getSourceResources](/api-reference/workflows/getSourceResources). ### sim workflows source get @@ -8639,6 +8652,7 @@ sim workflows source get [options] | `--function-code ` | No | Where function-block code goes: `files` (default) writes it to `functions/*` files referenced with `codeFile()`; `inline` prints it in tagged templates. Accepted values: `inline`, `files`. | | `--dir ` | No | Write the source, its lock and SDK type declarations into this directory instead of printing them. | | `--force` | No | With --dir: replace another workflow's source or edits no apply has saved. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -8678,6 +8692,7 @@ sim workflows source apply [workflowId] [options] | `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. With several triggers (an API and a webhook), name the one to enter through by its const: --run 'shopWebhook={…}' (--run shopWebhook alone: no input). Repeat --run to test more inputs or triggers: every run is made and reported, and --deploy needs all to complete. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. | | `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). | | `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -8708,6 +8723,7 @@ sim workflows source create [options] | `-y, --yes` | No | Create without asking for confirmation. | | `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. With several triggers (an API and a webhook), name the one to enter through by its const: --run 'shopWebhook={…}' (--run shopWebhook alone: no input). Repeat --run to test more inputs or triggers: every run is made and reported, and --deploy needs all to complete. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. | | `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -8734,6 +8750,7 @@ sim workflows source check [options] | `--no-strict` | No | Never fail on a warning an apply saves. | | `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -8762,7 +8779,7 @@ sim workflows source status [options] | `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--offline` | No | Report local changes only, without asking the server. | -| `--json` | No | Print the machine-readable status (same as --output json). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -8798,7 +8815,7 @@ sim workflows source diff [paths...] [options] | --- | --- | --- | | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--server` | No | Compare with the server's current source instead of the base. | -| `--json` | No | Print the machine-readable diff (same as --output json). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -8832,6 +8849,7 @@ sim workflows source params [options] | --- | --- | --- | | `--dir ` | No | Source directory whose catalog to read. Defaults to `.`. | | `--full` | No | Print every param with its type, enum, default and doc, not the brief form. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -8864,6 +8882,7 @@ sim workflows source find [options] | Option | Required | Description | | --- | --- | --- | | `--dir ` | No | Workflow source directory to read. Defaults to `.`. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -10093,6 +10112,7 @@ sim workspaces source get [options] | `--dir ` | Yes | Directory to write the workspace source into. | | `--only ` | No | Read only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--force` | No | Replace files with edits no apply has saved. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -10126,6 +10146,7 @@ sim workspaces source apply [options] | `--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, 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. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -10152,6 +10173,7 @@ sim workspaces source check [options] | `--no-strict` | No | Never fail on a warning an apply saves. | | `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -10183,7 +10205,7 @@ sim workspaces source status [options] | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--only ` | No | Report only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--offline` | No | Report local changes only, without asking the server. | -| `--json` | No | Print the machine-readable status (same as --output json). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -10219,7 +10241,7 @@ sim workspaces source diff [paths...] [options] | --- | --- | --- | | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--server` | No | Compare with the server's current source instead of the base. | -| `--json` | No | Print the machine-readable diff (same as --output json). | +| `--json` | No | Print machine-readable JSON (same as --output json). | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 1ba505bb7d7..cae7347fca5 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1396,6 +1396,7 @@ sim workflows source get [options] | `--function-code ` | No | Where function-block code goes: `files` (default) writes it to `functions/*` files referenced with `codeFile()`; `inline` prints it in tagged templates. Accepted values: `inline`, `files`. | | `--dir ` | No | Write the source, its lock and SDK type declarations into this directory instead of printing them. | | `--force` | No | With --dir: replace another workflow's source or edits no apply has saved. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1418,7 +1419,7 @@ sim workflows source status [options] | `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--offline` | No | Report local changes only, without asking the server. | -| `--json` | No | Print the machine-readable status (same as --output json). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1449,6 +1450,7 @@ sim workflows source create [options] | `-y, --yes` | No | Create without asking for confirmation. | | `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. With several triggers (an API and a webhook), name the one to enter through by its const: --run 'shopWebhook={…}' (--run shopWebhook alone: no input). Repeat --run to test more inputs or triggers: every run is made and reported, and --deploy needs all to complete. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. | | `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1486,6 +1488,7 @@ sim workflows source apply [workflowId] [options] | `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. With several triggers (an API and a webhook), name the one to enter through by its const: --run 'shopWebhook={…}' (--run shopWebhook alone: no input). Repeat --run to test more inputs or triggers: every run is made and reported, and --deploy needs all to complete. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. | | `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). | | `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1505,7 +1508,9 @@ sim workflows source catalog [options] | Option | Required | Description | | --- | --- | --- | -| `--workflow-id ` | No | Return the source catalog for this workflow: the workspace catalog plus every block type already placed in it, the ones the caller could not add marked `addable: false`. | +| `--workflow-id ` | No | Workflow id, or its exact name: adds every block type already placed in it, the ones the caller could not add marked `addable: false`. | +| `--dir ` | No | Source directory whose workspace and workflow to read (default: the one the command runs in). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1528,6 +1533,7 @@ sim workflows source check [options] | `--no-strict` | No | Never fail on a warning an apply saves. | | `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1563,7 +1569,7 @@ sim workflows source diff [paths...] [options] | --- | --- | --- | | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--server` | No | Compare with the server's current source instead of the base. | -| `--json` | No | Print the machine-readable diff (same as --output json). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1596,6 +1602,7 @@ sim workflows source find [options] | Option | Required | Description | | --- | --- | --- | | `--dir ` | No | Workflow source directory to read. Defaults to `.`. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1629,6 +1636,7 @@ sim workflows source params [options] | --- | --- | --- | | `--dir ` | No | Source directory whose catalog to read. Defaults to `.`. | | `--full` | No | Print every param with its type, enum, default and doc, not the brief form. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1639,9 +1647,20 @@ Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one i ### List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names source can name ```bash -sim workflows source resources +sim workflows source resources [options] ``` +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--dir ` | No | Source directory whose workspace to read (default: the one the command runs in). | +| `--json` | No | Print machine-readable JSON (same as --output json). | + + + API request and response schemas: [getSourceResources](/api-reference/workflows/getSourceResources). ## Related docs diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 68812f900c7..994577a7f38 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -703,6 +703,7 @@ sim workspaces source get [options] | `--dir ` | Yes | Directory to write the workspace source into. | | `--only ` | No | Read only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--force` | No | Replace files with edits no apply has saved. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -728,7 +729,7 @@ sim workspaces source status [options] | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--only ` | No | Report only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--offline` | No | Report local changes only, without asking the server. | -| `--json` | No | Print the machine-readable status (same as --output json). | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -760,6 +761,7 @@ sim workspaces source apply [options] | `--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, 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. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -784,6 +786,7 @@ sim workspaces source check [options] | `--no-strict` | No | Never fail on a warning an apply saves. | | `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--json` | No | Print machine-readable JSON (same as --output json). | @@ -821,7 +824,7 @@ sim workspaces source diff [paths...] [options] | --- | --- | --- | | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--server` | No | Compare with the server's current source instead of the base. | -| `--json` | No | Print the machine-readable diff (same as --output json). | +| `--json` | No | Print machine-readable JSON (same as --output json). | diff --git a/packages/sim-cli/src/commands/protocol/index.ts b/packages/sim-cli/src/commands/protocol/index.ts index 6a5b72a897e..54c319adbbb 100644 --- a/packages/sim-cli/src/commands/protocol/index.ts +++ b/packages/sim-cli/src/commands/protocol/index.ts @@ -29,6 +29,7 @@ import { attachWorkflowSourceCheck } from './workflow-source-check' import { attachWorkflowSourceFind } from './workflow-source-find' import { attachWorkflowSourceGet } from './workflow-source-get' import { attachWorkflowSourceParams } from './workflow-source-params' +import { attachWorkflowSourceReads } from './workflow-source-reads' import { attachWorkflowSourceDiff, attachWorkflowSourceStatus } from './workflow-source-status' import { attachWorkspaceOperationWait } from './workspace-operation-wait' import { attachWorkspaceSourceApply } from './workspace-source-apply' @@ -90,9 +91,9 @@ export function attachProtocolCommands(program: Command): void { folders: 'listWorkflowFolders', createFolder: 'createWorkflowFolder', }) - // All four augment commands the generated pass already built — `run` gains `--follow`, - // `runs get` gains block names, `runs` gains `wait`, and `source get` gains `--dir` — so they - // must attach after it, which is the order `buildProgram` calls them in. + // These augment commands the generated pass already built — `run` gains `--follow`, `runs get` + // gains block names, `runs` gains `wait`, and `source get`, `resources` and `catalog` gain + // `--dir` — so they must attach after it, which is the order `buildProgram` calls them in. attachWorkflowRunFollow(workflows) const runs = group(workflows, 'runs') attachWorkflowRunGet(runs) @@ -110,6 +111,7 @@ export function attachProtocolCommands(program: Command): void { attachWorkflowSourceDiff(source) attachWorkflowSourceParams(source) attachWorkflowSourceFind(source) + attachWorkflowSourceReads(source) const workspaces = group(program, 'workspaces') attachWorkspaceOperationWait(group(workspaces, 'operations')) @@ -122,6 +124,9 @@ export function attachProtocolCommands(program: Command): void { attachWorkspaceSourceCheck(workspaceSource) attachWorkspaceSourceStatus(workspaceSource) attachWorkspaceSourceDiff(workspaceSource) + for (const leaf of [...source.commands, ...workspaceSource.commands]) { + leaf.option('--json', 'Print machine-readable JSON (same as --output json)') + } attachLogsFollow(group(program, 'logs')) diff --git a/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts b/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts index 83ae693c68a..c87eee28848 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts @@ -77,18 +77,36 @@ async function sourceDirKind( return null } +/** The subcommands both `sim workflows source` and `sim workspaces source` have. */ +const SHARED_SOURCE_COMMANDS: ReadonlySet = new Set([ + 'get', + 'apply', + 'check', + 'status', + 'diff', +]) + /** - * Refuses a `kind` command on a directory of the other kind, whatever `--force` says: a workflow - * get into a workspace directory (or the reverse) would replace its base, so staleness could no - * longer be detected and its unapplied edits would sit in a directory neither command reads. + * Refuses `sim s source ` on a directory of the other kind, whatever `--force` + * says: a get would replace its base, so staleness could no longer be detected and its unapplied + * edits would sit in a directory neither command reads, and any other command reads a directory + * of its own kind only. The refusal names the commands that do act on the directory. */ -export async function assertSourceDirKind(dir: string, kind: SourceDirKind): Promise { +export async function assertSourceDirKind( + dir: string, + kind: SourceDirKind, + command: string +): Promise { const held = await sourceDirKind(dir) if (held === null || held.kind === kind) return + const run = `sim ${kind}s source ${command}` + const reason = + command === 'get' ? `so \`${run}\` would replace its base` : `which \`${run}\` does not read` + const anotherDirectory = command === 'get' ? `, or get the ${kind} into another directory` : '' const message = held.kind === 'workspace' - ? `${dir} is a workspace source directory${held.readFrom ? ` (workspace ${held.readFrom})` : ''}, so a \`sim workflows source\` command would replace its base. Edit a workflow of it in ${dir}/${KIND_DIRS.workflow}/ with \`sim workspaces source\` (check, status, apply) --dir ${dir}, or get the workflow into another directory.` - : `${dir} is a workflow source directory${held.readFrom ? ` (workflow ${held.readFrom})` : ''}, so a \`sim workspaces source\` command would replace its base. Use \`sim workflows source\` (get, check, status, apply) --dir ${dir}, or get the workspace into another directory.` + ? `${dir} is a workspace source directory${held.readFrom ? ` (workspace ${held.readFrom})` : ''}, ${reason}. Run it on one of its workflow folders (--dir ${dir}/${KIND_DIRS.workflow}/)${SHARED_SOURCE_COMMANDS.has(command) ? `, or run \`sim workspaces source ${command} --dir ${dir}\`` : ''}${anotherDirectory}.` + : `${dir} is a workflow source directory${held.readFrom ? ` (workflow ${held.readFrom})` : ''}, ${reason}. Run \`sim workflows source ${command}${command === 'get' ? ' ' : ''} --dir ${dir}\`${anotherDirectory}.` throw new SourceDirError(message, { code: 'SOURCE_DIR_KIND_MISMATCH' }) } diff --git a/packages/sim-cli/src/commands/protocol/source-dir/write-back.ts b/packages/sim-cli/src/commands/protocol/source-dir/write-back.ts index 5824db7a80c..93d67458358 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/write-back.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/write-back.ts @@ -3,6 +3,7 @@ * files, lock and base in one staged update, and the records that say the CLI wrote them. */ +import { mapWithConcurrency } from '@sim/utils/concurrency' import { toRecord } from '@sim/utils/object' import { compareStrings } from '@sim/utils/string' import { codeFileReferences } from '@sim/workflow-code/code-files/references' @@ -15,7 +16,14 @@ import { import { fingerprintOf } from '@sim/workspace-code' import { printError } from '#sim-cli/output/io' import { type WorkspaceFolder, workspaceFolderOf } from './dir-kind' -import { readSourceJson, readSourceText, type SourceDirChange, updateSourceDir } from './files' +import { + FILE_CONCURRENCY, + normalizeSourceText, + readSourceJson, + readSourceText, + type SourceDirChange, + updateSourceDir, +} from './files' import { lockCodeFiles, orphanedCodeFiles, sourceRelativePath, writableFiles } from './layout' import { digest, @@ -70,10 +78,27 @@ async function recordFolderWrite( } /** - * Writes a server answer into the source directory in one staged update: its files, lock and base, - * plus `extra`, pruning the function files the previous lock named and the new one no longer does. - * Returns how many files it wrote. A get refuses an unsafe path first - * ({@link assertPrintedSourcePaths}); after a stored write one is skipped ({@link writableFiles}). + * Of `files` (path → text), those whose text on disk, as the CLI reads it, is not already that + * text: rewriting one that is would change nothing but its modification time, which editors, file + * watchers and incremental type-checks read as an edit. A file edited by hand is rewritten. + */ +async function changedFiles( + dir: string, + files: Record +): Promise> { + const entries = Object.entries(files) + const current = await mapWithConcurrency(entries, FILE_CONCURRENCY, ([path]) => + readSourceText(dir, path) + ) + return entries.filter(([, text], index) => current[index] !== normalizeSourceText(text)) +} + +/** + * Writes a server answer into the source directory in one staged update: its files whose text + * changed ({@link changedFiles}), lock and base, plus `extra`, pruning the function files the + * previous lock named and the new one no longer does. Returns how many files it wrote. A get + * refuses an unsafe path first ({@link assertPrintedSourcePaths}); after a stored write one is + * skipped ({@link writableFiles}). */ export async function writeBack( dir: string, @@ -83,12 +108,16 @@ export async function writeBack( ): Promise { const files = writableFiles(answer.files) const folder = await workspaceFolderOf(dir) - const printed: Array = [ - ...Object.entries(files), + const records: Array = [ [SOURCE_LOCK_FILE, `${JSON.stringify(answer.lock, null, 2)}\n`], [SOURCE_BASE_FILE, `${JSON.stringify(answer.base, null, 2)}\n`], ] - const write = [...printed, ...(folder ? [] : writtenFiles(writtenRecord(files))), ...extra.write] + const write = [ + ...(await changedFiles(dir, files)), + ...records, + ...(folder ? [] : writtenFiles(writtenRecord(files))), + ...extra.write, + ] const orphaned = orphanedCodeFiles( previousLock, answer.lock, @@ -100,7 +129,14 @@ export async function writeBack( write, remove: [...orphaned, ...(extra.remove ?? [])], }) - if (folder) await recordFolderWrite(folder, Object.fromEntries(printed), orphaned, answer.base) + if (folder) { + await recordFolderWrite( + folder, + Object.fromEntries([...Object.entries(files), ...records]), + orphaned, + answer.base + ) + } if (unnamed.length > 0) { printError( `warning: ${unnamed.join(', ')} ${unnamed.length === 1 ? 'is' : 'are'} no longer named by ${SOURCE_ENTRY_FILE} (the printed source names no code file there, such as code now printed as stored()), so ${unnamed.length === 1 ? 'it was' : 'they were'} left on disk as written: delete ${unnamed.length === 1 ? 'it' : 'them'}, or name ${unnamed.length === 1 ? 'it' : 'them'} again with codeFile(). Never commit one that holds a credential.` diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 17fdf65918b..a26b43b35e1 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -107,15 +107,16 @@ export function codeFilePaths(entry: string | null, lock: unknown): string[] { const GET_HINT = 'Write the directory with `sim workflows source get` first.' /** - * The base an apply sends, refused when it is not the named workflow's: a directory written for - * one workflow and applied to another would replace that workflow's draft with a stranger's - * source. Without a `workflowId` the apply targets the workflow the base names. + * The base `sim workflows source ` sends, refused when it is not the named workflow's: a + * directory written for one workflow and applied to another would replace that workflow's draft + * with a stranger's source. Without a `workflowId` the apply targets the workflow the base names. */ export async function readBase( directory: string, - workflowId: string | undefined + workflowId: string | undefined, + command: string ): Promise { - await assertSourceDirKind(directory, 'workflow') + await assertSourceDirKind(directory, 'workflow', command) const parsed = parseSourceBase(await readJson(directory, SOURCE_BASE_FILE, GET_HINT)) if ('problem' in parsed) { throw new SourceDirError( 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 1da465e933e..49281b2c53e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -747,10 +747,10 @@ export function attachWorkflowSourceApply(source: Command): void { options.dir, async () => { const checked = await checkedWriteOptions(options) - await assertSourceDirKind(options.dir, 'workflow') + await assertSourceDirKind(options.dir, 'workflow', 'apply') const { client, profile } = connectApply() const lock = await readLock(options.dir) - const base = await readBase(options.dir, named) + const base = await readBase(options.dir, named, 'apply') const workflowId = base.workflowId const files = await readSourceFiles(options.dir, lock) if (!isReadOnly(mode)) { @@ -847,7 +847,7 @@ export function attachWorkflowSourceCreate(source: Command): void { await withSourceCommandLock( options.dir, async () => { - await assertSourceDirKind(options.dir, 'workflow') + await assertSourceDirKind(options.dir, 'workflow', 'create') const checked = await checkedWriteOptions(options) if ((await readSourceText(options.dir, ENTRY_FILE)) === null) { if (options.dry || options.yes) { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index 0cf3da8450f..d1ff2c921be 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts @@ -508,7 +508,7 @@ describe('sim workflows source check', () => { expect((error as SimApiError).message).toContain('is a workspace source directory') expect((error as SimApiError).message).toContain( - `\`sim workspaces source\` (check, status, apply) --dir ${dir}` + `--dir ${dir}/workflows/), or run \`sim workspaces source check --dir ${dir}\`` ) }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts index e775916e4e3..aca585f9e46 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -76,7 +76,7 @@ export function attachWorkflowSourceCheck(source: Command): void { command: Command ) => { const profile = actingProfileFrom(command) - await assertSourceDirKind(options.dir, 'workflow') + await assertSourceDirKind(options.dir, 'workflow', 'check') await requireEntry(options.dir) const workspace = await workspaceFolderOf(options.dir) const workspaceId = directoryWorkspace( diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts index 8b869f81dd8..2e4daf13fd8 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts @@ -195,6 +195,22 @@ describe('sim workflows source find', () => { ]) }) + it('points a workspace directory at its workflow folders, not at a workspace command it lacks', async () => { + writeFileSync( + join(dir, '.sim/base.json'), + JSON.stringify({ version: 1, workspaceId: 'ws_find', resources: {} }) + ) + + const error = await find('Audit').catch((caught: unknown) => caught) + + expect(error).toMatchObject({ code: 'SOURCE_DIR_KIND_MISMATCH' }) + const { message } = error as Error + expect(message).toContain('which `sim workflows source find` does not read') + expect(message).toContain(`--dir ${dir}/workflows/`) + expect(message).not.toContain('replace its base') + expect(message).not.toContain('sim workspaces source') + }) + it('refuses an empty name rather than matching every block', async () => { await expect(find(' ')).rejects.toMatchObject({ code: 'BLOCK_UNKNOWN' }) await expect(find('.')).rejects.toMatchObject({ code: 'BLOCK_UNKNOWN' }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-find.ts b/packages/sim-cli/src/commands/protocol/workflow-source-find.ts index cbdc8a27bf2..3462292fb16 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-find.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-find.ts @@ -338,7 +338,7 @@ export function attachWorkflowSourceFind(source: Command): void { .addHelpText('after', FIND_HELP) .action(async (queries: string[], options: { dir: string }, command: Command) => { const profile = actingProfileFrom(command) - await assertSourceDirKind(options.dir, 'workflow') + await assertSourceDirKind(options.dir, 'workflow', 'find') const catalog = await lookupCatalog(options.dir, profile) const { compiled, files } = await compileWorkflowDir(options.dir, catalog) if (queries.some((query) => normalizeWorkflowBlockName(query) === '')) { 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 a70e327de6c..ff052767471 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -30,7 +30,7 @@ const DIR_FLAG = 'dir' const FORCE_FLAG = 'force' /** The workflow `.sim/base.json` says the directory holds, or `null` when it names none. */ -async function heldWorkflowId(dir: string): Promise { +export async function heldWorkflowId(dir: string): Promise { const held = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)).workflowId return typeof held === 'string' ? held : null } @@ -75,7 +75,7 @@ const SEARCH_MAX_LENGTH = 200 * name is exactly `workflow`. No match or several are refused, naming the candidates with their * ids (a workflow's name is unique only within its folder). */ -async function resolveWorkflow( +export async function resolveWorkflow( client: OperationClient<'listWorkflows'>, workflow: string, /** The workspace to look in when not the command's own: a directory's recorded one. */ @@ -167,7 +167,7 @@ export function attachWorkflowSourceGet(source: Command): void { } await withSourceCommandLock(dir, async () => { const force = flags[FORCE_FLAG] === true - await assertSourceDirKind(dir, 'workflow') + await assertSourceDirKind(dir, 'workflow', 'get') const { client, profile } = connectGet() // A name is looked up in the workspace the directory was read from, as its other commands // act on it; --force gets into it from the command's own workspace instead. diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts b/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts new file mode 100644 index 00000000000..4a17ceb8e3a --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts @@ -0,0 +1,70 @@ +import type { Command } from 'commander' +import { setWorkingDirectoryWorkspace } from '../../context' +import { heldAction } from '../../runtime/build' +import { callsOperations } from '../../runtime/called-operations' +import { absoluteDirOption, enclosingWorkspace } from './source-dir' +import { heldWorkflowId, resolveWorkflow } from './workflow-source-get' + +const DIR_FLAG = 'dir' + +/** The generated `workflows source ` leaf with the action it holds, given `--dir`. */ +function generatedLeafWithDir( + source: Command, + name: string, + reads: string +): [Command, (args: unknown[]) => void | Promise] { + const leaf = source.commands.find((command) => command.name() === name) + const previous = heldAction(leaf) + if (!leaf || !previous) { + throw new Error( + `workflows source ${name} must be registered before --dir can be attached to it` + ) + } + leaf.option( + `--${DIR_FLAG} `, + `Source directory whose ${reads} to read (default: the one the command runs in)` + ) + absoluteDirOption(leaf) + return [leaf, previous] +} + +/** + * The `--dir` the command was given, after making it the directory the command acts in: the + * workspace it names is the one read, as for a command run inside it. + */ +async function actInDirectory(command: Command): Promise { + const dir: unknown = command.getOptionValue(DIR_FLAG) + if (typeof dir !== 'string') return undefined + const named = await enclosingWorkspace(dir) + if (named) setWorkingDirectoryWorkspace(command, named) + return dir +} + +/** + * Teaches the generated `workflows source resources` and `catalog` leaves the `--dir ` every + * other `workflows source` command takes: each reads the workspace the directory names, and + * `catalog` also the block types placed in the workflow the directory holds. `catalog + * --workflow-id` takes a workflow's exact name as well as its id, as `get` does. Commander offers + * no way to read the action a leaf holds, so it is captured and delegated to, as `get` does. + */ +export function attachWorkflowSourceReads(source: Command): void { + const [resources, readResources] = generatedLeafWithDir(source, 'resources', 'workspace') + resources.action(async (_options: unknown, command: Command): Promise => { + await actInDirectory(command) + await readResources(command.processedArgs) + }) + + const [catalog, readCatalog] = generatedLeafWithDir(source, 'catalog', 'workspace and workflow') + const connectCatalog = callsOperations(catalog, ['getSourceCatalog', 'listWorkflows']) + catalog.action(async (_options: unknown, command: Command): Promise => { + const dir = await actInDirectory(command) + const workflow: unknown = command.getOptionValue('workflowId') + if (typeof workflow === 'string') { + command.setOptionValue('workflowId', await resolveWorkflow(connectCatalog().client, workflow)) + } else if (dir !== undefined) { + const held = await heldWorkflowId(dir) + if (held !== null) command.setOptionValue('workflowId', held) + } + await readCatalog(command.processedArgs) + }) +} diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index cc6ea84e589..6682f0773dc 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -5,7 +5,9 @@ import { readdirSync, readFileSync, rmSync, + statSync, symlinkSync, + utimesSync, writeFileSync, } from 'node:fs' import { tmpdir } from 'node:os' @@ -479,6 +481,30 @@ describe('line endings', () => { }) }) +describe('writing an answer back', () => { + const PAST = new Date('2020-01-01T00:00:00Z') + const modified = (path: string) => statSync(join(dir, path)).mtimeMs + + it('leaves a file whose text the answer keeps untouched, and rewrites one edited by hand', async () => { + await get() + for (const path of Object.keys(FILES)) utimesSync(join(dir, path), PAST, PAST) + server.apply = () => json(appliedResponse(FILES)) + + await apply() + + expect(modified('workflow.ts')).toBe(PAST.getTime()) + expect(modified('functions/score.js')).toBe(PAST.getTime()) + + writeFileSync(join(dir, 'functions/score.js'), 'return 9\n') + utimesSync(join(dir, 'functions/score.js'), PAST, PAST) + + await sim('workflows', 'source', 'get', WORKFLOW_ID, '--dir', dir, '--force') + + expect(read('functions/score.js')).toBe(FILES['functions/score.js']) + expect(modified('workflow.ts')).toBe(PAST.getTime()) + }) +}) + describe('the workspace-scoped source reads', () => { it.each(['resources', 'catalog'])( 'reads %s from the profile workspace, like every other workspace route', diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts index 3f371724c57..d061827e192 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts @@ -69,8 +69,8 @@ interface LocalWorkflow { unnamed: string[] } -async function readLocalWorkflow(dir: string): Promise { - const base = await readBase(dir, undefined) +async function readLocalWorkflow(dir: string, command: 'status' | 'diff'): Promise { + const base = await readBase(dir, undefined, command) const { workflowId } = base const written = await readFolderWritten(dir) const entry = await readSourceText(dir, SOURCE_ENTRY_FILE) @@ -142,7 +142,6 @@ function planLine(plan: WorkflowPlanSummary): string { interface StatusOptions { dir: string offline?: boolean - json?: boolean summaryFile?: string } @@ -161,18 +160,17 @@ export function attachWorkflowSourceStatus(source: Command): void { command .option('--dir ', 'Source directory: workflow.ts, functions/* and .sim/', '.') .option('--offline', 'Report local changes only, without asking the server') - .option('--json', 'Print the machine-readable status (same as --output json)') .allowExcessArguments(false) .description('Show what changed locally and on the server since the directory was read') .addHelpText('after', statusHelp('workflows source status')) .action(async (options: StatusOptions, invoked: Command) => { - const output = options.json ? 'json' : profileFrom(invoked).output + const output = profileFrom(invoked).output // A status only reads, but holds the lock so it never reports a directory an apply or get is // halfway through rewriting, nor refreshes its types meanwhile (exit 10 while one runs). await withSourceCommandLock( options.dir, async () => { - const local = await readLocalWorkflow(options.dir) + const local = await readLocalWorkflow(options.dir, 'status') const { workflowId } = local const locals: LocalResourceChange[] = local.changed.length > 0 @@ -264,7 +262,6 @@ export function attachWorkflowSourceStatus(source: Command): void { interface DiffOptions { dir: string server?: boolean - json?: boolean } /** @@ -280,13 +277,12 @@ export function attachWorkflowSourceDiff(source: Command): void { .argument('[paths...]', 'Files or folders to compare (default: every file)') .option('--dir ', 'Source directory: workflow.ts, functions/* and .sim/', '.') .option('--server', "Compare with the server's current source instead of the base") - .option('--json', 'Print the machine-readable diff (same as --output json)') .allowExcessArguments(false) .addHelpText('after', DIFF_HELP) .description('Show the content of the changes in a workflow source directory') .action(async (filters: string[], options: DiffOptions, invoked: Command) => { - const output = options.json ? 'json' : profileFrom(invoked).output - const local = await readLocalWorkflow(options.dir) + const output = profileFrom(invoked).output + const local = await readLocalWorkflow(options.dir, 'diff') const filter = pathFilter(filters, options.dir) const selects = filter.selects const read = async () => { 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 e608d6fcc3e..7bf20fb76d8 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -849,7 +849,7 @@ export function attachWorkspaceSourceApply(source: Command): void { // The read already walked the kind folders: only a read that found none, or a workflow // directory's base, needs the full check (which refuses with the reason). if (read.kinds.length === 0 || baseWorkflowOf(read.base) !== null) { - await assertWorkspaceDir(options.dir) + await assertWorkspaceDir(options.dir, 'apply') } assertBlobsFetched(options.dir, read, written.digests) promotion = options.to diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts index 91a0b7bc97a..d3ccab7edfe 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts @@ -233,7 +233,7 @@ describe('sim workspaces source check', () => { expect(error).toMatchObject({ message: expect.stringContaining( - 'is a workflow source directory (workflow wf_first), so a `sim workspaces source` command' + 'is a workflow source directory (workflow wf_first), which `sim workspaces source check` does not read. Run `sim workflows source check --dir' ), }) }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts index 9516faaeb0d..4a1ac7a5876 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -112,7 +112,7 @@ export function attachWorkspaceSourceCheck(source: Command): void { ) => { const profile = actingProfileFrom(command) const base = toRecord(await readSourceJson(options.dir, WORKSPACE_BASE_FILE)) - await assertWorkspaceDir(options.dir) + await assertWorkspaceDir(options.dir, 'check') const workspaceId = directoryWorkspace( options.dir, typeof base.workspaceId === 'string' ? base.workspaceId : null, 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 4d4d0ab0542..ae510567e82 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -604,8 +604,8 @@ export async function kindFolders( * Refuses a directory a workspace command would find nothing in, so a mistyped `--dir` or a * workflow folder fails instead of passing with nothing checked or applied. */ -export async function assertWorkspaceDir(dir: string): Promise { - await assertSourceDirKind(dir, 'workspace') +export async function assertWorkspaceDir(dir: string, command: string): Promise { + await assertSourceDirKind(dir, 'workspace', command) const { present } = await kindFolders(dir, APPLY_ORDER) if (present.length > 0) return throw new SourceDirError( diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts index 67ad158400d..1a7dd19f5d5 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -350,7 +350,7 @@ export function attachWorkspaceSourceGet(source: Command): void { const kinds = parseKinds(options.only) const { client, profile } = connect() await withSourceDirLock(options.dir, async () => { - await assertSourceDirKind(options.dir, 'workspace') + await assertSourceDirKind(options.dir, 'workspace', 'get') // Read as leniently as an apply reads it: a base the parser refuses still names its workspace. const recorded = toRecord( await readSourceJson(options.dir, WORKSPACE_BASE_FILE) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts index fe6c47a7fed..9fa08f3cd65 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -108,7 +108,8 @@ interface LocalWorkspace { */ async function readLocalWorkspace( dir: string, - only: readonly WorkspaceKind[] | undefined + only: readonly WorkspaceKind[] | undefined, + command: 'status' | 'diff' ): Promise { await assertWrittenReadable(dir) const written = await readWritten(dir) @@ -116,7 +117,7 @@ async function readLocalWorkspace( const readFrom = typeof base.workspaceId === 'string' ? base.workspaceId : null const submission = await readWorkspaceDir(dir, only, readFrom ?? '', written, { whole: true }) if (submission.kinds.length === 0 || typeof base.workflowId === 'string') { - await assertWorkspaceDir(dir) + await assertWorkspaceDir(dir, command) } const current: Record = {} for (const [path, text] of Object.entries(submission.files)) current[path] = digest(text) @@ -340,7 +341,6 @@ interface StatusOptions { dir: string only?: string offline?: boolean - json?: boolean summaryFile?: string } @@ -357,20 +357,19 @@ export function attachWorkspaceSourceStatus(source: Command): void { .option('--dir ', 'Workspace source directory written by `workspaces source get`', '.') .option('--only ', `Report only these kinds (${ONLY_KINDS_HELP})`) .option('--offline', 'Report local changes only, without asking the server') - .option('--json', 'Print the machine-readable status (same as --output json)') .allowExcessArguments(false) .description('Show what changed locally and on the server since the directory was read') .addHelpText('after', statusHelp('workspaces source status')) .action(async (options: StatusOptions, invoked: Command) => { const nextPrefix = `${simInvocation(invoked)} workspaces source` const only = parseKinds(options.only) - const output = options.json ? 'json' : profileFrom(invoked).output + const output = profileFrom(invoked).output // A status or diff only reads, but holds the directory's lock so it never reports a // directory an apply or get is halfway through rewriting (exit 10 while one runs). await withSourceDirLock( options.dir, async () => { - const local = await readLocalWorkspace(options.dir, only) + const local = await readLocalWorkspace(options.dir, only, 'status') const locals = localResourceChanges(local.changed) let server: ServerCheck = options.offline ? 'offline' : 'checked' let note: string | undefined = options.offline ? 'Skipped with --offline.' : undefined @@ -511,7 +510,6 @@ function isSidecar(path: string): boolean { interface DiffOptions { dir: string server?: boolean - json?: boolean } /** @@ -606,18 +604,17 @@ export function attachWorkspaceSourceDiff(source: Command): void { .argument('[paths...]', 'Files, folders or kind:key resources to compare (default: every file)') .option('--dir ', 'Workspace source directory written by `workspaces source get`', '.') .option('--server', "Compare with the server's current source instead of the base") - .option('--json', 'Print the machine-readable diff (same as --output json)') .allowExcessArguments(false) .addHelpText('after', `${DIFF_HELP}\n${SOURCE_DIR_BUSY_HELP}`) .description('Show the content of the changes in a workspace source directory') .action(async (filters: string[], options: DiffOptions, invoked: Command) => { - const output = options.json ? 'json' : profileFrom(invoked).output + const output = profileFrom(invoked).output // A status or diff only reads, but holds the directory's lock so it never reports a // directory an apply or get is halfway through rewriting (exit 10 while one runs). await withSourceDirLock( options.dir, async () => { - const local = await readLocalWorkspace(options.dir, undefined) + const local = await readLocalWorkspace(options.dir, undefined, 'diff') const filter = pathFilter(filters, options.dir, resourceOf) const selects = filter.selects const read = async (kinds: readonly WorkspaceKind[]) => { diff --git a/packages/sim-cli/src/context.ts b/packages/sim-cli/src/context.ts index 098d1939179..fb0d40e9099 100644 --- a/packages/sim-cli/src/context.ts +++ b/packages/sim-cli/src/context.ts @@ -11,12 +11,14 @@ import { } from './config/index' import { SimClient } from './http/client' -/** Global flags, shared by every subcommand. */ +/** Global flags, shared by every subcommand, and the `--json` every source command takes. */ export interface GlobalOptions { profile?: string endpoint?: string workspace?: string output?: OutputFormat + /** `--json`: the same as `--output json`, over any other `--output`. */ + json?: boolean } /** @@ -34,7 +36,7 @@ export function profileFrom(command: Command, extra: ProfileOverrides = {}): Res profile: globals.profile, endpoint: globals.endpoint, workspaceId: globals.workspace, - output: globals.output, + output: globals.json ? 'json' : globals.output, ...extra, }) } @@ -42,20 +44,21 @@ export function profileFrom(command: Command, extra: ProfileOverrides = {}): Res /** The workspace the source directory the terminal runs in names, by the program running there. */ const workingDirectoryWorkspaces = new WeakMap() -/** - * Records the workspace the source directory `program` runs in names, which the terminal reads - * before each action: {@link actingProfileFrom} then gives it to every command `program` runs. - */ -export function setWorkingDirectoryWorkspace(program: Command, named: NamedWorkspace): void { - workingDirectoryWorkspaces.set(program, named) -} - function rootOf(command: Command): Command { let root = command while (root.parent) root = root.parent return root } +/** + * Records the workspace the source directory `command`'s program runs in names: the terminal reads + * the working directory's before each action, and a `--dir` read names its directory's. + * {@link actingProfileFrom} then gives it to every command the program runs. + */ +export function setWorkingDirectoryWorkspace(command: Command, named: NamedWorkspace): void { + workingDirectoryWorkspaces.set(rootOf(command), named) +} + /** * The profile a command acts with: {@link profileFrom}, whose workspace the source directory the * terminal runs in chooses when neither `--workspace` nor `SIM_WORKSPACE` names one, so a command diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 7ab0bd4ce07..6e3ec141a7e 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -734,7 +734,13 @@ export const CLI_CONTRACT: CliContract = { command: 'workflows source catalog', describe: 'Show the block catalog workflow source is checked against', profileWorkspacePath: true, - flags: { 'if-none-match': { omit: true } }, + flags: { + 'if-none-match': { omit: true }, + workflowId: { + describe: + 'Workflow id, or its exact name: adds every block type already placed in it, the ones the caller could not add marked `addable: false`', + }, + }, }, /** `workflows source create --dir ` reads and writes a source directory by hand. */ createWorkflowFromSource: { hidden: true }, diff --git a/packages/sim-cli/src/runtime/build.ts b/packages/sim-cli/src/runtime/build.ts index 3db9d96a65a..767f5febbc4 100644 --- a/packages/sim-cli/src/runtime/build.ts +++ b/packages/sim-cli/src/runtime/build.ts @@ -294,7 +294,8 @@ function siblingsDeclaring(command: Command, flag: string): string[] { * another flag as its value is named, and a JSON operand is moved to the JSON flag it belongs to. * - An unknown option gets the command's own flags, and the sibling commands * that do take it: `tables rows list --filter` belongs to `tables rows - * query`, which commander's near-spelling suggestion never reaches. + * query`, which commander's near-spelling suggestion never reaches. An + * unknown `--json` gets the root `--output json` every command takes instead. * - An id swallowed as an option because it opens with a dash gets the `--` * escape, which commander never mentions. */ @@ -328,6 +329,7 @@ function parseErrorGuidance(command: Command, code: string | undefined): string[ return [`Example: ${commandPath(command)} -- ${token}`] } const flag = token.split('=', 1)[0] + if (flag === '--json') return [optionList(command), 'For JSON output, pass --output json.'] const owners = siblingsDeclaring(command, flag) return [ optionList(command), diff --git a/packages/sim-cli/src/runtime/execute.test.ts b/packages/sim-cli/src/runtime/execute.test.ts index 2f7694b9aab..f3cc5cd29f5 100644 --- a/packages/sim-cli/src/runtime/execute.test.ts +++ b/packages/sim-cli/src/runtime/execute.test.ts @@ -366,7 +366,7 @@ describe('a resource the resolved workspace does not hold', () => { ) ).rejects.toMatchObject({ message: - 'Table not found (searched workspace ws_local, the workspace of profile "default"; pass -w or set SIM_WORKSPACE to search another)', + 'Table not found (searched workspace ws_local, the workspace of profile "default"; pass -w or set SIM_WORKSPACE to search another)', status: 404, code: 'NOT_FOUND', }) @@ -384,7 +384,7 @@ describe('a resource the resolved workspace does not hold', () => { ]) ).rejects.toMatchObject({ message: - 'Table not found (searched workspace ws_local, from SIM_WORKSPACE; pass -w to search another)', + 'Table not found (searched workspace ws_local, from SIM_WORKSPACE; pass -w to search another)', }) }) diff --git a/packages/sim-cli/src/runtime/execute.ts b/packages/sim-cli/src/runtime/execute.ts index c9a50dd0d0f..ed3ecba5f62 100644 --- a/packages/sim-cli/src/runtime/execute.ts +++ b/packages/sim-cli/src/runtime/execute.ts @@ -439,11 +439,11 @@ function withSearchedWorkspace(error: unknown, profile: ResolvedProfile): unknow if (!(error instanceof SimApiError) || error.status !== 404 || !profile.workspaceId) return error const source = profile.sources.workspaceId const from = profile.workspaceDirectory - ? `, the workspace of the source directory ${safeOneLine(profile.workspaceDirectory)}; pass -w or set SIM_WORKSPACE to search another` + ? `, the workspace of the source directory ${safeOneLine(profile.workspaceDirectory)}; pass -w or set SIM_WORKSPACE to search another` : source === 'env' - ? ', from SIM_WORKSPACE; pass -w to search another' + ? ', from SIM_WORKSPACE; pass -w to search another' : source === 'config' - ? `, the workspace of profile "${safeOneLine(profile.name)}"; pass -w or set SIM_WORKSPACE to search another` + ? `, the workspace of profile "${safeOneLine(profile.name)}"; pass -w or set SIM_WORKSPACE to search another` : '' const searched = `searched workspace ${safeOneLine(profile.workspaceId)}${from}` return new SimApiError( diff --git a/packages/sim-cli/src/terminal.test.ts b/packages/sim-cli/src/terminal.test.ts index d11c4452e0f..79819781979 100644 --- a/packages/sim-cli/src/terminal.test.ts +++ b/packages/sim-cli/src/terminal.test.ts @@ -7,12 +7,17 @@ import { runTerminalCli } from './terminal' /** * Runs `sim ` the way the installed binary does against a server that - * answers with `response`, and returns what it wrote to stderr and its exit code. + * answers with `response` (or what `response` returns for the requested URL), and + * returns what it wrote to stderr and its exit code. */ async function runAgainst( argv: string[], - response: Response, - { workspace = 'ws_1', profileWorkspace }: { workspace?: string; profileWorkspace?: string } = {} + response: Response | ((url: string) => Response), + { + workspace = 'ws_1', + profileWorkspace, + output, + }: { workspace?: string; profileWorkspace?: string; output?: string } = {} ): Promise<{ stderr: string; exitCode: number }> { const configDir = mkdtempSync(join(tmpdir(), 'sim-cli-terminal-')) if (profileWorkspace) { @@ -23,7 +28,13 @@ async function runAgainst( vi.stubEnv('SIM_API_KEY', 'sk-test') vi.stubEnv('SIM_WORKSPACE', workspace) vi.stubEnv('SIM_NO_UPDATE_CHECK', '1') - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response)) + if (output) vi.stubEnv('SIM_OUTPUT', output) + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL | Request) => + typeof response === 'function' ? response(String(input)) : response + ) + ) let stderr = '' vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { @@ -251,3 +262,80 @@ describe('a command run inside a source directory', () => { } }) }) + +describe('the workflow source reads', () => { + const notFound = () => + new Response(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Workflow not found' } }), { + status: 404, + headers: { 'content-type': 'application/json' }, + }) + const requestedUrls = () => vi.mocked(fetch).mock.calls.map(([input]) => String(input)) + + /** A directory whose `.sim/base.json` holds `base`. */ + function directoryWith(base: unknown): string { + const dir = mkdtempSync(join(tmpdir(), 'sim-cli-source-read-')) + mkdirSync(join(dir, '.sim')) + writeFileSync(join(dir, '.sim', 'base.json'), JSON.stringify(base)) + return dir + } + + it('reads resources and the catalog for the workspace and workflow --dir names', async () => { + const workflowId = '00000000-0000-4000-8000-00000000000a' + const dir = directoryWith({ workflowId, workspaceId: 'ws_dir' }) + try { + const options = { workspace: '', profileWorkspace: 'ws_profile' } + await runAgainst(['workflows', 'source', 'resources', '--dir', dir], notFound(), options) + expect(requestedUrls()).toEqual([ + 'https://sim.example/api/v2/workspaces/ws_dir/workflows/source/resources', + ]) + + await runAgainst(['workflows', 'source', 'catalog', '--dir', dir], notFound(), options) + expect(requestedUrls()).toEqual([ + `https://sim.example/api/v2/workspaces/ws_dir/workflows/source/catalog?workflowId=${workflowId}`, + ]) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('reads the catalog for a workflow named by its exact name', async () => { + const workflowId = '00000000-0000-4000-8000-00000000000c' + await runAgainst(['workflows', 'source', 'catalog', '--workflow-id', 'Triage'], (url) => + url.includes('/source/catalog') + ? notFound() + : new Response( + JSON.stringify({ + data: [ + { id: workflowId, name: 'Triage' }, + { id: 'other', name: 'Triage copy' }, + ], + nextCursor: null, + }), + { headers: { 'content-type': 'application/json' } } + ) + ) + expect(requestedUrls().at(-1)).toBe( + `https://sim.example/api/v2/workspaces/ws_1/workflows/source/catalog?workflowId=${workflowId}` + ) + }) + + it('names the -w flag a not-found answer can retry with, untouched by the wire-name rewording', async () => { + const { stderr } = await runAgainst( + ['workflows', 'source', 'catalog', '--workflow-id', '00000000-0000-4000-8000-00000000000a'], + notFound(), + { workspace: '', profileWorkspace: 'ws_profile' } + ) + expect(stderr).toContain('pass -w or set SIM_WORKSPACE to search another') + }) + + it('takes --json on every source command, and points --json elsewhere at --output json', async () => { + const asJson = await runAgainst(['workflows', 'source', 'resources', '--json'], notFound(), { + output: 'text', + }) + expect(asJson.stderr).toContain('{"error"') + + const elsewhere = await runAgainst(['workflows', 'list', '--json'], notFound()) + expect(elsewhere.stderr).toContain('For JSON output, pass --output json.') + expect(elsewhere.stderr).not.toContain('--json is an option of') + }) +}) diff --git a/packages/sim-cli/src/terminal.ts b/packages/sim-cli/src/terminal.ts index a59e671987f..04263998ded 100644 --- a/packages/sim-cli/src/terminal.ts +++ b/packages/sim-cli/src/terminal.ts @@ -23,7 +23,7 @@ import { createCommandTelemetry } from './telemetry/index' * in the CLI, and hiding it behind a friendly message would make it * unreportable, so the caller prints it with its stack trace. */ -function explainFailure(error: unknown, program: Command): number | null { +function explainFailure(error: unknown, command: Command): number | null { if (error instanceof CliExit) return error.code if (error instanceof ProfileConfigError || error instanceof CliUpdateError) { printError(styles().red(`Error: ${sanitize(error.message)}`)) @@ -38,9 +38,9 @@ function explainFailure(error: unknown, program: Command): number | null { return 1 } if (error instanceof SimApiError) { - let output = program.opts().output + let output = command.optsWithGlobals().output try { - output = profileFrom(program).output + output = profileFrom(command).output } catch { /** Preserve the original error when configuration is invalid. */ } @@ -79,16 +79,19 @@ export async function runTerminalCli(suppliedProgram?: Command): Promise { const telemetry = suppliedProgram ? undefined : createCommandTelemetry() const program = suppliedProgram ?? buildProgram() telemetry?.observe(program) + /** The command whose action ran, whose options (a source command's `--json`) format a failure. */ + let acting = program // The working directory's workspace is read here, once, with the readers source commands use, // because it is a terminal's alone: an embedded run has no working directory of its own. - program.hook('preAction', async () => { + program.hook('preAction', async (_program, command) => { + acting = command const named = await enclosingWorkspace(process.cwd()) if (named) setWorkingDirectoryWorkspace(program, named) }) try { await program.parseAsync(process.argv) } catch (error) { - const exitCode = explainFailure(error, program) + const exitCode = explainFailure(error, acting) telemetry?.complete( error instanceof CliExit ? { exitCode: error.code } : { exitCode: exitCode ?? 1, error } ) From 0517b20b9717b909fed19e34c37afade923ed4e9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:16:06 -0800 Subject: [PATCH 2/2] fix(sim-cli): resolve resources and catalog --dir as the directory's other commands do --dir defaults to the working directory, so catalog includes the workflow it holds; a directory naming no workspace clears the working directory's; and a -w or SIM_WORKSPACE naming another workspace than the directory's record is refused (SOURCE_OTHER_WORKSPACE). The docs baseline records the changed resources usage fence. --- apps/docs/content/docs/cli/reference.mdx | 4 +-- apps/docs/content/docs/cli/workflows.mdx | 4 +-- .../scripts/fixtures/content-baseline.json | 4 +-- .../protocol/workflow-source-reads.ts | 32 +++++++++++-------- .../workflow-source-roundtrip.test.ts | 1 + packages/sim-cli/src/context.ts | 9 +++--- packages/sim-cli/src/terminal.test.ts | 30 +++++++++++++++++ packages/sim-cli/src/terminal.ts | 3 +- 8 files changed, 62 insertions(+), 25 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 30f1fece6ee..3bcb26e42e2 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8597,7 +8597,7 @@ sim workflows source catalog [options] | Option | Required | Description | | --- | --- | --- | | `--workflow-id ` | No | Workflow id, or its exact name: adds every block type already placed in it, the ones the caller could not add marked `addable: false`. | -| `--dir ` | No | Source directory whose workspace and workflow to read (default: the one the command runs in). | +| `--dir ` | No | Source directory whose workspace and workflow to read. Defaults to `.`. | | `--json` | No | Print machine-readable JSON (same as --output json). | @@ -8618,7 +8618,7 @@ sim workflows source resources [options] | Option | Required | Description | | --- | --- | --- | -| `--dir ` | No | Source directory whose workspace to read (default: the one the command runs in). | +| `--dir ` | No | Source directory whose workspace to read. Defaults to `.`. | | `--json` | No | Print machine-readable JSON (same as --output json). | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index cae7347fca5..f976968d5d2 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1509,7 +1509,7 @@ sim workflows source catalog [options] | Option | Required | Description | | --- | --- | --- | | `--workflow-id ` | No | Workflow id, or its exact name: adds every block type already placed in it, the ones the caller could not add marked `addable: false`. | -| `--dir ` | No | Source directory whose workspace and workflow to read (default: the one the command runs in). | +| `--dir ` | No | Source directory whose workspace and workflow to read. Defaults to `.`. | | `--json` | No | Print machine-readable JSON (same as --output json). | @@ -1656,7 +1656,7 @@ sim workflows source resources [options] | Option | Required | Description | | --- | --- | --- | -| `--dir ` | No | Source directory whose workspace to read (default: the one the command runs in). | +| `--dir ` | No | Source directory whose workspace to read. Defaults to `.`. | | `--json` | No | Print machine-readable JSON (same as --output json). | diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index 2fe30baf048..dc7dea27a01 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -13164,7 +13164,7 @@ { "lang": "bash", "meta": null, - "sha256": "face4eea006073000b49334d0a2bea7f15f9df86cb1f606ac8fe39004c754027", + "sha256": "f893698f2fd6f13766a0f3e9d0ad0d4200ccb097939860a634500730358066ab", "bytes": null, "line": null }, @@ -17813,7 +17813,7 @@ { "lang": "bash", "meta": null, - "sha256": "face4eea006073000b49334d0a2bea7f15f9df86cb1f606ac8fe39004c754027", + "sha256": "f893698f2fd6f13766a0f3e9d0ad0d4200ccb097939860a634500730358066ab", "bytes": null, "line": null } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts b/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts index 4a17ceb8e3a..ba4c566c40d 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts @@ -1,8 +1,8 @@ import type { Command } from 'commander' -import { setWorkingDirectoryWorkspace } from '../../context' +import { profileFrom, setWorkingDirectoryWorkspace } from '../../context' import { heldAction } from '../../runtime/build' import { callsOperations } from '../../runtime/called-operations' -import { absoluteDirOption, enclosingWorkspace } from './source-dir' +import { absoluteDirOption, directoryWorkspace, enclosingWorkspace } from './source-dir' import { heldWorkflowId, resolveWorkflow } from './workflow-source-get' const DIR_FLAG = 'dir' @@ -20,23 +20,29 @@ function generatedLeafWithDir( `workflows source ${name} must be registered before --dir can be attached to it` ) } - leaf.option( - `--${DIR_FLAG} `, - `Source directory whose ${reads} to read (default: the one the command runs in)` - ) + leaf.option(`--${DIR_FLAG} `, `Source directory whose ${reads} to read`, '.') absoluteDirOption(leaf) return [leaf, previous] } /** - * The `--dir` the command was given, after making it the directory the command acts in: the - * workspace it names is the one read, as for a command run inside it. + * Makes `--dir` the directory the command acts in, as if run inside it: the workspace it (or a + * directory above it) names is the one read, and none when it names none. A `--workspace` or + * `SIM_WORKSPACE` naming another one than its record is refused, as the directory's other + * commands refuse it ({@link directoryWorkspace}). Returns the directory. */ -async function actInDirectory(command: Command): Promise { - const dir: unknown = command.getOptionValue(DIR_FLAG) - if (typeof dir !== 'string') return undefined +async function actInDirectory(command: Command): Promise { + const dir = String(command.getOptionValue(DIR_FLAG)) const named = await enclosingWorkspace(dir) - if (named) setWorkingDirectoryWorkspace(command, named) + setWorkingDirectoryWorkspace(command, named) + if (named && !named.starter) { + directoryWorkspace( + dir, + named.workspaceId, + profileFrom(command), + (_from, _named, setting) => `Drop ${setting}, or pass --dir naming a directory of it.` + ) + } return dir } @@ -61,7 +67,7 @@ export function attachWorkflowSourceReads(source: Command): void { const workflow: unknown = command.getOptionValue('workflowId') if (typeof workflow === 'string') { command.setOptionValue('workflowId', await resolveWorkflow(connectCatalog().client, workflow)) - } else if (dir !== undefined) { + } else { const held = await heldWorkflowId(dir) if (held !== null) command.setOptionValue('workflowId', held) } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index 6682f0773dc..fdc59ca49a8 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -43,6 +43,7 @@ vi.mock('../../context', async () => { profileFrom: () => profile, actingProfileFrom: () => profile, clientFrom: () => ({ client: new SimClient(profile), profile }), + setWorkingDirectoryWorkspace: () => {}, } }) diff --git a/packages/sim-cli/src/context.ts b/packages/sim-cli/src/context.ts index fb0d40e9099..e42c353a29f 100644 --- a/packages/sim-cli/src/context.ts +++ b/packages/sim-cli/src/context.ts @@ -51,12 +51,13 @@ function rootOf(command: Command): Command { } /** - * Records the workspace the source directory `command`'s program runs in names: the terminal reads - * the working directory's before each action, and a `--dir` read names its directory's. + * Records the workspace the source directory `command`'s program runs in names (`null`: none): the + * terminal reads the working directory's before each action, and a `--dir` read its directory's. * {@link actingProfileFrom} then gives it to every command the program runs. */ -export function setWorkingDirectoryWorkspace(command: Command, named: NamedWorkspace): void { - workingDirectoryWorkspaces.set(rootOf(command), named) +export function setWorkingDirectoryWorkspace(command: Command, named: NamedWorkspace | null): void { + if (named) workingDirectoryWorkspaces.set(rootOf(command), named) + else workingDirectoryWorkspaces.delete(rootOf(command)) } /** diff --git a/packages/sim-cli/src/terminal.test.ts b/packages/sim-cli/src/terminal.test.ts index 79819781979..626595b4c26 100644 --- a/packages/sim-cli/src/terminal.test.ts +++ b/packages/sim-cli/src/terminal.test.ts @@ -298,6 +298,36 @@ describe('the workflow source reads', () => { } }) + it('reads the directory --dir names, not the one it runs in, and refuses a -w naming another', async () => { + const workflowId = '00000000-0000-4000-8000-00000000000a' + const recorded = directoryWith({ workflowId, workspaceId: 'ws_dir' }) + const plain = mkdtempSync(join(tmpdir(), 'sim-cli-source-read-plain-')) + const previous = process.cwd() + process.chdir(recorded) + try { + const options = { workspace: '', profileWorkspace: 'ws_profile' } + await runAgainst(['workflows', 'source', 'catalog'], notFound(), options) + expect(requestedUrls()).toEqual([ + `https://sim.example/api/v2/workspaces/ws_dir/workflows/source/catalog?workflowId=${workflowId}`, + ]) + + await runAgainst(['workflows', 'source', 'resources', '--dir', plain], notFound(), options) + expect(requestedUrls()).toEqual([ + 'https://sim.example/api/v2/workspaces/ws_profile/workflows/source/resources', + ]) + + const other = await runAgainst(['workflows', 'source', 'resources'], notFound(), { + workspace: 'ws_env', + }) + expect(other.stderr).toContain('SOURCE_OTHER_WORKSPACE') + expect(requestedUrls()).toEqual([]) + } finally { + process.chdir(previous) + rmSync(recorded, { recursive: true, force: true }) + rmSync(plain, { recursive: true, force: true }) + } + }) + it('reads the catalog for a workflow named by its exact name', async () => { const workflowId = '00000000-0000-4000-8000-00000000000c' await runAgainst(['workflows', 'source', 'catalog', '--workflow-id', 'Triage'], (url) => diff --git a/packages/sim-cli/src/terminal.ts b/packages/sim-cli/src/terminal.ts index 04263998ded..7711c11737f 100644 --- a/packages/sim-cli/src/terminal.ts +++ b/packages/sim-cli/src/terminal.ts @@ -85,8 +85,7 @@ export async function runTerminalCli(suppliedProgram?: Command): Promise { // because it is a terminal's alone: an embedded run has no working directory of its own. program.hook('preAction', async (_program, command) => { acting = command - const named = await enclosingWorkspace(process.cwd()) - if (named) setWorkingDirectoryWorkspace(program, named) + setWorkingDirectoryWorkspace(program, await enclosingWorkspace(process.cwd())) }) try { await program.parseAsync(process.argv)