From ec3429eb09080ee64bf6e888bbe3470c262e2335 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 11:42:14 -0800 Subject: [PATCH 1/7] chore(workflow-code): round 11 package fixes for workflow-code, workflow-sdk and workspace-code - compile: keep refs to unknown outputs out of W_JSON_REF_UNTYPED past the warning cap - babelMessage lives in babel.ts and strips (line:column) from code-file syntax errors - SDK_MAJOR defined once in workflow-code/sdk; workspace-code and the CLI starter use it - drop SPECIAL_BUILDER_KEYS, dead subflow edge branches, duplicate env/stored/key helpers - isModelField, RESOURCE_KEY_HINT, isStoredCall shared; casts narrowed - builder snippets fill McpServerRef, FolderRef and FileRef params - doc fixes: MCP url identity, auth schemes, not-executable message, limits and TSDoc --- .../content/docs/workflows/code/directory.mdx | 2 +- .../lib/workflows/code/real-catalog.test.ts | 13 +++++-- .../src/commands/protocol/workflow-dir.ts | 6 ++-- packages/workflow-code/src/babel.ts | 6 ++++ packages/workflow-code/src/catalog/surface.ts | 8 +++++ .../workflow-code/src/code-files/from-file.ts | 4 +-- packages/workflow-code/src/compile/blocks.ts | 21 ++++++----- .../workflow-code/src/compile/checks.test.ts | 14 ++++++++ packages/workflow-code/src/compile/context.ts | 10 ++++-- .../workflow-code/src/compile/grammar.test.ts | 1 + packages/workflow-code/src/compile/index.ts | 14 ++++---- packages/workflow-code/src/compile/parse.ts | 8 +---- packages/workflow-code/src/compile/report.ts | 2 +- packages/workflow-code/src/compile/values.ts | 36 +++++++++++++++---- packages/workflow-code/src/index.ts | 9 ++--- packages/workflow-code/src/json-fields.ts | 6 ++-- packages/workflow-code/src/print/context.ts | 2 +- packages/workflow-code/src/print/edges.ts | 12 ------- packages/workflow-code/src/sdk.ts | 8 +++++ packages/workflow-sdk/src/codegen/generate.ts | 3 +- packages/workflow-sdk/src/codegen/index.ts | 3 +- packages/workflow-sdk/src/codegen/major.ts | 6 ---- .../workflow-sdk/src/codegen/map-subblock.ts | 4 +-- packages/workflow-sdk/src/codegen/names.ts | 3 -- .../workflow-sdk/src/codegen/reference.ts | 3 ++ .../workflow-sdk/src/codegen/semantics.ts | 2 +- packages/workflow-sdk/src/not-executable.ts | 4 +-- .../workspace-code/src/declaration/print.ts | 4 +-- .../workspace-code/src/declaration/read.ts | 34 ++++++++++-------- .../workspace-code/src/diagnostics/finding.ts | 7 ++-- .../workspace-code/src/kinds/credentials.ts | 9 ++--- .../workspace-code/src/kinds/deployment.ts | 12 ++++--- packages/workspace-code/src/kinds/group.ts | 33 ++++++++++------- packages/workspace-code/src/kinds/mcp.ts | 13 ++++--- packages/workspace-code/src/kinds/skills.ts | 2 +- packages/workspace-code/src/kinds/table.ts | 9 +++-- packages/workspace-code/src/kinds/tools.ts | 20 ++++++----- packages/workspace-code/src/layout.ts | 4 +++ packages/workspace-code/src/limits.ts | 5 +-- packages/workspace-code/src/promote.ts | 21 +++++------ packages/workspace-code/src/specs.ts | 2 +- 41 files changed, 226 insertions(+), 159 deletions(-) delete mode 100644 packages/workflow-sdk/src/codegen/major.ts diff --git a/apps/docs/content/docs/workflows/code/directory.mdx b/apps/docs/content/docs/workflows/code/directory.mdx index ae2aec5f011..ae7feabab71 100644 --- a/apps/docs/content/docs/workflows/code/directory.mdx +++ b/apps/docs/content/docs/workflows/code/directory.mdx @@ -57,7 +57,7 @@ A resource's key is its file or folder name, and a workflow names it by that key - `credentials.ts`: `export default defineCredentials({ : { provider, name? } })`, binding each key to this workspace's credential for that provider (never a token): the one bound already, else the only one, else the one whose display name is `name`. A workflow: `credential('')`; one using a key no credential binds to is held back, and the rest apply. - `tools/.ts` (`defineTool({ title, schema, code: codeFile('./.js') })`) and its code in `tools/.js`, where each schema parameter is a variable. Code holding a literal credential prints as `code: stored()`, which keeps the stored code. A workflow: `customTool('')`. - `skills/.md`: a frontmatter block of `name` and `description`, then the content. A workflow: `skills: [skill('')]` on an agent. -- `mcp/.ts`: `export default defineMcpServer({ name?, url, headers?, auth?, timeout?, retries?, enabled? })`. A credential header holds `env.NAME` or `'Bearer {{NAME}}'`, never a literal secret; `stored()` keeps the value the server holds. A changed `url` replaces the server. A workflow: `mcp('').tool('')`. +- `mcp/.ts`: `export default defineMcpServer({ name?, url, headers?, auth?, timeout?, retries?, enabled? })`. A credential header holds `env.NAME` or `'Bearer {{NAME}}'`, never a literal secret; `stored()` keeps the value the server holds. A new host or path in `url` replaces the server; a new query string updates it in place. A workflow: `mcp('').tool('')`. - `tables/.ts`: `export default defineTable({ name, description?, folder?, columns: { … } })` with `column.string()`, `column.number()`, `column.select({ options: [...] })`, … from `@sim/workflow-sdk/workspace`. Rows stay out of source unless `rows` opts in: `{ mode: 'managed', key: '' }` keeps the rows equal to `tables/.rows.jsonl` (one JSON object per line, keyed by column key), `{ mode: 'seed' }` writes them once into a new table. A workflow: `table('')`. - `knowledge//knowledge.ts` (`defineKnowledgeBase({ name, description?, folder?, chunking?, embeddingModel? })`) and `knowledge//docs/`, one file per document, flat. A workflow: `knowledgeBase('')`. Connector-synced documents are never part of source. - `files/`: every file is one workspace file at that folder path; no declaration. diff --git a/apps/sim/lib/workflows/code/real-catalog.test.ts b/apps/sim/lib/workflows/code/real-catalog.test.ts index 984778f7bb6..ad282d53449 100644 --- a/apps/sim/lib/workflows/code/real-catalog.test.ts +++ b/apps/sim/lib/workflows/code/real-catalog.test.ts @@ -18,10 +18,12 @@ import { printWorkflow, type ResourceKeyResolver, } from '@sim/workflow-code' +import { SDK_SPECIAL_BUILDERS } from '@sim/workflow-code/sdk' import { + builderSnippet, COOKBOOK_EXAMPLES, + describeBuilder, generateWorkspaceTypes, - SPECIAL_BUILDER_KEYS, WORKSPACE_COOKBOOK, type WorkspaceManifest, } from '@sim/workflow-sdk/codegen' @@ -104,7 +106,9 @@ describe('canonicalize and codegen over the real block catalog', () => { it('maps every builder core.d.ts declares to the block type its signature is written for', () => { expect( - Object.fromEntries(SPECIAL_BUILDER_KEYS.map((key) => [key, catalogBuilder(catalog, key)])) + Object.fromEntries( + Object.keys(SDK_SPECIAL_BUILDERS).map((key) => [key, catalogBuilder(catalog, key)]) + ) ).toEqual({ condition: { type: 'condition' }, router: { type: 'router_v2' }, @@ -117,6 +121,11 @@ describe('canonicalize and codegen over the real block catalog', () => { }) }) + it("fills an MCP server param of a builder's example call with mcp('')", () => { + const reference = describeBuilder(catalog, 'mcpBlock.runOperation') + expect(reference && builderSnippet(reference)).toContain("mcp('')") + }) + it('projects a registry multiSelect dropdown or combobox as a multiple subBlock', () => { const missing: string[] = [] let multiSelects = 0 diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 6e286410b31..51e9d979dcf 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -14,7 +14,7 @@ import { SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE, } from '@sim/workflow-code/limits' -import { SDK_GUIDE_FILE, SOURCE_COMPILER_OPTIONS } from '@sim/workflow-sdk/codegen' +import { SDK_GUIDE_FILE, SDK_MAJOR, SOURCE_COMPILER_OPTIONS } from '@sim/workflow-sdk/codegen' import { SOURCE_PLANNED_EXIT_CODE, SOURCE_STALE_EXIT_CODE } from '../../exit-codes' import type { ApplyWorkflowSourceBody, GetWorkflowSourceResponse } from '../../generated/v2-api' import type { OperationClient } from '../../runtime/called-operations' @@ -244,7 +244,7 @@ export default workflow('Workflow name', {}, () => { }) \`\`\` -The \`// @sim-sdk 1\` 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 \`{}\`. +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 \`{}\`. ## Finding a builder and its types @@ -316,7 +316,7 @@ export const WORKFLOW_TREE: SourceTreeProfile = { } /** The `workflow.ts` a new directory starts from: the smallest workflow that compiles. */ -const STARTER_SOURCE = `// @sim-sdk 1 +const STARTER_SOURCE = `// @sim-sdk ${SDK_MAJOR} import { response, trigger, workflow } from '@sim/workflow-sdk' export default workflow('New workflow', { description: 'Describe what this workflow does.' }, () => { diff --git a/packages/workflow-code/src/babel.ts b/packages/workflow-code/src/babel.ts index bb3f94cdf1b..e5510c151ab 100644 --- a/packages/workflow-code/src/babel.ts +++ b/packages/workflow-code/src/babel.ts @@ -17,6 +17,12 @@ export function babelErrorShape(error: unknown): BabelErrorShape { return typeof error === 'object' && error !== null ? error : {} } +/** A Babel error's message without its trailing `(line:column)`. */ +export function babelMessage(error: BabelErrorShape): string { + const message = typeof error.message === 'string' ? error.message : 'Invalid syntax' + return message.replace(/ \(\d+:\d+\)$/, '') +} + const SKIPPED_KEYS = new Set([ 'leadingComments', 'trailingComments', diff --git a/packages/workflow-code/src/catalog/surface.ts b/packages/workflow-code/src/catalog/surface.ts index 6c74f0cb3f4..8549f85b69d 100644 --- a/packages/workflow-code/src/catalog/surface.ts +++ b/packages/workflow-code/src/catalog/surface.ts @@ -32,6 +32,14 @@ export function isTriggerSurface(subBlock: SurfaceFields): boolean { return subBlock.mode === 'trigger' || subBlock.mode === 'trigger-advanced' } +/** + * Whether a declaration is a block's model picker: the `model` combobox, whose options are the + * models the catalog lists but whose value may name any other. + */ +export function isModelField(subBlock: Pick): boolean { + return subBlock.id === 'model' && subBlock.type === 'combobox' +} + /** * Trigger subBlocks source never states: the shared system set (setup text, sample payloads, the * webhook URL display, schedule info) minus the credential, which source writes, plus the diff --git a/packages/workflow-code/src/code-files/from-file.ts b/packages/workflow-code/src/code-files/from-file.ts index 9d81cbe57f1..9898d4c46e6 100644 --- a/packages/workflow-code/src/code-files/from-file.ts +++ b/packages/workflow-code/src/code-files/from-file.ts @@ -1,7 +1,7 @@ import { type ParserOptions, parse } from '@babel/parser' import type { Expression, MemberExpression, Node } from '@babel/types' import { isLikelyWorkflowReferenceSegment } from '@sim/utils/workflow-references' -import { babelErrorShape, childNodes, memberSegment } from '../babel' +import { babelErrorShape, babelMessage, childNodes, memberSegment } from '../babel' import { ENV_VAR_NAME, formatStoredPath, type RefSegment } from './ref-path' import { type CodeFileLanguage, ENV_ROOT, REF_ROOT } from './to-file' @@ -56,7 +56,7 @@ function toSyntaxError(error: unknown): CodeFileSyntaxError { const line = typeof shape.loc?.line === 'number' ? shape.loc.line : 1 const column = typeof shape.loc?.column === 'number' ? shape.loc.column + 1 : 1 return { - message: typeof shape.message === 'string' ? shape.message : 'Invalid JavaScript', + message: babelMessage(shape), start: typeof shape.pos === 'number' ? shape.pos : 0, line, column, diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 22b47b1a6d6..2ba78cd721f 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -16,7 +16,7 @@ import { type WorkflowBranchKind, } from '@sim/workflow-types/workflow' import { encodeAnchor } from '../anchors' -import { babelErrorShape } from '../babel' +import { babelErrorShape, babelMessage } from '../babel' import { isBranchExtraField } from '../canonicalize/branches' import { DEFAULT_LOOP_ITERATIONS, @@ -34,6 +34,7 @@ import { declarationFor, type FieldIndex, isModalPair, + isModelField, isWrittenInSource, memberFor, typedForBuilder, @@ -46,7 +47,12 @@ import { codeFileLanguage, fromCodeFile, } from '../code-files' -import { isIdentifierName, LOOP_PROPERTIES, parseStoredPath } from '../code-files/ref-path' +import { + ENV_VAR_NAME, + isIdentifierName, + LOOP_PROPERTIES, + parseStoredPath, +} from '../code-files/ref-path' import { branchesAtTopLevel, ELSE_KEY, isElseTrue } from '../forms/condition' import { compileResponseParam, usesResponseForm } from '../forms/response' import { type ConfigField, type ContainerForm, loopForm, parallelForm } from '../forms/subflow' @@ -84,7 +90,7 @@ import { unsupported, } from './context' import { closest, didYouMean } from './hints' -import { babelMessage, bracketDepthOverflow } from './parse' +import { bracketDepthOverflow } from './parse' import type { Range } from './report' import { compileToolList } from './tools' import { @@ -522,9 +528,6 @@ function reportScriptRefSyntax( } } -/** The name inside a `{{NAME}}` env token a run substitutes; other `{{…}}` text is left alone. */ -const ENV_TOKEN_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/ - /** * The `` references a code file writes as text, found by the runtime's own scanner (a * JavaScript string, a Python or shell line): the run resolves each one, so compile checks them as @@ -535,7 +538,7 @@ function referenceTags(text: string): CodeFileRef[] { for (const token of findWorkflowReferenceTokens(text)) { if (token.kind === 'environment') { const name = token.value.slice(2, -2).trim() - if (ENV_TOKEN_NAME.test(name)) { + if (ENV_VAR_NAME.test(name)) { tags.push({ kind: 'env', name, start: token.start, end: token.end }) } continue @@ -1490,7 +1493,7 @@ function unknownOption( ): { value: string; ids: string[] } | null { const options = sub.options if (!Array.isArray(options) || options.length === 0) return null - const isModel = sub.id === 'model' && sub.type === 'combobox' + const isModel = isModelField(sub) if (sub.type !== 'dropdown' && !isModel) return null const ids = options.map((option) => option.id) const known = new Set(ids) @@ -1537,7 +1540,7 @@ function checkOption( ) return } - if (sub.id === 'model' && sub.type === 'combobox') { + if (isModelField(sub)) { ctx.reporter.report( 'W_UNKNOWN_MODEL', `${unknown.value} is not a model the catalog lists; it is kept as written.`, diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 2f17a5583ab..37c140dfb5f 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -600,6 +600,20 @@ describe('typed references in JSON fields', () => { expect(findings(result, 'W_JSON_REF_UNTYPED')).toEqual([]) }) + it('keeps a reference to an output the block lacks out of W_JSON_REF_UNTYPED past the warning cap', () => { + const fields = Array.from({ length: 25 }, (_, i) => `k${i}: a.missing${i}`).join(', ') + const result = run( + [ + START, + "const a = api('A', { url: 'https://x' })", + `const b = api('B', { url: 'https://x', body: { ${fields} } })`, + 'start.to(a)', + 'a.to(b)', + ].join('\n') + ) + expect(findings(result, 'W_JSON_REF_UNTYPED')).toEqual([]) + }) + it('still warns that an input the start does not declare is stored bare, as a caller may pass text', () => { const result = run( [ diff --git a/packages/workflow-code/src/compile/context.ts b/packages/workflow-code/src/compile/context.ts index 4ae8f33b5d1..a8debf6da23 100644 --- a/packages/workflow-code/src/compile/context.ts +++ b/packages/workflow-code/src/compile/context.ts @@ -122,8 +122,9 @@ interface CodeFileBudget { /** Bytes of the entry plus the distinct code files read so far. */ bytes: number /** - * The `$ref` chains and `$env` names of each distinct JavaScript file read, checked against the declared blocks - * once every block is known (`checkCodeFileRefs`). + * The references of each distinct code file read: `$ref` chains and `$env` names (JavaScript) + * plus `` tags (every language), checked once every block is known + * (`checkCodeFileRefs`). */ chains: Array<{ path: string; blockKey: BlockKey; refs: CodeFileRef[] }> /** @@ -191,6 +192,11 @@ export interface CompileContext { * `x.errorMessage`), checked once the edges are known (`checkErrorOutputRefs`). */ errorOutputRefs: Array & { output: string }> + /** + * Where each reference that reads nothing was reported (`file:start`), listed or not, so the JSON + * field check leaves it out of `W_JSON_REF_UNTYPED`. + */ + unknownRefAt: Set /** * Branch keys already refused with an error, by block key. Wiring and branch meta that name one * stay quiet instead of adding `E_UNKNOWN_BRANCH` for the same mistake. diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 488b90128db..2e672e1c4b1 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1200,6 +1200,7 @@ describe('errors, each with its code, location and hint', () => { }) const syntax = result.diagnostics.find((d) => d.code === 'E_SYNTAX') expect(syntax?.span).toMatchObject({ file: 'workflows/functions/bad.js', line: 1 }) + expect(syntax?.message).not.toMatch(/\(\d+:\d+\)$/) expect(result.workflow).toBeNull() }) diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index 91558307d64..9e4f17747c2 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -594,6 +594,7 @@ function compileEntry( dynamicOutputRefs: [], unresolvedTags: [], errorOutputRefs: [], + unknownRefAt: new Set(), refusedBranches: new Map(), valueConsts: new Set(), } @@ -705,9 +706,8 @@ function compileEntry( }) } - const unread = input.stored === undefined ? input.storedUnread : undefined - const unreadRenames = unread - ? lockIdentRenames(hints, unread, (key) => Object.hasOwn(unread.blocks, key)) + const unreadRenames = storedUnread + ? lockIdentRenames(hints, storedUnread, (key) => Object.hasOwn(storedUnread.blocks, key)) : new Map() const renamed = new Map([...unreadRenames, ...(input.renamedKeys ?? [])]) checkCodeFileRefs(ctx, renamed) @@ -745,9 +745,9 @@ function compileEntry( const edges = new EdgeCollector( ctx, compiled, - unread && { + storedUnread && { lockKeys: new Map([ - ...Object.keys(unread.blocks).map((key) => [key, key] as const), + ...Object.keys(storedUnread.blocks).map((key) => [key, key] as const), ...[...unreadRenames].map(([lockKey, key]) => [key, lockKey] as const), ]), ...(input.storedUnreadEdges @@ -774,9 +774,7 @@ function compileEntry( // one finding: whether text there would break the JSON is moot until the path is fixed. An input // the start does not declare is not: a caller may still pass text there. const unknownAt = new Set([ - ...reporter.diagnostics - .filter((d) => d.code === 'W_UNKNOWN_OUTPUT_PATH' || d.code === 'W_UNRESOLVED_REF') - .map((d) => `${d.span.file}:${d.span.start}`), + ...ctx.unknownRefAt, ...ctx.errorOutputRefs .filter(({ target }) => !erroring.has(target.key)) .map(({ at }) => `${at.file}:${at.start}`), diff --git a/packages/workflow-code/src/compile/parse.ts b/packages/workflow-code/src/compile/parse.ts index 29ca14fa292..e66698ee3e4 100644 --- a/packages/workflow-code/src/compile/parse.ts +++ b/packages/workflow-code/src/compile/parse.ts @@ -1,7 +1,7 @@ import { type ParserOptions, parse } from '@babel/parser' import type { File, Node } from '@babel/types' import { utf8ByteLength } from '@sim/utils/paste' -import { type BabelErrorShape, babelErrorShape, childNodes } from '../babel' +import { type BabelErrorShape, babelErrorShape, babelMessage, childNodes } from '../babel' import { codeFileLanguage } from '../code-files' import { createJsContextScanner } from '../code-files/lexer' import { SOURCE_LIMITS } from '../limits' @@ -88,12 +88,6 @@ function depthOverflow(root: Node, maxDepth: number): Node | null { return null } -/** A Babel error's message without its trailing `(line:column)`. */ -export function babelMessage(error: BabelErrorShape): string { - const message = typeof error.message === 'string' ? error.message : 'Invalid syntax' - return message.replace(/ \(\d+:\d+\)$/, '') -} - interface ParsedSource { ast: File | null /** The header's major, or `null` when the first line is not `// @sim-sdk N`. */ diff --git a/packages/workflow-code/src/compile/report.ts b/packages/workflow-code/src/compile/report.ts index 050f243323f..a5c992223a5 100644 --- a/packages/workflow-code/src/compile/report.ts +++ b/packages/workflow-code/src/compile/report.ts @@ -53,7 +53,7 @@ export interface Range { end: number } -interface ReportExtras { +export interface ReportExtras { /** * A function is called only when the diagnostic is recorded, so a costly did-you-mean is never * computed for a warning past {@link MAX_LISTED}; a withheld warning computes it when its diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index 32486939295..c92e41d80f9 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -66,7 +66,7 @@ import { unsupported, } from './context' import { didYouMean, HINTS, hintForNode, nodeLabel } from './hints' -import type { Range } from './report' +import type { Range, ReportExtras } from './report' /** Where a value is compiled: the block it belongs to and the scope its identifiers resolve in. */ export interface ValueSite { @@ -300,6 +300,22 @@ function reportNotNormalized(ctx: CompileContext, tag: LiteralTag): void { ) } +/** + * Reports a reference that reads nothing (`W_UNKNOWN_OUTPUT_PATH`, `W_UNRESOLVED_REF`) and records + * where it is, so the JSON field check does not also call it untyped, even when the warning cap + * leaves the finding out of the listing. + */ +function reportUnknownRef( + ctx: CompileContext, + code: 'W_UNKNOWN_OUTPUT_PATH' | 'W_UNRESOLVED_REF', + message: string, + at: Range, + extras: ReportExtras +): void { + ctx.unknownRefAt.add(`${at.file}:${at.start}`) + ctx.reporter.report(code, message, at, extras) +} + /** * Reports each literal `` whose head names no block once the apply's renames are known * (`renamed`, stored key → source key). The apply rewrites a renamed block's stored key to its new @@ -316,7 +332,8 @@ export function checkUnresolvedTags( reportNotNormalized(ctx, tag) continue } - ctx.reporter.report( + reportUnknownRef( + ctx, 'W_UNRESOLVED_REF', `${tag.token} names no block, so it does not resolve at run time.`, tag.at, @@ -807,7 +824,8 @@ function checkOutputPath( ...(containerKind === 'loop' ? LOOP_PROPERTIES : PARALLEL_PROPERTIES), ] if (first.kind === 'name' && !known.includes(first.name)) { - ctx.reporter.report( + reportUnknownRef( + ctx, 'W_UNKNOWN_OUTPUT_PATH', `A ${containerKind} has no output ${first.name}.`, at, @@ -836,7 +854,8 @@ function checkOutputPath( ctx.errorOutputRefs.push({ at, target, blockKey, output: errorOutput }) return } - ctx.reporter.report( + reportUnknownRef( + ctx, 'W_UNKNOWN_OUTPUT_PATH', `${target.name} has no output ${formatStoredPath(segments)}.`, at, @@ -945,7 +964,8 @@ export function checkDynamicOutputRefs( ) continue } - ctx.reporter.report( + reportUnknownRef( + ctx, 'W_UNKNOWN_OUTPUT_PATH', fields.length > 0 ? `${target.name} has no output ${path}: its responseFormat declares ${fields.join(', ')}.` @@ -994,7 +1014,8 @@ export function checkCodeFileRefs( if (head.name === 'variable') { const name = rest[0]?.kind === 'name' ? rest[0].name : null if (name !== null && !ctx.variables.has(name)) { - ctx.reporter.report( + reportUnknownRef( + ctx, 'W_UNRESOLVED_REF', `${written}: no workflow variable is keyed ${name}.`, at, @@ -1025,7 +1046,8 @@ export function checkCodeFileRefs( const byName = ctx.declsByKey.get(normalizeWorkflowBlockName(head.name)) const suggested = byIdent ?? byName const rewritten = (key: BlockKey) => spell([{ kind: 'name', name: key }, ...rest]) - ctx.reporter.report( + reportUnknownRef( + ctx, 'W_UNRESOLVED_REF', `${written} names no block, so it does not resolve at run time.`, at, diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 2d6eef61272..26381dfe703 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -1,5 +1,5 @@ export { decodeAnchor, encodeAnchor } from './anchors' -export { babelErrorShape } from './babel' +export { babelErrorShape, babelMessage } from './babel' export { type CanonicalizeResult, canonicalize, canonicalizeUnderLock } from './canonicalize' export { toolModes } from './canonicalize/modes' export { builderOutputSchemas, executableInactiveParams } from './catalog/activity' @@ -41,12 +41,7 @@ export { export { type CompileResult, compileWorkflow, type StoredEdgeRef } from './compile' export { codePointLabel, scriptName } from './compile/characters' export { didYouMean, suggestBuilder } from './compile/hints' -export { - babelMessage, - bracketDepthOverflow, - sdkHeader, - sourceDepthOverflow, -} from './compile/parse' +export { bracketDepthOverflow, sdkHeader, sourceDepthOverflow } from './compile/parse' export { LineIndex } from './compile/report' export { type ApplyDiagnosticCode, diff --git a/packages/workflow-code/src/json-fields.ts b/packages/workflow-code/src/json-fields.ts index dd7f704d51f..ba5d0bc6a6f 100644 --- a/packages/workflow-code/src/json-fields.ts +++ b/packages/workflow-code/src/json-fields.ts @@ -20,7 +20,7 @@ import { isRecordLike } from '@sim/utils/object' import { blockOutputSchemas, errorOutputOf } from './catalog/activity' import type { BlockCatalog, CatalogOutput } from './catalog/types' import { catalogBlock } from './catalog/view' -import { parseStoredPath, type RefSegment } from './code-files/ref-path' +import { ENV_VAR_NAME, parseStoredPath, type RefSegment } from './code-files/ref-path' import { referencedResultKind } from './compile/function-returns' import { type BlockKey, @@ -282,7 +282,9 @@ export function jsonFieldText(tree: JsonTree, isString: (token: string) => boole /** The single reference a whole JSON string holds (`""`, `"{{X}}"`), if any. */ function wholeToken(text: string): string | null { - if (/^\{\{[A-Za-z_][A-Za-z0-9_]*\}\}$/.test(text)) return text + if (text.startsWith('{{') && text.endsWith('}}') && ENV_VAR_NAME.test(text.slice(2, -2))) { + return text + } if (!text.startsWith('<') || !text.endsWith('>')) return null return parseStoredPath(text.slice(1, -1)) ? text : null } diff --git a/packages/workflow-code/src/print/context.ts b/packages/workflow-code/src/print/context.ts index dba17334f3a..ceab13466fa 100644 --- a/packages/workflow-code/src/print/context.ts +++ b/packages/workflow-code/src/print/context.ts @@ -69,7 +69,7 @@ export function foldCodePath(path: string): string { return path.normalize('NFC').toLowerCase() } -/** The context for printing `input`, with its parent tree built; `layout` fills the rest. */ +/** The context for printing `input`, with its parent tree built; `orderDeclarations` (print/scope.ts) fills the rest. */ export function createPrintContext(input: PrintInput): PrintContext { const workflow = input.workflow const catalog = input.catalog diff --git a/packages/workflow-code/src/print/edges.ts b/packages/workflow-code/src/print/edges.ts index e5d9724c882..fef013ad84e 100644 --- a/packages/workflow-code/src/print/edges.ts +++ b/packages/workflow-code/src/print/edges.ts @@ -205,12 +205,6 @@ export function wiringStatements( targets = targets.filter((edge) => !mismatched.includes(edge)) if (targets.length === 0) continue } - if (kind.kind === 'subflowStart') { - for (const edge of targets) { - statements.push({ expr: raw(source, 'loop-start-source', edge.to), anchor, source }) - } - continue - } if (kind.kind === 'raw' || (kind.kind === 'out' && (isContainer || hasBranches))) { const handle = kind.kind === 'raw' ? kind.handle : 'source' for (const edge of [...targets].sort(byTarget)) { @@ -218,12 +212,6 @@ export function wiringStatements( } continue } - if (kind.kind === 'subflowEnd' && !isContainer) { - for (const edge of [...targets].sort(byTarget)) { - statements.push({ expr: raw(source, 'loop-end-source', edge.to), anchor, source }) - } - continue - } if (kind.kind === 'error') { statements.push({ expr: call(ident, targets, 'onError'), anchor, source }) } else if (kind.kind === 'branch') { diff --git a/packages/workflow-code/src/sdk.ts b/packages/workflow-code/src/sdk.ts index 41258878f63..eac04fe1b18 100644 --- a/packages/workflow-code/src/sdk.ts +++ b/packages/workflow-code/src/sdk.ts @@ -7,6 +7,14 @@ import type { CatalogBlock, CatalogBuilder } from './catalog/types' import type { ResourceKind } from './model' +/** + * The SDK major `core.d.ts` is written for, the one the server's block catalog serves, and the + * only one a workflow or declaration file's `// @sim-sdk N` header may name. A block catalog for + * another major describes builders these declarations cannot type, so a consumer bundling + * `CORE_DTS` refuses to write beside it. + */ +export const SDK_MAJOR = 1 + /** The module a workflow file imports the SDK from: the only import compile accepts. */ export const SDK_MODULE = '@sim/workflow-sdk' diff --git a/packages/workflow-sdk/src/codegen/generate.ts b/packages/workflow-sdk/src/codegen/generate.ts index 84445c04fc7..ceb7de6eb43 100644 --- a/packages/workflow-sdk/src/codegen/generate.ts +++ b/packages/workflow-sdk/src/codegen/generate.ts @@ -23,6 +23,7 @@ import { type EditorDefault, subBlockEditorDefault } from '@sim/workflow-code/ca import { builderPins, hasDefaultValue, + isModelField, isWrittenInSource, onSurface, paramAliases, @@ -736,7 +737,7 @@ function modelIds(catalog: BlockCatalog): string[] { const ids = new Set() for (const type of catalogBlockTypes(catalog)) { for (const subBlock of catalogBlock(catalog, type)?.subBlocks ?? []) { - if (subBlock.id !== 'model' || subBlock.type !== 'combobox') continue + if (!isModelField(subBlock)) continue if (!Array.isArray(subBlock.options)) continue for (const option of subBlock.options) ids.add(option.id) } diff --git a/packages/workflow-sdk/src/codegen/index.ts b/packages/workflow-sdk/src/codegen/index.ts index 30b7f99a658..8cc93fb21a5 100644 --- a/packages/workflow-sdk/src/codegen/index.ts +++ b/packages/workflow-sdk/src/codegen/index.ts @@ -1,3 +1,4 @@ +export { SDK_MAJOR } from '@sim/workflow-code/sdk' export { COOKBOOK_EXAMPLES } from './cookbook-text.generated' export { CORE_DTS } from './core-text.generated' export { @@ -16,8 +17,6 @@ export { SDK_INDEX_FILE, SDK_MODELS_FILE, } from './layout' -export { SDK_MAJOR } from './major' -export { SPECIAL_BUILDER_KEYS } from './names' export { type BuilderLookup, type BuilderReference, diff --git a/packages/workflow-sdk/src/codegen/major.ts b/packages/workflow-sdk/src/codegen/major.ts deleted file mode 100644 index 615d7959d8c..00000000000 --- a/packages/workflow-sdk/src/codegen/major.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * The SDK major `core.d.ts` is written for, and the one the server's block catalog serves. A block - * catalog for another major describes builders these declarations cannot type, so a consumer - * bundling `CORE_DTS` refuses to write beside it. - */ -export const SDK_MAJOR = 1 diff --git a/packages/workflow-sdk/src/codegen/map-subblock.ts b/packages/workflow-sdk/src/codegen/map-subblock.ts index 47eb5ec781d..75d710911d4 100644 --- a/packages/workflow-sdk/src/codegen/map-subblock.ts +++ b/packages/workflow-sdk/src/codegen/map-subblock.ts @@ -9,7 +9,7 @@ import type { CatalogSubBlock } from '@sim/workflow-code' import { quoteString } from '@sim/workflow-code' -import { isCredentialIdTwin } from '@sim/workflow-code/catalog/surface' +import { isCredentialIdTwin, isModelField } from '@sim/workflow-code/catalog/surface' import type { SubBlockType } from '@sim/workflow-types/blocks' import { arrayOf, literal, union } from './emit' @@ -97,7 +97,7 @@ export function mapSubBlock(subBlock: CatalogSubBlock): MappedType | null { case 'dropdown': return { type: dropdownType(subBlock), doc: [...doc, ...selectorDoc(subBlock)] } case 'combobox': { - if (subBlock.id === 'model') return { type: 'Value>', doc } + if (isModelField(subBlock)) return { type: 'Value>', doc } const options = staticOptions(subBlock) return { type: options ? `Value>` : 'Value', diff --git a/packages/workflow-sdk/src/codegen/names.ts b/packages/workflow-sdk/src/codegen/names.ts index ce148d1a525..18f1c6ab434 100644 --- a/packages/workflow-sdk/src/codegen/names.ts +++ b/packages/workflow-sdk/src/codegen/names.ts @@ -15,9 +15,6 @@ import { } from '@sim/workflow-code/sdk' import { pascal } from './emit' -/** The builder paths `core.d.ts` declares itself; the catalog must map each to its block type. */ -export const SPECIAL_BUILDER_KEYS: readonly string[] = Object.keys(SDK_SPECIAL_BUILDERS) - const CORE_EXPORTS: ReadonlySet = new Set(SDK_CORE_EXPORTS) /** The namespace each tool-form builder is exposed under: `slack.tool.sendMessage(...)`. */ diff --git a/packages/workflow-sdk/src/codegen/reference.ts b/packages/workflow-sdk/src/codegen/reference.ts index adf46520c01..b0dbe151f20 100644 --- a/packages/workflow-sdk/src/codegen/reference.ts +++ b/packages/workflow-sdk/src/codegen/reference.ts @@ -278,6 +278,9 @@ function exampleValue(type: string): string { if (/^TableData\b/.test(type)) return "{ column: '…' }" if (/^KnowledgeBaseRef\b/.test(type)) return "knowledgeBase('')" if (/^WorkflowRef\b/.test(type)) return "childWorkflow('')" + if (/^McpServerRef\b/.test(type)) return "mcp('')" + if (/^FolderRef\b/.test(type)) return "folder('')" + if (/^FileRef\b/.test(type)) return "file('')" if (/^(?:Template|string|Value.ts`). A header value is plain text in which `{{NAME}}` names an env variable anywhere (`Authorization: 'Bearer {{GITHUB_TOKEN}}'`), `env.NAME` for a whole value, or `stored()` to keep the value the server holds. A `t` template or a template literal with `\u0024{}` is refused. A credential header (`Authorization`, `Cookie`, or a name with `key`, `token`, `secret`, `auth`, `password`, `session`, `signature` or `credential`) holds nothing but an optional scheme word (`Bearer`, `Basic`, `Token`, `Bot`, `ApiKey`) and `{{NAME}}` references (`E_MCP_LITERAL_SECRET`). The variables resolve when the server connects, from the personal and workspace env (the workspace value wins); a missing one fails the connection.", + "- **MCP headers** (`mcp/.ts`). A header value is plain text in which `{{NAME}}` names an env variable anywhere (`Authorization: 'Bearer {{GITHUB_TOKEN}}'`), `env.NAME` for a whole value, or `stored()` to keep the value the server holds. A `t` template or a template literal with `\u0024{}` is refused. A credential header (`Authorization`, `Cookie`, or a name with `key`, `token`, `secret`, `auth`, `password`, `session`, `signature` or `credential`) holds nothing but an optional scheme word (`Bearer`, `Basic`, `Token`, `Bot`, `Digest`, `ApiKey`, `Key`) and `{{NAME}}` references (`E_MCP_LITERAL_SECRET`). The variables resolve when the server connects, from the personal and workspace env (the workspace value wins); a missing one fails the connection.", "- **Table rows are keyed by column name.** A Table block's `data` (and `conflictColumn`, and a filter's `field`) names each column by its name: its key in `tables/.ts`, or the `name` set there (`phone: column.string({ name: 'mobile' })` is written `{ mobile: … }`). A key naming no column is dropped from the row at run time; `check` and `apply` warn on it (`W_TABLE_UNKNOWN_COLUMN`). A table's `rows.jsonl` is the exception: it is keyed by column key.", "- **MCP tool names are checked late.** `mcp('k').tool('name')` is type-checked only when `workspace.d.ts` lists that server's tools; a server that could not be listed, or one declared but not yet applied, takes any name. `sim workflows source check` and `sim workflows source apply` do not check tool names (the apply checks only that the server exists). `sim workspaces source apply` checks the tools of each workflow it changes against the server's live listing (`E_MCP_TOOL_UNKNOWN`, or `W_MCP_TOOLS_UNCHECKED` when it cannot list the server). Otherwise a wrong name surfaces at run time: the agent block fails before the model runs, `MCP operation \"name\" is missing or not permitted`.", '', diff --git a/packages/workflow-sdk/src/not-executable.ts b/packages/workflow-sdk/src/not-executable.ts index 259daf6cb91..d5d9596962a 100644 --- a/packages/workflow-sdk/src/not-executable.ts +++ b/packages/workflow-sdk/src/not-executable.ts @@ -3,13 +3,13 @@ * declaration files are compiled or read statically, never executed. */ -/** Thrown by every runtime export: workflow files are compiled, never executed. */ +/** Thrown by every runtime export: Sim source files are read statically, never executed. */ export class SimSdkNotExecutable extends Error { readonly export: string constructor(exportName: string) { super( - `@sim/workflow-sdk: \`${exportName}\` does not run. Workflow files are compiled by Sim, never executed; check them with \`sim workflows source apply --dry-run\` or a type-check.` + `@sim/workflow-sdk: \`${exportName}\` does not run. Sim source files are read statically, never executed; check them with \`sim workflows source check\` or \`sim workspaces source check\`.` ) this.name = 'SimSdkNotExecutable' this.export = exportName diff --git a/packages/workspace-code/src/declaration/print.ts b/packages/workspace-code/src/declaration/print.ts index 72a6de544ab..48f5a39ad88 100644 --- a/packages/workspace-code/src/declaration/print.ts +++ b/packages/workspace-code/src/declaration/print.ts @@ -6,9 +6,9 @@ */ import { compareStrings } from '@sim/utils/string' import { type Json, printKey, printNumber, quoteString } from '@sim/workflow-code' +import { SDK_MAJOR } from '@sim/workflow-code/sdk' import { CALL_KEY, - DECLARATION_SDK_MAJOR, ENV_KEY, isDeclarationCall, isDeclarationEnvRef, @@ -110,7 +110,7 @@ export function printDeclaration(callee: string, value: Json): string { const imports = [...helperRoots(value, new Set([callee]))].sort(compareStrings) const exported = `export default ${callee}(` return [ - `// @sim-sdk ${DECLARATION_SDK_MAJOR}`, + `// @sim-sdk ${SDK_MAJOR}`, `import { ${imports.join(', ')} } from '${WORKSPACE_SDK_MODULE}'`, '', `${exported}${printValue(value, '', exported.length)})`, diff --git a/packages/workspace-code/src/declaration/read.ts b/packages/workspace-code/src/declaration/read.ts index 97ed086b335..f7b920e1a00 100644 --- a/packages/workspace-code/src/declaration/read.ts +++ b/packages/workspace-code/src/declaration/read.ts @@ -28,6 +28,7 @@ import { type SourceSpan, sdkHeader, } from '@sim/workflow-code' +import { SDK_MAJOR } from '@sim/workflow-code/sdk' import { diagnostic, findingLimitReached, @@ -39,8 +40,6 @@ import { WORKSPACE_SOURCE_LIMITS } from '../limits' /** The module every declaration imports from. */ export const WORKSPACE_SDK_MODULE = '@sim/workflow-sdk/workspace' -/** The only SDK major declarations are written in. */ -export const DECLARATION_SDK_MAJOR = 1 /** The key a helper call is read under; no declaration object may use it. */ export const CALL_KEY = '$call' /** The key an `env.NAME` reference is read under; no declaration object may use it. */ @@ -99,6 +98,14 @@ export function isDeclarationCall(value: unknown): value is DeclarationCall { return isRecordLike(value) && typeof value[CALL_KEY] === 'string' && Array.isArray(value.args) } +/** The helper that keeps the value the server already holds: `stored()`. */ +export const STORED_CALL = 'stored' + +/** Whether a decoded value is `stored()`, with no arguments. */ +export function isStoredCall(value: unknown): boolean { + return isDeclarationCall(value) && value.$call === STORED_CALL && value.args.length === 0 +} + /** Whether a decoded value is an `env.NAME` reference the reader produced. */ export function isDeclarationEnvRef(value: unknown): value is DeclarationEnvRef { return isRecordLike(value) && typeof value[ENV_KEY] === 'string' && ENV_NAME.test(value[ENV_KEY]) @@ -190,15 +197,11 @@ export function readDeclaration( return fail() } const header = sdkHeader(text) - if (header.sdkMajor !== DECLARATION_SDK_MAJOR) { + if (header.sdkMajor !== SDK_MAJOR) { diagnostics.push( - diagnostic( - 'E_DECL_HEADER', - `The first line must be \`// @sim-sdk ${DECLARATION_SDK_MAJOR}\`.`, - { - ...at(0, Math.max(1, header.headerEnd)), - } - ) + diagnostic('E_DECL_HEADER', `The first line must be \`// @sim-sdk ${SDK_MAJOR}\`.`, { + ...at(0, Math.max(1, header.headerEnd)), + }) ) return fail() } @@ -266,12 +269,13 @@ export function readDeclaration( declaration.type === 'CallExpression' && declaration.callee.type === 'Identifier' && declaration.callee.name === options.callee && - declaration.arguments.length === 1 && - declaration.arguments[0].type !== 'SpreadElement' && - declaration.arguments[0].type !== 'ArgumentPlaceholder' + declaration.arguments.length === 1 ) { - exported = declaration.arguments[0] as Expression - continue + const [argument] = declaration.arguments + if (argument.type !== 'SpreadElement' && argument.type !== 'ArgumentPlaceholder') { + exported = argument + continue + } } } record( diff --git a/packages/workspace-code/src/diagnostics/finding.ts b/packages/workspace-code/src/diagnostics/finding.ts index 2c8e669c7b5..78b0b6241a1 100644 --- a/packages/workspace-code/src/diagnostics/finding.ts +++ b/packages/workspace-code/src/diagnostics/finding.ts @@ -57,9 +57,10 @@ export function findingLimitReached(extras: DiagnosticExtras = {}): WorkspaceDia } /** - * A workspace finding with its severity filled in from the code. Its message and hint are cut as - * the compile cuts its own (`boundFindingText`): a limit that stops work, so a finding never holds - * more of the source it quotes (a 50 KB key, a hundred times in one file) than an answer could show. + * A workspace finding with its severity filled in from the code. Its message and hint are cut with + * the same bound the answer edge applies (`boundFindingText`): a limit that stops work, so a finding + * never holds more of the source it quotes (a 50 KB key, a hundred times in one file) than an answer + * could show. */ export function diagnostic( code: C, diff --git a/packages/workspace-code/src/kinds/credentials.ts b/packages/workspace-code/src/kinds/credentials.ts index 1cc3faea22e..5fcfc51d796 100644 --- a/packages/workspace-code/src/kinds/credentials.ts +++ b/packages/workspace-code/src/kinds/credentials.ts @@ -21,7 +21,7 @@ import type { ResourceFingerprint } from '../base' import { type DeclFields, stringField } from '../declaration/field-table' import type { KindCodec } from '../kind' -import { isResourceKey } from '../layout' +import { isResourceKey, RESOURCE_KEY_HINT } from '../layout' import { entryCodec, entryFingerprint } from './entries' /** One credential as `credentials.ts` declares it. */ @@ -48,12 +48,7 @@ export const credentialCodec: KindCodec = entryCodec.ts`. */ export function deploymentDeclarationPath(key: string): string { @@ -122,7 +126,7 @@ function canonicalSecret(secret: ChatSecretDecl): Json { function readSecret(raw: Json, pointer: string, report: FieldReport) { if (isDeclarationEnvRef(raw)) return { env: raw.$env } - if (isDeclarationCall(raw) && raw.$call === STORED_CALL && raw.args.length === 0) return 'stored' + if (isStoredCall(raw)) return 'stored' report( 'E_DEPLOY_SECRET', pointer, @@ -325,7 +329,7 @@ function parseDeployment( /** Reads and prints `deployments/.ts`. */ export const deploymentCodec: KindCodec = { - group: (paths) => groupByFile(KIND_DIRS.deployment, [DECLARATION_EXTENSION], paths), + group: (paths) => groupByFile(KIND_DIRS.deployment, DECLARATION_EXTENSION, paths), parse: (key, text) => parseDeployment(key, text), print: (key, decl) => ({ text: { diff --git a/packages/workspace-code/src/kinds/group.ts b/packages/workspace-code/src/kinds/group.ts index 0db5fd41390..21791ff8e16 100644 --- a/packages/workspace-code/src/kinds/group.ts +++ b/packages/workspace-code/src/kinds/group.ts @@ -1,10 +1,10 @@ import { diagnostic, type WorkspaceDiagnostic, wholeFile } from '../diagnostics' import type { GroupedPaths } from '../kind' -import { isResourceKey } from '../layout' +import { isResourceKey, RESOURCE_KEY_HINT } from '../layout' function keyProblem(path: string, key: string): WorkspaceDiagnostic { return diagnostic('E_KEY_INVALID', `"${key}" is not a valid key.`, { - hint: 'A key is lowercase letters, digits, `-` and `_`, starting with a letter, at most 64 characters.', + hint: RESOURCE_KEY_HINT, span: wholeFile(path), }) } @@ -16,29 +16,36 @@ function unknownFile(path: string, expected: string): WorkspaceDiagnostic { }) } +/** A second file a resource may keep beside its declaration, and what it holds (`its code`). */ +interface FileCompanion { + extension: string + holds: string +} + /** - * Groups a kind whose resources are files named by key: `/`, one file per - * extension (`tools/.ts` and `tools/.js` group under one key). + * Groups a kind whose resources are files named by key: `/`, plus the + * companion file when the kind has one (`tools/.ts` and `tools/.js` group under one key). */ export function groupByFile( dir: string, - allowed: readonly string[], - paths: readonly string[] + extension: string, + paths: readonly string[], + companion?: FileCompanion ): GroupedPaths { + const allowed = companion ? [extension, companion.extension] : [extension] const groups = new Map() const diagnostics: WorkspaceDiagnostic[] = [] for (const path of paths) { const name = path.slice(dir.length + 1) - const extension = allowed.find((candidate) => name.endsWith(candidate)) - if (name.includes('/') || extension === undefined) { - const [primary, ...companions] = allowed.map((candidate) => `\`${candidate}\``) - const expected = companions.length - ? `one ${primary} per resource, with its code in ${companions.join(' or ')}` - : `one ${primary} file per resource` + const matched = allowed.find((candidate) => name.endsWith(candidate)) + if (name.includes('/') || matched === undefined) { + const expected = companion + ? `one \`${extension}\` per resource, with ${companion.holds} in \`${companion.extension}\`` + : `one \`${extension}\` file per resource` diagnostics.push(unknownFile(path, expected)) continue } - const key = name.slice(0, -extension.length) + const key = name.slice(0, -matched.length) if (!isResourceKey(key)) { diagnostics.push(keyProblem(path, key)) continue diff --git a/packages/workspace-code/src/kinds/mcp.ts b/packages/workspace-code/src/kinds/mcp.ts index 1186abc07d0..8528543816c 100644 --- a/packages/workspace-code/src/kinds/mcp.ts +++ b/packages/workspace-code/src/kinds/mcp.ts @@ -44,9 +44,10 @@ import { } from '../declaration/fields' import { call, envRef, printDeclaration } from '../declaration/print' import { - isDeclarationCall, isDeclarationEnvRef, + isStoredCall, readDeclaration, + STORED_CALL, unstorableCharacter, } from '../declaration/read' import { diagnostic, resourceOf, type WorkspaceDiagnostic, wholeFile } from '../diagnostics' @@ -94,7 +95,10 @@ export interface McpServerDecl { /** The display name; the key when the declaration leaves it out. */ name: string description?: string - /** The server's URL. Its id derives from it, so a changed URL replaces the server. */ + /** + * The server's URL. Its id derives from it, so a new host or path replaces the server; a new + * query string updates it in place. + */ url: string transport?: (typeof MCP_TRANSPORTS)[number] headers?: Record @@ -106,7 +110,6 @@ export interface McpServerDecl { } const CALLEE = 'defineMcpServer' -const STORED_CALL = 'stored' /** A whole value that is one env reference: `{{NAME}}`. */ const WHOLE_ENV_REFERENCE = /^\{\{([A-Za-z_][A-Za-z0-9_]*)\}\}$/ /** An HTTP header name (RFC 9110 token). */ @@ -198,7 +201,7 @@ function readHeaderValue( report: Parameters['read']>[3] ): McpHeaderDecl | undefined { if (isDeclarationEnvRef(raw)) return `{{${raw.$env}}}` - if (isDeclarationCall(raw) && raw.$call === STORED_CALL && raw.args.length === 0) { + if (isStoredCall(raw)) { return { stored: null } } if (typeof raw !== 'string') { @@ -355,7 +358,7 @@ function parseMcpServer( /** Reads and prints `mcp/.ts`. */ export const mcpCodec: KindCodec = { - group: (paths) => groupByFile(KIND_DIRS['mcp-server'], [DECLARATION_EXTENSION], paths), + group: (paths) => groupByFile(KIND_DIRS['mcp-server'], DECLARATION_EXTENSION, paths), parse: (key, text) => parseMcpServer(key, text), print: (key, decl) => ({ text: { [mcpDeclarationPath(key)]: printDeclaration(CALLEE, printFields(MCP_FIELDS, decl)) }, diff --git a/packages/workspace-code/src/kinds/skills.ts b/packages/workspace-code/src/kinds/skills.ts index e108328cfa0..adb7c291bf8 100644 --- a/packages/workspace-code/src/kinds/skills.ts +++ b/packages/workspace-code/src/kinds/skills.ts @@ -230,7 +230,7 @@ function readQuoted(raw: string): string | null { /** Reads and prints `skills/.md`. */ export const skillCodec: KindCodec = { - group: (paths) => groupByFile(KIND_DIRS.skill, [EXTENSION], paths), + group: (paths) => groupByFile(KIND_DIRS.skill, EXTENSION, paths), parse: (key, text) => parseSkill(key, text), print: (key, decl) => ({ text: { diff --git a/packages/workspace-code/src/kinds/table.ts b/packages/workspace-code/src/kinds/table.ts index 5dfdf8bbcf9..d08cdfe3203 100644 --- a/packages/workspace-code/src/kinds/table.ts +++ b/packages/workspace-code/src/kinds/table.ts @@ -235,7 +235,7 @@ const METADATA_READERS: Record = { if ( !Array.isArray(raw) || raw.length === 0 || - !raw.every((item) => typeof item === 'string' && item.length > 0) + !raw.every((item): item is string => typeof item === 'string' && item.length > 0) ) { report( 'E_TABLE_OPTIONS', @@ -244,7 +244,7 @@ const METADATA_READERS: Record = { ) return } - const names = raw as string[] + const names = raw if (names.length > catalog.maxOptions) { report( 'E_TABLE_OPTIONS', @@ -557,7 +557,10 @@ const ABSENT: Record = { */ export const tableLayout: KindLayout = { group: (paths) => - groupByFile(KIND_DIRS.table, [DECLARATION_EXTENSION, TABLE_ROWS_EXTENSION], paths), + groupByFile(KIND_DIRS.table, DECLARATION_EXTENSION, paths, { + extension: TABLE_ROWS_EXTENSION, + holds: 'its rows', + }), budgetOf: (path) => (path.endsWith(TABLE_ROWS_EXTENSION) ? 'rows' : 'declaration'), } diff --git a/packages/workspace-code/src/kinds/tools.ts b/packages/workspace-code/src/kinds/tools.ts index 2d3b12c43d2..2f491d66a53 100644 --- a/packages/workspace-code/src/kinds/tools.ts +++ b/packages/workspace-code/src/kinds/tools.ts @@ -39,7 +39,13 @@ import { } from '../declaration/field-table' import { fieldPointer, fieldReporter, readObject } from '../declaration/fields' import { call, printDeclaration } from '../declaration/print' -import { isDeclarationCall, readDeclaration, unstorableCharacter } from '../declaration/read' +import { + isDeclarationCall, + isStoredCall, + readDeclaration, + STORED_CALL, + unstorableCharacter, +} from '../declaration/read' import { diagnostic, resourceOf, @@ -88,7 +94,6 @@ export function toolLiteralSecret(printedStored: boolean): { message: string; hi const CALLEE = 'defineTool' const CODE_FILE_CALL = 'codeFile' -const STORED_CALL = 'stored' /** The field the codec reads, prints and fingerprints itself: it may name the tool's code file. */ const CODE_FIELD = 'code' satisfies keyof ToolDecl const CODE_EXTENSION = '.js' @@ -255,11 +260,7 @@ function parseTool( rawCode.args[0] === expected ) { code = readCodeFile(key, text, diagnostics) - } else if ( - isDeclarationCall(rawCode) && - rawCode.$call === STORED_CALL && - rawCode.args.length === 0 - ) { + } else if (isStoredCall(rawCode)) { code = { stored: null } if (text[codePath(key)] !== undefined) { report( @@ -295,7 +296,10 @@ function parseTool( /** Reads and prints `tools/.ts` and `tools/.js`. */ export const toolCodec: KindCodec = { group: (paths) => - groupByFile(KIND_DIRS['custom-tool'], [DECLARATION_EXTENSION, CODE_EXTENSION], paths), + groupByFile(KIND_DIRS['custom-tool'], DECLARATION_EXTENSION, paths, { + extension: CODE_EXTENSION, + holds: 'its code', + }), parse: (key, text) => parseTool(key, text), print(key, decl) { const code = decl.code diff --git a/packages/workspace-code/src/layout.ts b/packages/workspace-code/src/layout.ts index 36650b00278..cf1c7bbd376 100644 --- a/packages/workspace-code/src/layout.ts +++ b/packages/workspace-code/src/layout.ts @@ -23,6 +23,10 @@ const RESOURCE_KEY_SOURCE = '[a-z][a-z0-9_-]{0,63}' const RESOURCE_KEY_PATTERN = new RegExp(`^${RESOURCE_KEY_SOURCE}$`) +/** What a resource key may hold, for the hint of a key {@link isResourceKey} refuses. */ +export const RESOURCE_KEY_HINT = + 'A key is lowercase letters, digits, `-` and `_`, starting with a letter, at most 64 characters.' + /** Whether `value` is a resource key: lowercase, starting with a letter, at most 64 characters. */ export function isResourceKey(value: string): boolean { return RESOURCE_KEY_PATTERN.test(value) diff --git a/packages/workspace-code/src/limits.ts b/packages/workspace-code/src/limits.ts index c788d84709d..c15fd771fad 100644 --- a/packages/workspace-code/src/limits.ts +++ b/packages/workspace-code/src/limits.ts @@ -41,10 +41,7 @@ export const WORKSPACE_SOURCE_LIMITS = { maxWorkflows: 100, /** Planned changes one apply makes, no-ops excluded. */ maxChanges: 1_000, - /** - * Rows one table's `tables/.rows.jsonl` holds. Mirrors the most rows one replace writes - * (`MAX_REPLACE_TABLE_ROWS`, apps/sim/lib/table/application/rows.ts). - */ + /** Rows one table's `tables/.rows.jsonl` holds: the source's own cap per rows file. */ maxTableRows: 10_000, /** UTF-8 bytes of every table rows file together, apart from the declaration budget. */ maxRowsBytes: 16_000_000, diff --git a/packages/workspace-code/src/promote.ts b/packages/workspace-code/src/promote.ts index 987f1def997..40fe74d2147 100644 --- a/packages/workspace-code/src/promote.ts +++ b/packages/workspace-code/src/promote.ts @@ -17,7 +17,7 @@ */ import { isRecordLike } from '@sim/utils/object' import { compareStrings } from '@sim/utils/string' -import { parseSourceBase, sha256Hex, stableStringify } from '@sim/workflow-code' +import { parseSourceBase, type SourceBase, sha256Hex, stableStringify } from '@sim/workflow-code' import { SOURCE_BASE_FILE, SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { type BaseResource, @@ -152,17 +152,14 @@ function withFingerprint(text: string, fingerprint: string): string | null { * is not recorded, and a base naming a workflow the target no longer holds is never compiled. */ function recordedFolderBase(promoted: PromotedWorkflow, workspaceId: string): string { - return `${JSON.stringify( - { - version: 1, - workflowId: promoted.workflowId, - workspaceId, - fingerprint: promoted.fingerprint, - catalogHash: '', - }, - null, - 2 - )}\n` + const base: SourceBase = { + version: 1, + workflowId: promoted.workflowId, + workspaceId, + fingerprint: promoted.fingerprint, + catalogHash: '', + } + return `${JSON.stringify(base, null, 2)}\n` } /** The workflow a folder base's text names, or `null` if unreadable. */ diff --git a/packages/workspace-code/src/specs.ts b/packages/workspace-code/src/specs.ts index a07ce58ff57..c2f0d9f3763 100644 --- a/packages/workspace-code/src/specs.ts +++ b/packages/workspace-code/src/specs.ts @@ -87,7 +87,7 @@ export const WORKSPACE_KIND_SPECS: { readonly [K in WorkspaceKind]: WorkspaceKin resourceKind: 'mcp-server', typeChecked: [`${KIND_DIRS['mcp-server']}/*.ts`], manifestKey: 'mcpServerDeclarations', - guide: `\`${KIND_DIRS['mcp-server']}/.ts\`: \`export default defineMcpServer({ name?, url, headers?, auth?, timeout?, retries?, enabled? })\`. A credential header holds \`env.NAME\` or \`'Bearer {{NAME}}'\`, never a literal secret; \`stored()\` keeps the value the server holds. A changed \`url\` replaces the server. A workflow: \`mcp('').tool('')\`.`, + guide: `\`${KIND_DIRS['mcp-server']}/.ts\`: \`export default defineMcpServer({ name?, url, headers?, auth?, timeout?, retries?, enabled? })\`. A credential header holds \`env.NAME\` or \`'Bearer {{NAME}}'\`, never a literal secret; \`stored()\` keeps the value the server holds. A new host or path in \`url\` replaces the server; a new query string updates it in place. A workflow: \`mcp('').tool('')\`.`, }, table: { noun: 'table', From 1c5c8f20b56a0140f70169a1cbdb9cbc1deb6255 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 11:36:39 -0800 Subject: [PATCH 2/7] =?UTF-8?q?chore(workflow-code):=20server=20lane=20?= =?UTF-8?q?=E2=80=94=20dedupe=20source=20refusals,=20shared=20refusal=20co?= =?UTF-8?q?des,=20human=20subject=20for=20source=20scope,=20drop=20legacy-?= =?UTF-8?q?id=20catalog=20projection,=20doc=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/docs/content/docs/workflows/code/ci.mdx | 2 +- .../content/docs/workflows/code/directory.mdx | 3 +- .../docs/workflows/code/get-started.mdx | 2 +- .../content/docs/workflows/code/limits.mdx | 2 +- apps/docs/openapi-v2-resources.json | 59 ------------------ .../lib/api/contracts/v2/source-catalog.ts | 27 --------- apps/sim/lib/workflows/api/route-policies.ts | 60 +++++++++---------- .../source-pipeline/evaluate/types.ts | 2 +- .../application/source-pipeline/load.ts | 19 +++--- .../sim/lib/workflows/code/catalog/project.ts | 25 -------- .../lib/workflows/executor/execution-state.ts | 8 ++- .../migrations/subblock-migrations.ts | 4 +- .../workspace-source/api/route-policies.ts | 10 ++-- .../src/commands/protocol/source-ui.ts | 19 +++--- .../protocol/workspace-source-blobs.ts | 3 +- packages/sim-cli/src/generated/v2-api.ts | 10 ---- packages/workflow-code/src/catalog/types.ts | 10 ---- .../workflow-code/src/diagnostics/index.ts | 2 + .../workflow-code/src/diagnostics/refusals.ts | 20 +++++++ packages/workflow-code/src/index.ts | 1 - .../workflow-sdk/test/fixtures/catalog.json | 22 +------ 21 files changed, 95 insertions(+), 215 deletions(-) diff --git a/apps/docs/content/docs/workflows/code/ci.mdx b/apps/docs/content/docs/workflows/code/ci.mdx index 4b96da36834..121c7392e0c 100644 --- a/apps/docs/content/docs/workflows/code/ci.mdx +++ b/apps/docs/content/docs/workflows/code/ci.mdx @@ -88,7 +88,7 @@ jobs: fi ``` -`check` runs first because it needs no server and is fast: it compiles every workflow and type-checks the directory after regenerating `.sim/sdk/workspace.d.ts`, so resources the pull request adds are typed. Each finding is also a GitHub annotation at its line. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. That step runs even when the apply failed (`!cancelled()`), because an apply can fail having written part of its plan: exit `15` means it held back changes that use a secret with no value or a credential nothing binds to and applied the rest, and exit `8` means it stopped part-way. Either way the directory records what was written, so committing it keeps the next run from being refused as stale (exit `5`) for resources this run wrote; the job still fails, so set the secret, connect the credential or fix the failure, and push again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. +`check` runs first because it is fast and, after a one-time catalog download, needs no server: it compiles every workflow and type-checks the directory after regenerating `.sim/sdk/workspace.d.ts`, so resources the pull request adds are typed. Each finding is also a GitHub annotation at its line. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. That step runs even when the apply failed (`!cancelled()`), because an apply can fail having written part of its plan: exit `15` means it held back changes that use a secret with no value or a credential nothing binds to and applied the rest, and exit `8` means it stopped part-way. Either way the directory records what was written, so committing it keeps the next run from being refused as stale (exit `5`) for resources this run wrote; the job still fails, so set the secret, connect the credential or fix the failure, and push again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. After merging two branches that each applied, a dry run with no changes means the files match the workspace. Exit `5` means a resource changed since this branch's base: get the workspace into a fresh directory and carry the edit over. Exit `10` means another apply is writing the workspace (or another command is using the directory), so retry; the `concurrency` key keeps two runs of this job from overlapping. Pull requests from forks do not receive repository secrets, so the dry run needs a branch in the same repository. diff --git a/apps/docs/content/docs/workflows/code/directory.mdx b/apps/docs/content/docs/workflows/code/directory.mdx index ae7feabab71..e51c6068209 100644 --- a/apps/docs/content/docs/workflows/code/directory.mdx +++ b/apps/docs/content/docs/workflows/code/directory.mdx @@ -71,7 +71,8 @@ Beside the resources: | Path | What it is | In git | | --- | --- | --- | | `.sim/base.json` | The workspace the directory was read from and the version of every resource | Commit | -| `workflows//.sim/` | Each workflow's `lock.json`, `base.json` and `written.json`, as above | Commit | +| `workflows//.sim/` | Each workflow's `lock.json`, `base.json` and `stored-edges.json`, as above | Commit | +| `.sim/written.json` | A digest of each file as the CLI last wrote it, so `status` and `get` tell your edits from the CLI's | Commit | | `.sim/targets/.json` | What each [promotion](/workflows/code/promote) left in that workspace | Commit | | `.sim/skipped.json` | Documents and files a get left out, with the reason | Optional | | `.sim/AGENTS.md`, `.sim/GUIDE-advanced.md`, `.sim/examples/`, `.sim/sdk/` | The agent guide with deletes, Git and CI, and promotion in depth; examples of every kind; type declarations including `.sim/sdk/workspace.d.ts` | Optional, written again by `get` | diff --git a/apps/docs/content/docs/workflows/code/get-started.mdx b/apps/docs/content/docs/workflows/code/get-started.mdx index 6bbdeedd29d..d8c7ecec2e6 100644 --- a/apps/docs/content/docs/workflows/code/get-started.mdx +++ b/apps/docs/content/docs/workflows/code/get-started.mdx @@ -9,7 +9,7 @@ This walks through one change end to end: read a workflow as a file, edit it, ch - Workflows as code is [enabled](/workflows/code) for your workspace. Where it is not, step 2 answers `403`. - The Sim CLI is installed and you are signed in with a default workspace. See [Your first command](/cli#your-first-command). -- Optional: Bun, for the type-check in step 4. +- Optional: npm (Node.js), which the type check in step 4 uses once to install TypeScript; without it `check` reports `W_TYPES_UNCHECKED` and the compile still runs. ## 1. Find the workflow ID diff --git a/apps/docs/content/docs/workflows/code/limits.mdx b/apps/docs/content/docs/workflows/code/limits.mdx index 6f08e50e88b..d6461c7c863 100644 --- a/apps/docs/content/docs/workflows/code/limits.mdx +++ b/apps/docs/content/docs/workflows/code/limits.mdx @@ -9,7 +9,7 @@ A get leaves out what an apply would refuse, so anything a get writes can be app - **A workflow** over a limit is refused when you read or save it (`E_LIMIT_EXCEEDED`), and the CLI exits `7`. - **An apply of a workspace directory** that would make more changes than the limit, send more edited workflows, or hold more resources of a kind is refused before anything is written, and the CLI exits `7`. -- **A get of a workspace** that holds more resources of a kind than one directory takes exits `7`. +- **A get of a workspace** that holds more resources of a kind than one directory takes leaves that kind out (`E_LIMIT_EXCEEDED`, hint `--only`), writes the rest and exits `0`; the directory does not manage that kind. - **A workspace file or knowledge base document** over its limit, or whose name a directory cannot hold, is left out of the get and listed in `.sim/skipped.json`. An apply never writes or deletes it. {/* workflow-code-docs:limits:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index a62bb01b2a7..c8d676579fa 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -33005,65 +33005,6 @@ "additionalProperties": false, "description": "Edge rules for the block." }, - "legacyIds": { - "description": "Field id renames applied on load.", - "type": "array", - "items": { - "type": "object", - "properties": { - "from": { - "type": "string", - "description": "Legacy field id." - }, - "to": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Current field id, or null when removed." - }, - "whenOperation": { - "description": "Operations the rename applies to.", - "type": "array", - "items": { - "type": "string" - } - }, - "conditional": { - "description": "Applies only to some values.", - "type": "boolean", - "const": true - } - }, - "required": ["from", "to"], - "additionalProperties": false, - "description": "One field id rename." - } - }, - "legacyCanonicalIds": { - "description": "Basic/advanced pair id renames applied on load.", - "type": "array", - "items": { - "type": "object", - "properties": { - "from": { - "type": "string", - "description": "Legacy pair id." - }, - "to": { - "type": "string", - "description": "Current pair id." - } - }, - "required": ["from", "to"], - "additionalProperties": false, - "description": "One pair id rename." - } - }, "paramAliases": { "description": "The name source writes for a param, by param name: oauthCredential → credential.", "type": "object", diff --git a/apps/sim/lib/api/contracts/v2/source-catalog.ts b/apps/sim/lib/api/contracts/v2/source-catalog.ts index 226e57aed92..fa8dca9b9d8 100644 --- a/apps/sim/lib/api/contracts/v2/source-catalog.ts +++ b/apps/sim/lib/api/contracts/v2/source-catalog.ts @@ -376,33 +376,6 @@ const catalogBlockSchema = z .describe('The field lifted into named branches.'), }) .describe('Edge rules for the block.'), - legacyIds: z - .array( - z - .object({ - from: z.string().describe('Legacy field id.'), - to: z.string().nullable().describe('Current field id, or null when removed.'), - whenOperation: z - .array(z.string()) - .optional() - .describe('Operations the rename applies to.'), - conditional: z.literal(true).optional().describe('Applies only to some values.'), - }) - .describe('One field id rename.') - ) - .optional() - .describe('Field id renames applied on load.'), - legacyCanonicalIds: z - .array( - z - .object({ - from: z.string().describe('Legacy pair id.'), - to: z.string().describe('Current pair id.'), - }) - .describe('One pair id rename.') - ) - .optional() - .describe('Basic/advanced pair id renames applied on load.'), paramAliases: z .object({ action: z.record(z.string(), z.string()).optional().describe('Action-surface aliases.'), diff --git a/apps/sim/lib/workflows/api/route-policies.ts b/apps/sim/lib/workflows/api/route-policies.ts index 6ba5bbaf78a..8316ff74ea8 100644 --- a/apps/sim/lib/workflows/api/route-policies.ts +++ b/apps/sim/lib/workflows/api/route-policies.ts @@ -4,7 +4,8 @@ import type { SessionPrincipal, WorkspaceApiKeyPrincipal, } from '@sim/auth/principal' -import { boundAnswerFindings } from '@sim/workflow-code/diagnostics' +import { boundAnswerFindings, SOURCE_REFUSAL_CODES } from '@sim/workflow-code/diagnostics' +import type { NextResponse } from 'next/server' import { v2CancelWorkflowRunDataSchema } from '@/lib/api/contracts/v2/workflows' import { createInternalResourceConcealmentPolicy, @@ -62,6 +63,29 @@ function v2CancelRunErrorResponse(error: unknown) { return v2CaughtOrchestrationError(error) } +/** + * The refusals a source apply and a source create share: no slot answers `429` with + * `Retry-After`, refused source answers `400` (`413` for a size limit) with its line-pinned + * diagnostics, and a name taken in the folder answers `409` with `SOURCE_NAME_TAKEN`. + */ +function renderWorkflowSourceRefusal(error: unknown): NextResponse | undefined { + const busy = renderSourceSlotBusy(error) + if (busy) return busy + if (error instanceof WorkflowSourceRejectedError) { + return v2ErrorForOrchestration(error.code, error.message, { + code: SOURCE_REFUSAL_CODES.rejected, + diagnostics: boundAnswerFindings(error.diagnostics), + }) + } + if (error instanceof WorkflowSourceNameTakenError) { + return v2ErrorForOrchestration(error.code, error.message, { + code: SOURCE_REFUSAL_CODES.nameTaken, + name: error.workflowName, + }) + } + return undefined +} + export const v2WorkflowErrorPolicies = { default: v2OrchestrationErrorPolicy, import: { @@ -101,8 +125,8 @@ export const v2WorkflowErrorPolicies = { concealWorkflowGraphAuthorization: createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workflow not found', render(error) { - const busy = renderSourceSlotBusy(error) - if (busy) return busy + const refusal = renderWorkflowSourceRefusal(error) + if (refusal) return refusal if (error instanceof WorkflowOperationsNotAppliedError) { return v2ErrorForOrchestration(error.code, error.message, { code: 'OPERATIONS_NOT_APPLIED', @@ -110,24 +134,12 @@ export const v2WorkflowErrorPolicies = { droppedInputs: error.droppedInputs, }) } - if (error instanceof WorkflowSourceRejectedError) { - return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_REJECTED', - diagnostics: boundAnswerFindings(error.diagnostics), - }) - } if (error instanceof WorkflowSourceStaleError) { return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_STALE', + code: SOURCE_REFUSAL_CODES.stale, currentFingerprint: error.currentFingerprint, }) } - if (error instanceof WorkflowSourceNameTakenError) { - return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_NAME_TAKEN', - name: error.workflowName, - }) - } return v2CaughtOrchestrationError(error) }, }), @@ -141,21 +153,7 @@ export const v2WorkflowErrorPolicies = { concealWorkspaceSourceCreate: createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workspace not found', render(error) { - const busy = renderSourceSlotBusy(error) - if (busy) return busy - if (error instanceof WorkflowSourceRejectedError) { - return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_REJECTED', - diagnostics: boundAnswerFindings(error.diagnostics), - }) - } - if (error instanceof WorkflowSourceNameTakenError) { - return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_NAME_TAKEN', - name: error.workflowName, - }) - } - return v2CaughtOrchestrationError(error) + return renderWorkflowSourceRefusal(error) ?? v2CaughtOrchestrationError(error) }, }), concealRunAuthorization: createV2ResourceConcealmentPolicy({ diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts index 1471f23dc15..aa332764e90 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts @@ -43,7 +43,7 @@ export interface SourceEvaluationInput { /** Env names the subject's runs resolve, for `env('…')` checks. */ envNames: ReadonlySet /** Attribution for resource keys a submitted reference allocates. */ - createdBy: string | null + createdBy: string files: Record lock: WorkflowLockV1 /** Where and when the source was read, its fingerprint already matched; absent for a create. */ diff --git a/apps/sim/lib/workflows/application/source-pipeline/load.ts b/apps/sim/lib/workflows/application/source-pipeline/load.ts index 7fca7287b2b..1c2684d7d88 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/load.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/load.ts @@ -1,8 +1,4 @@ -import { - type Principal, - resolvePrincipalAttribution, - resolvePrincipalSubjectUserId, -} from '@sim/auth/principal' +import { type Principal, requirePrincipalSubjectUserId } from '@sim/auth/principal' import { db } from '@sim/db' import type { BlockCatalog, @@ -90,7 +86,7 @@ export interface LoadedTarget { storedFingerprint: SourceFingerprint envNames: string[] /** Attribution for resource keys the write allocates. */ - createdBy: string | null + createdBy: string scope: SourceScope } @@ -102,8 +98,8 @@ export function targetIds(target: CommitTarget): { workflowId: string; workspace } /** - * Who and where a write to `target` acts: the human it is attributed to (the workspace's billing - * owner for a workspace key) and the workflow's folder. + * Who and where a write to `target` acts: the human it is attributed to and the workflow's + * folder. */ export function sourceScope(principal: Principal, target: CommitTarget): SourceScope { const context = @@ -114,9 +110,8 @@ export function sourceScope(principal: Principal, target: CommitTarget): SourceS workflowId: context.workflowId, workspaceId: context.workspaceId, workspaceOrganizationId: context.workspaceOrganizationId, - subjectUserId: resolvePrincipalAttribution(principal, { - workspaceBillingOwnerUserId: context.billedAccountUserId, - }).attributedUserId, + // actorless-unsupported: workflows.source.apply, .plan and .create admit only session, personal-key, OAuth or Copilot principals, never an executor or workspace key. + subjectUserId: requirePrincipalSubjectUserId(principal), folderId: target.kind === 'existing' ? target.context.workflow.folderId : target.folderId, } } @@ -134,7 +129,7 @@ export async function loadSourceTarget( options: { loads?: SourceLoads; allocate: boolean } ): Promise { const scope = sourceScope(principal, target) - const createdBy = resolvePrincipalSubjectUserId(principal) ?? null + const createdBy = scope.subjectUserId const loads = options.loads ?? {} const context = target.kind === 'existing' diff --git a/apps/sim/lib/workflows/code/catalog/project.ts b/apps/sim/lib/workflows/code/catalog/project.ts index ab070760398..b45b374cab5 100644 --- a/apps/sim/lib/workflows/code/catalog/project.ts +++ b/apps/sim/lib/workflows/code/catalog/project.ts @@ -2,7 +2,6 @@ import { type CatalogBlock, type CatalogBlockGraph, type CatalogCondition, - type CatalogLegacyId, type CatalogOption, type CatalogOutput, type CatalogSubBlock, @@ -20,10 +19,6 @@ import { UNIFIED_START_OUTPUTS } from '@/lib/workflows/blocks/start-outputs' import { probeThunk, readsOnly } from '@/lib/workflows/code/catalog/probe' import { operationOptions } from '@/lib/workflows/code/catalog/sdk-names' import { deriveValueShape } from '@/lib/workflows/code/catalog/value-kind' -import { - CANONICAL_ID_MIGRATIONS, - SUBBLOCK_ID_MIGRATIONS, -} from '@/lib/workflows/migrations/subblock-migrations' import { TRIGGER_TYPES } from '@/lib/workflows/triggers/types' import type { BlockConfig, SubBlockConfig } from '@/blocks/types' import { @@ -563,20 +558,6 @@ function projectDynamicOutputs(block: BlockConfig): CatalogBlock['dynamicOutputs : { source: 'inputFormat', param: inputFormat.id } } -function projectLegacyIds(type: string): CatalogLegacyId[] | undefined { - const migrations = SUBBLOCK_ID_MIGRATIONS[type] - if (!migrations?.length) return undefined - return migrations.map((migration) => { - const legacy: CatalogLegacyId = { - from: migration.from, - to: migration.to.startsWith('_removed_') ? null : migration.to, - } - if (migration.whenOperation) legacy.whenOperation = [...migration.whenOperation] - if (migration.whenValue) legacy.conditional = true - return legacy - }) -} - /** A block's literal `model` options and static dropdown values, for model-condition probes. */ function conditionChoices(block: BlockConfig): Pick { let models: string[] = [] @@ -652,12 +633,6 @@ export function projectBlock(block: BlockConfig): CatalogBlock { const dynamicOutputs = projectDynamicOutputs(block) if (dynamicOutputs) projected.dynamicOutputs = dynamicOutputs if (block.errorOutputs) projected.errorOutputs = Object.keys(block.errorOutputs) - const legacyIds = projectLegacyIds(block.type) - if (legacyIds) projected.legacyIds = legacyIds - const legacyCanonicalIds = CANONICAL_ID_MIGRATIONS[block.type] - if (legacyCanonicalIds?.length) { - projected.legacyCanonicalIds = legacyCanonicalIds.map(({ from, to }) => ({ from, to })) - } if (block.sourceWorkflowId !== undefined) { projected.custom = { sourceWorkflowId: block.sourceWorkflowId } } diff --git a/apps/sim/lib/workflows/executor/execution-state.ts b/apps/sim/lib/workflows/executor/execution-state.ts index cea3262c0be..1b66b7cbf4d 100644 --- a/apps/sim/lib/workflows/executor/execution-state.ts +++ b/apps/sim/lib/workflows/executor/execution-state.ts @@ -233,7 +233,13 @@ export async function getHumanPauseResumeUrl( return waitsOnPerson ? buildResumeUiUrl(getBaseUrl(), workflowId, executionId) : null } -/** A terminal run's failure message: its own `error`, else {@link forceFailedMessage}. */ +/** + * A terminal run's failure message: its own `error`, else {@link forceFailedMessage}. Unlike + * `runFailureMessage` it skips `completionFailure`: it reads completed and cancelled runs too, and + * a completion that fell back to a cost-only log records why there (`Failed to store trace + * spans: …`, `Run was cancelled`), which is a logging note, not the run's error. A failed run's + * error is already its own `error` or its forced finalization's message. + */ function readFailureMessage(executionData: Record): string | undefined { if (typeof executionData.error === 'string') return executionData.error return forceFailedMessage(executionData) diff --git a/apps/sim/lib/workflows/migrations/subblock-migrations.ts b/apps/sim/lib/workflows/migrations/subblock-migrations.ts index 1830bffaf06..76436a44757 100644 --- a/apps/sim/lib/workflows/migrations/subblock-migrations.ts +++ b/apps/sim/lib/workflows/migrations/subblock-migrations.ts @@ -644,7 +644,7 @@ export function migrateSubblockIds(blocks: Record): { * typed a reference has both — and `resolveCanonicalMode` prefers basic, which * would silently swap which value the run uses. */ -export interface CanonicalIdMigration { +interface CanonicalIdMigration { /** The canonical id a legacy saved state stores the mode under. */ from: string /** The canonical id the block definition declares now. */ @@ -652,7 +652,7 @@ export interface CanonicalIdMigration { } /** Canonical-id renames per block type. */ -export const CANONICAL_ID_MIGRATIONS: Record = { +const CANONICAL_ID_MIGRATIONS: Record = { /** * The tool parameter is `file`, and `check-block-registry.ts` requires the * canonical id to match it once the parameter is `user-only` — which it diff --git a/apps/sim/lib/workspace-source/api/route-policies.ts b/apps/sim/lib/workspace-source/api/route-policies.ts index 2efea163b55..10125471b52 100644 --- a/apps/sim/lib/workspace-source/api/route-policies.ts +++ b/apps/sim/lib/workspace-source/api/route-policies.ts @@ -1,5 +1,5 @@ import { utf8ByteLength } from '@sim/utils/paste' -import { boundAnswerFindings } from '@sim/workflow-code/diagnostics' +import { boundAnswerFindings, SOURCE_REFUSAL_CODES } from '@sim/workflow-code/diagnostics' import { type BlobEntry, budgetOfPath, WORKSPACE_ANSWER_BOUND } from '@sim/workspace-code' import { KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' import { workflowCodec, workflowFolder } from '@sim/workspace-code/kinds/workflow' @@ -29,15 +29,17 @@ export const v2WorkspaceSourceErrorPolicy = createV2ResourceConcealmentPolicy({ if (busy) return busy if (error instanceof WorkspaceSourceRejectedError) { return v2ErrorForOrchestration(error.code, error.message, { - code: error.stale ? 'SOURCE_STALE' : 'SOURCE_REJECTED', + code: error.stale ? SOURCE_REFUSAL_CODES.stale : SOURCE_REFUSAL_CODES.rejected, diagnostics: boundAnswerFindings(error.diagnostics, WORKSPACE_ANSWER_BOUND), }) } if (error instanceof WorkspaceSourceBusyError) { - return v2ErrorForOrchestration(error.code, error.message, { code: 'SOURCE_BUSY' }) + return v2ErrorForOrchestration(error.code, error.message, { code: SOURCE_REFUSAL_CODES.busy }) } if (error instanceof SourceStagingFullError) { - return v2ErrorForOrchestration(error.code, error.message, { code: 'SOURCE_STAGING_FULL' }) + return v2ErrorForOrchestration(error.code, error.message, { + code: SOURCE_REFUSAL_CODES.stagingFull, + }) } return v2CaughtOrchestrationError(error) }, diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index 7aab45a7def..7a0aa5d497f 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -5,7 +5,12 @@ */ import { relative } from 'node:path' import { isRecordLike, toRecord } from '@sim/utils/object' -import { boundFindingText, type RefusalClass } from '@sim/workflow-code/diagnostics' +import { + boundFindingText, + type RefusalClass, + SOURCE_REFUSAL_CODES, + type SourceRefusalCode, +} from '@sim/workflow-code/diagnostics' import { SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { type FlatDiagnostic, refusalClass } from '@sim/workspace-code' import type { Command } from 'commander' @@ -360,10 +365,10 @@ export async function confirm(question: string): Promise { } /** The exit status of each `409` the server tells apart by `details.code`; any other exits 1. */ -const CONFLICT_EXIT_CODES: Readonly> = { - SOURCE_STALE: SOURCE_STALE_EXIT_CODE, - SOURCE_BUSY: SOURCE_BUSY_EXIT_CODE, -} +const CONFLICT_EXIT_CODES: ReadonlyMap = new Map([ + [SOURCE_REFUSAL_CODES.stale, SOURCE_STALE_EXIT_CODE], + [SOURCE_REFUSAL_CODES.busy, SOURCE_BUSY_EXIT_CODE], +]) /** * The exit status of a refused write. A `409` is stale only when the server says so @@ -373,7 +378,7 @@ const CONFLICT_EXIT_CODES: Readonly> = { */ function refusalExitCode(error: SimApiError, detailCode: unknown): number { if (error.status === 409) { - return typeof detailCode === 'string' ? (CONFLICT_EXIT_CODES[detailCode] ?? 1) : 1 + return typeof detailCode === 'string' ? (CONFLICT_EXIT_CODES.get(detailCode) ?? 1) : 1 } return REFUSAL_EXIT_CODES[error.status] ?? error.exitCode } @@ -419,7 +424,7 @@ export function printRefusal( const message = machine ? error.message : error.message.replace(DETAILS_REFERENCE, printed ? ' Each finding is printed above.' : '') - const nameTaken = error.status === 409 && details.code === 'SOURCE_NAME_TAKEN' + const nameTaken = error.status === 409 && details.code === SOURCE_REFUSAL_CODES.nameTaken const hint = nameTaken ? 'Pass --name to create it under another name, or apply to that workflow.' : ifAnswerLost && answerLost(error) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-blobs.ts b/packages/sim-cli/src/commands/protocol/workspace-source-blobs.ts index f985c1c0c3e..a9dea4487a0 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-blobs.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-blobs.ts @@ -13,6 +13,7 @@ import { pipeline } from 'node:stream/promises' import { mapWithConcurrency } from '@sim/utils/concurrency' import { generateShortId } from '@sim/utils/id' import { toRecord } from '@sim/utils/object' +import { SOURCE_REFUSAL_CODES } from '@sim/workflow-code/diagnostics' import { APPLY_ORDER, type BlobEntry, @@ -540,7 +541,7 @@ export async function stageBlobs( */ function stagingTooLarge(error: unknown, batch: readonly BlobEntry[]): unknown { if (!(error instanceof SimApiError) || error.status !== 413) return error - if (toRecord(error.details).code === 'SOURCE_STAGING_FULL') return error + if (toRecord(error.details).code === SOURCE_REFUSAL_CODES.stagingFull) return error const bytes = batch.reduce((sum, blob) => sum + blob.size, 0) const largest = batch.reduce((top, blob) => (blob.size > top.size ? blob : top), batch[0]) return new SimApiError( diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 5260bb25d56..7c64008d196 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -9271,16 +9271,6 @@ export type GetSourceCatalogResponse = { kind: 'condition' | 'router' } } - legacyIds?: Array<{ - from: string - to: string | null - whenOperation?: Array - conditional?: true - }> - legacyCanonicalIds?: Array<{ - from: string - to: string - }> paramAliases?: { action?: Record trigger?: Record diff --git a/packages/workflow-code/src/catalog/types.ts b/packages/workflow-code/src/catalog/types.ts index e103e034d7c..d0da1cd5f0e 100644 --- a/packages/workflow-code/src/catalog/types.ts +++ b/packages/workflow-code/src/catalog/types.ts @@ -212,14 +212,6 @@ interface CatalogBlockLifecycle { sunset?: { status: 'legacy' | 'deprecated'; replacedBy?: string } } -/** A registry `subBlocks` id rename applied by load-time migrations, for CLI hints. */ -export interface CatalogLegacyId { - from: SubBlockId - to: SubBlockId | null - whenOperation?: string[] - conditional?: true -} - /** Graph facts compile needs and the registry spreads over several helpers. */ export interface CatalogBlockGraph { /** False for trigger-category blocks: nothing may connect into them (`E_TARGET_TRIGGER`). */ @@ -296,8 +288,6 @@ export interface CatalogBlock { */ errorOutputs?: string[] graph: CatalogBlockGraph - legacyIds?: CatalogLegacyId[] - legacyCanonicalIds?: Array<{ from: CanonicalParamId; to: CanonicalParamId }> /** * The user-facing name source writes for a param, per surface: param name (a canonical id or a * subBlock id) → alias (`oauthCredential` → `credential`). Frozen in diff --git a/packages/workflow-code/src/diagnostics/index.ts b/packages/workflow-code/src/diagnostics/index.ts index f93b31ccd74..421842ea830 100644 --- a/packages/workflow-code/src/diagnostics/index.ts +++ b/packages/workflow-code/src/diagnostics/index.ts @@ -21,5 +21,7 @@ export { refusalClassifier, refuseEditedFindings, refusesEdited, + SOURCE_REFUSAL_CODES, + type SourceRefusalCode, } from './refusals' export type { DiagnosticSeverity, SeverityOf } from './severity' diff --git a/packages/workflow-code/src/diagnostics/refusals.ts b/packages/workflow-code/src/diagnostics/refusals.ts index 096d81fd9d0..ac1334254bc 100644 --- a/packages/workflow-code/src/diagnostics/refusals.ts +++ b/packages/workflow-code/src/diagnostics/refusals.ts @@ -60,6 +60,26 @@ export function refusalClassifier( /** The class of a workflow source refusal with these error codes (see {@link refusalClassifier}). */ export const refusalClass = refusalClassifier() +/** + * The `details.code` of a refused source write, which a client tells refusals of one status apart + * by: the server sets it and the CLI branches on it. + */ +export const SOURCE_REFUSAL_CODES = { + /** Refused findings, with `details.diagnostics`. */ + rejected: 'SOURCE_REJECTED', + /** A resource changed since the source was read (`409`). */ + stale: 'SOURCE_STALE', + /** Another workspace apply is writing the workspace (`409`). */ + busy: 'SOURCE_BUSY', + /** A workflow name another workflow holds (`409`). */ + nameTaken: 'SOURCE_NAME_TAKEN', + /** The caller's staging area has no room (`413`). */ + stagingFull: 'SOURCE_STAGING_FULL', +} as const + +/** One of {@link SOURCE_REFUSAL_CODES}. */ +export type SourceRefusalCode = (typeof SOURCE_REFUSAL_CODES)[keyof typeof SOURCE_REFUSAL_CODES] + /** The error codes an edited block's warning is refused under. */ export type EditRefusalCode = | 'E_APPLY_UNRESOLVED_REF' diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 26381dfe703..c798e458eb5 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -11,7 +11,6 @@ export type { CatalogBuilder, CatalogCondition, CatalogDynamicOutputs, - CatalogLegacyId, CatalogOption, CatalogOutput, CatalogStructuredKind, diff --git a/packages/workflow-sdk/test/fixtures/catalog.json b/packages/workflow-sdk/test/fixtures/catalog.json index c6508bcec59..aff50d326b5 100644 --- a/packages/workflow-sdk/test/fixtures/catalog.json +++ b/packages/workflow-sdk/test/fixtures/catalog.json @@ -6634,13 +6634,7 @@ "dynamicOutputs": { "source": "responseFormat", "param": "responseFormat" - }, - "legacyIds": [ - { - "from": "previousInteractionId", - "to": null - } - ] + } }, "api": { "type": "api", @@ -10885,13 +10879,7 @@ "trigger_sync": { "names": [] } - }, - "legacyIds": [ - { - "from": "knowledgeBaseId", - "to": "knowledgeBaseSelector" - } - ] + } }, "loop": { "type": "loop", @@ -31542,12 +31530,6 @@ "slack_oauth" ] }, - "legacyIds": [ - { - "from": "channelMaxPages", - "to": null - } - ], "paramAliases": { "action": { "oauthCredential": "credential" From f7110cbc5f8ea9a651f9e27c8c0e13540660b2f0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 11:42:20 -0800 Subject: [PATCH 3/7] chore(workflow-code): cli lock, workspace binding and exit-code help from one table - workflow check and status hold the command lock (read-only), so they never read a directory an apply or get is rewriting; check help names exit 10 - recordedWorkspace binds check, create and params to the workspace a directory records - workspace check: no login keeps its AUTH_REQUIRED refusal (exit 13); drop requireCachedCatalog - typeCheckWorkspace shared by the workspace check and a workflow folder check - status commands declare no apply operation - every source command's exit-code help built from the one table, status included - drop renamedVariables; reword apply's workflowId argument, name SOURCE_WORKFLOW_MISMATCH - workspace get never exits 7; INTERRUPTED_EXIT_CODE defined once --- apps/docs/content/docs/cli/reference.mdx | 24 +-- apps/docs/content/docs/cli/workflows.mdx | 12 +- apps/docs/content/docs/cli/workspaces.mdx | 12 +- .../src/commands/protocol/source-check.ts | 43 +++-- .../commands/protocol/source-dir/dir-kind.ts | 14 ++ .../src/commands/protocol/source-dir/index.ts | 1 + .../protocol/source-exit-codes.test.ts | 3 +- .../commands/protocol/source-exit-codes.ts | 84 ++++++--- .../src/commands/protocol/source-status.ts | 19 +- .../protocol/workflow-source-apply.test.ts | 21 ++- .../protocol/workflow-source-apply.ts | 42 ++--- .../protocol/workflow-source-check.test.ts | 22 ++- .../protocol/workflow-source-check.ts | 128 ++++++------- .../protocol/workflow-source-params.test.ts | 14 ++ .../protocol/workflow-source-params.ts | 19 +- .../protocol/workflow-source-status.test.ts | 17 +- .../protocol/workflow-source-status.ts | 171 ++++++++++-------- .../protocol/workspace-operation-wait.ts | 4 +- .../protocol/workspace-source-apply.ts | 7 +- .../protocol/workspace-source-check.test.ts | 15 -- .../protocol/workspace-source-check.ts | 31 +--- .../protocol/workspace-source-status.ts | 11 +- packages/sim-cli/src/commands/secrets.ts | 5 +- packages/sim-cli/src/exit-codes.ts | 6 + packages/sim-cli/src/terminal/line-input.ts | 4 +- packages/sim-cli/src/test/context-mock.ts | 2 +- 26 files changed, 409 insertions(+), 322 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 76410565750..e79c9e0d427 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8649,7 +8649,7 @@ sim workflows source apply [workflowId] [options] | Argument | Required | Description | | --- | --- | --- | -| `workflowId` | No | Workflow whose draft the source replaces (default: the workflowId in .sim/base.json) | +| `workflowId` | No | Refuse unless .sim/base.json names this workflow (default: the workflowId there) | @@ -8669,7 +8669,7 @@ sim workflows source apply [workflowId] [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint) or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [getSourceResources](/api-reference/workflows/getSourceResources). @@ -8698,7 +8698,7 @@ sim workflows source create [options] -Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). @@ -8730,6 +8730,8 @@ Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its fra These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. + ### sim workflows source status Show what changed locally and on the server since the directory was read @@ -8753,9 +8755,9 @@ sim workflows source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. -API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). +API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). ### sim workflows source diff @@ -10051,7 +10053,7 @@ sim workspaces source get [options] A directory that already holds a .sim/base.json is refreshed from the workspace it was read from, whatever the profile's default workspace. -Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 7 the workspace has more resources of a kind than one directory holds; 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [downloadFile](/api-reference/files/downloadFile), [downloadKnowledgeDocument](/api-reference/knowledge-bases/downloadKnowledgeDocument). @@ -10081,7 +10083,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing. Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). @@ -10109,7 +10111,7 @@ sim workspaces source check [options] Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. -Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials). With --output json, stdout is one document that also lists every finding under diagnostics. +Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials; 13 when there is no login to download it with). With --output json, stdout is one document that also lists every finding under diagnostics. These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. @@ -10141,11 +10143,9 @@ sim workspaces source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). - -Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. -API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource), [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). +API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource). ### sim workspaces source diff diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 45d9a1c9ca4..719ad5b8881 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1413,9 +1413,9 @@ sim workflows source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. -API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). +API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). ### Create a workflow from a workflow source directory @@ -1440,7 +1440,7 @@ sim workflows source create [options] -Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). @@ -1456,7 +1456,7 @@ sim workflows source apply [workflowId] [options] | Argument | Required | Description | | --- | --- | --- | -| `workflowId` | No | Workflow whose draft the source replaces (default: the workflowId in .sim/base.json) | +| `workflowId` | No | Refuse unless .sim/base.json names this workflow (default: the workflowId there) | @@ -1476,7 +1476,7 @@ sim workflows source apply [workflowId] [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint) or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [getSourceResources](/api-reference/workflows/getSourceResources). @@ -1524,6 +1524,8 @@ Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its fra These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. + ### Show the content of the changes in a workflow source directory ```bash diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 785bf582b8b..d23130cf101 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -708,7 +708,7 @@ sim workspaces source get [options] A directory that already holds a .sim/base.json is refreshed from the workspace it was read from, whatever the profile's default workspace. -Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 7 the workspace has more resources of a kind than one directory holds; 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [downloadFile](/api-reference/files/downloadFile), [downloadKnowledgeDocument](/api-reference/knowledge-bases/downloadKnowledgeDocument). @@ -734,11 +734,9 @@ sim workspaces source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. -Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. - -API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource), [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). +API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource). ### Apply a workspace source directory @@ -764,7 +762,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing. Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). @@ -790,7 +788,7 @@ sim workspaces source check [options] Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. -Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials). With --output json, stdout is one document that also lists every finding under diagnostics. +Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials; 13 when there is no login to download it with). With --output json, stdout is one document that also lists every finding under diagnostics. These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 951e27fef13..b23b612214f 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -49,13 +49,13 @@ import { } from './source-dir' import { STRICT_FINDINGS } from './source-strict' import { - cachedCatalog, cachedSourceCatalog, type LocalDeclarations, refreshTsconfigs, + refreshWorkspaceTypes, workspaceTypesText, } from './source-tree' -import type { TypeCheck } from './source-types' +import { type TypeCheck, typeCheck } from './source-types' import { type Diagnostic, findingsOutput } from './source-ui' import { blockDigest, readStoredBlockDigests, readStoredEdges } from './stored-edges' import { lockRecoveryHint, readSourceFiles } from './workflow-dir' @@ -177,7 +177,7 @@ function workflowEntry(key: string): string { * Points the workspace directory's tsconfig files at the blocks its workflows now use, keeping the * blocks they include. */ -export async function refreshWorkspaceTsconfigs(root: string, workspaceId: string): Promise { +async function refreshWorkspaceTsconfigs(root: string, workspaceId: string): Promise { const keys = await workspaceWorkflowKeys(root) const sources = await Promise.all(keys.map((key) => readSourceText(root, workflowEntry(key)))) await refreshTsconfigs( @@ -502,6 +502,10 @@ async function compileWorkflowDir( } } +/** What {@link readCheckDeclarations} reads: the declarations and the compiled workflows' facts. */ +type CheckDeclarations = WorkspaceDeclarations & + Awaited> + /** * The workspace directory `root`'s declarations, with what a child workflow call is checked * against from compiling each of its workflows: the inputs of each workflow that compiles @@ -512,7 +516,7 @@ async function compileWorkflowDir( export async function readCheckDeclarations( root: string, catalog: BlockCatalog -): Promise>> { +): Promise { const [declared, workflows] = await Promise.all([ readWorkspaceDeclarations(root), compileWorkspaceWorkflows(root, catalog), @@ -535,7 +539,7 @@ async function compileWorkspaceWorkflows(root: string, catalog: BlockCatalog) { /** * The workflows of `local` typed with the inputs each declares (`inputs`), for `workspace.d.ts`. */ -export function withWorkflowInputs( +function withWorkflowInputs( local: LocalDeclarations, inputs: ReadonlyMap ): LocalDeclarations { @@ -548,6 +552,28 @@ export function withWorkflowInputs( return { ...local, workflows } } +/** + * Type-checks the workspace directory `root` as a check leaves it: regenerates `workspace.d.ts` + * from `declarations` and points its tsconfig files at the blocks its workflows use, then runs + * {@link typeCheck} against them (`scope` keeps one workflow folder's errors). + */ +export async function typeCheckWorkspace( + root: string, + workspaceId: string, + declarations: CheckDeclarations, + options: { enabled: boolean; compiled: readonly Diagnostic[]; scope?: string } +): Promise { + await refreshWorkspaceTypes( + root, + withWorkflowInputs(declarations.local, declarations.workflowInputs) + ) + await refreshWorkspaceTsconfigs(root, workspaceId) + return typeCheck(root, { + ...options, + writtenTypes: (written) => writtenWorkspaceTypes(root, declarations.workflowInputs, written), + }) +} + /** * `workspace.d.ts` as the last get or apply (`written`) left the workspace directory `root`: the * kept manifest, what the files that write recorded declare, and the `workflowInputs` of each @@ -555,7 +581,7 @@ export function withWorkflowInputs( * (none without a kept manifest), so an error its edit causes in another workflow is not taken * for one that workflow's printed source already had. */ -export async function writtenWorkspaceTypes( +async function writtenWorkspaceTypes( root: string, workflowInputs: ReadonlyMap, written: Written @@ -846,8 +872,3 @@ export function cachedOrRefuse( { code: 'CATALOG_NOT_CACHED' } ) } - -/** The cached catalog of `workspaceId`, or a refusal naming `get`, the command that caches one. */ -export function requireCachedCatalog(workspaceId: string, get: string): BlockCatalog { - return cachedOrRefuse(cachedCatalog(workspaceId), workspaceId, get) -} 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 edcfbaeed0a..dbde47468cf 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 @@ -98,6 +98,20 @@ export async function readStarterWorkspace(dir: string): Promise return typeof workspaceId === 'string' ? workspaceId : null } +/** + * The workspace `dir` records it belongs to: the one its `.sim/base.json` was read from, else the + * workspace directory it is a workflow folder of, else the one its starter's types were written + * for (`null` when none). A starter yields to a `--workspace` flag (`flagged`), which chooses + * another; a base or workspace folder does not ({@link directoryWorkspace} refuses that flag). + */ +export async function recordedWorkspace(dir: string, flagged: boolean): Promise { + const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)) + if (typeof base.workspaceId === 'string') return base.workspaceId + const folder = await workspaceFolderOf(dir) + if (folder) return folder.workspaceId + return flagged ? null : readStarterWorkspace(dir) +} + /** * A `workflows/` folder of a workspace directory: `root` holds a workspace `.sim/base.json`. * The workspace's `.sim/written.json` and base are the folder's records too, so a single-workflow diff --git a/packages/sim-cli/src/commands/protocol/source-dir/index.ts b/packages/sim-cli/src/commands/protocol/source-dir/index.ts index 21569e286f8..8a3926f0902 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/index.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/index.ts @@ -17,6 +17,7 @@ export { assertSourceDirKind, directoryWorkspace, readStarterWorkspace, + recordedWorkspace, workspaceFolderOf, } from './dir-kind' export { 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 890c9533bc3..1c2bc58f2e2 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 @@ -6,7 +6,7 @@ import { WORKSPACE_TREE } from './workspace-source-dir' /** * Every code a source command can exit with: each `*_EXIT_CODE` the CLI defines except the - * run-wait timeout (4), which no source command returns, plus 0, 1 and Ctrl-C's 130. + * run-wait timeout (4), which no source command returns, plus 0 and 1. */ const SOURCE_EXIT_CODES = [ 0, @@ -14,7 +14,6 @@ const SOURCE_EXIT_CODES = [ ...Object.entries(exitCodes) .filter(([name]) => name.endsWith('_EXIT_CODE') && name !== 'STILL_RUNNING_EXIT_CODE') .map(([, code]) => code as number), - 130, ].sort((a, b) => a - b) describe('the exit-code tables an agent or a reader relies on', () => { diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index 70bc16a50bf..758218316f0 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -1,6 +1,7 @@ import { DEFERRED_INTERRUPT_BOUND_MS } from '#sim-cli/terminal/interrupts' import { AUTH_REQUIRED_EXIT_CODE, + INTERRUPTED_EXIT_CODE, RATE_LIMITED_EXIT_CODE, SOURCE_BUSY_EXIT_CODE, SOURCE_DRIFT_EXIT_CODE, @@ -13,9 +14,6 @@ import { SOURCE_TOO_LARGE_EXIT_CODE, } from '../../exit-codes' -/** The status a shell reports for a command Ctrl-C ended (128 + SIGINT). */ -const INTERRUPTED_EXIT_CODE = 130 - /** How long an interrupted write waits for its answer before it stops without it. */ const DEFERRED_SECONDS = DEFERRED_INTERRUPT_BOUND_MS / 1000 @@ -27,8 +25,10 @@ export type SourceHelpCommand = | 'workflows source apply' | 'workflows source create' | 'workflows source get' + | 'workflows source status' | 'workspaces source apply' | 'workspaces source get' + | 'workspaces source status' /** One exit code of the source commands: what it means, what to do, and each command's wording. */ interface SourceExitCodeRow { @@ -45,6 +45,34 @@ interface SourceExitCodeRow { const GET_AUTH_REQUIRED = 'not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again' +/** A write's exit 13: nothing was sent. */ +const WRITE_AUTH_REQUIRED = + 'not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again' + +/** A write's exit 130: what a Ctrl-C leaves behind. */ +const WRITE_INTERRUPTED = `interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to ${DEFERRED_SECONDS}s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check` + +/** A status's exit 0, and what it does when the server cannot be reached. */ +const STATUS_CLEAN = `clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or ${SOURCE_LOCAL_CHANGES_EXIT_CODE})` + +/** A status's exit 11. */ +const STATUS_LOCAL_CHANGES = 'local changes only (applying writes them)' + +/** A status's exit 12. */ +const STATUS_DRIFT = + 'the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes' + +/** A status's exit 13: it still shows the local changes. */ +const STATUS_AUTH_REQUIRED = + 'not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`' + +/** A status's exit 7. */ +const STATUS_TOO_LARGE = 'the source is too large for the server to read in one dry run' + +/** The busy clause of a workspace command, which locks --dir. */ +const WORKSPACE_DIR_BUSY = + '(busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished' + /** The busy clause of a single-workflow command, which locks --dir or its workspace directory. */ const WORKFLOW_DIR_BUSY = '(busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished' @@ -64,8 +92,10 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo 'workflows source apply': 'applied (or a clean dry run)', 'workflows source create': 'created (or a clean dry run, or a starter written)', 'workflows source get': 'written', + 'workflows source status': STATUS_CLEAN, 'workspaces source apply': 'applied (or a clean dry run)', 'workspaces source get': 'written', + 'workspaces source status': STATUS_CLEAN, }, }, { @@ -74,15 +104,17 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo next: 'Fix what it printed and run it again', help: { 'workflows source apply': - 'the source has errors (each printed as file:line:column with its frame and hint) or the command failed', + "the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), or the command failed", 'workflows source create': 'the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another)', 'workflows source get': "the command failed, the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force)", + 'workflows source status': 'the command failed', 'workspaces source apply': 'the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed', 'workspaces source get': 'the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written)', + 'workspaces source status': 'the command failed', }, }, { @@ -126,9 +158,9 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo 'workflows source apply': 'the source is too large', 'workflows source create': 'the source is too large', 'workflows source get': 'the workflow is too large to print as source', + 'workflows source status': STATUS_TOO_LARGE, 'workspaces source apply': 'the directory is too large', - 'workspaces source get': - 'the workspace has more resources of a kind than one directory holds', + 'workspaces source status': STATUS_TOO_LARGE, }, }, { @@ -167,23 +199,30 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo 'workflows source apply': WORKFLOW_DIR_BUSY, 'workflows source create': WORKFLOW_DIR_BUSY, 'workflows source get': WORKFLOW_DIR_BUSY, + 'workflows source status': WORKFLOW_DIR_BUSY, 'workspaces source apply': 'another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished', - 'workspaces source get': - '(busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished', + 'workspaces source get': WORKSPACE_DIR_BUSY, + 'workspaces source status': WORKSPACE_DIR_BUSY, }, }, { code: SOURCE_LOCAL_CHANGES_EXIT_CODE, meaning: '`status`: only your edits, which applying writes', next: 'Dry-run, then apply', - help: {}, + help: { + 'workflows source status': STATUS_LOCAL_CHANGES, + 'workspaces source status': STATUS_LOCAL_CHANGES, + }, }, { code: SOURCE_DRIFT_EXIT_CODE, meaning: '`status`: the server changed since the get (drift, or a conflict with your edits)', next: 'Follow the `Next:` line it prints', - help: {}, + help: { + 'workflows source status': STATUS_DRIFT, + 'workspaces source status': STATUS_DRIFT, + }, }, { code: AUTH_REQUIRED_EXIT_CODE, @@ -191,8 +230,13 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo 'Not logged in, the login expired, or the server refused the credential (`AUTH_REQUIRED`); nothing was sent', next: '`sim login`, or fix or unset `SIM_API_KEY` when the key comes from it; then the same command again', help: { + 'workflows source apply': WRITE_AUTH_REQUIRED, + 'workflows source create': WRITE_AUTH_REQUIRED, 'workflows source get': GET_AUTH_REQUIRED, + 'workflows source status': STATUS_AUTH_REQUIRED, + 'workspaces source apply': WRITE_AUTH_REQUIRED, 'workspaces source get': GET_AUTH_REQUIRED, + 'workspaces source status': STATUS_AUTH_REQUIRED, }, }, { @@ -211,19 +255,21 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo }, { code: SOURCE_HELD_EXIT_CODE, - meaning: - '`sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to. Its dry run exits 15 too, so a script can tell beforehand that the apply would write only part', + meaning: `\`sim workspaces source apply\` (or \`--to\`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to. Its dry run exits ${SOURCE_HELD_EXIT_CODE} too, so a script can tell beforehand that the apply would write only part`, next: 'Set the secret (`sim secrets set`) or connect the credential, then apply again', help: { - 'workspaces source apply': - 'written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing', + 'workspaces source apply': `written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits ${SOURCE_HELD_EXIT_CODE} too, having written nothing`, }, }, { code: INTERRUPTED_EXIT_CODE, meaning: `Interrupted (Ctrl-C). An apply or create already sent is finished and saved into the directory first, waiting up to ${DEFERRED_SECONDS}s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written`, next: `\`${prefix} status --dir .\``, - help: {}, + help: { + 'workflows source apply': WRITE_INTERRUPTED, + 'workflows source create': WRITE_INTERRUPTED, + 'workspaces source apply': WRITE_INTERRUPTED, + }, }, ] } @@ -272,11 +318,3 @@ export function sourceExitCodesHelp(command: SourceHelpCommand, lead = 'Exit cod }) return `\n${wrapHelp(`${lead}: ${clauses.join('; ')}.`)}` } - -/** The exit codes every source write (apply, create) shares, appended to its help. */ -export const SOURCE_WRITE_EXIT_CODES_HELP = ` -Exit ${AUTH_REQUIRED_EXIT_CODE}: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. -Run \`sim login\`, or fix or unset SIM_API_KEY when the key comes from it. Exit ${INTERRUPTED_EXIT_CODE}: interrupted -(Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to -${DEFERRED_SECONDS}s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may -have been written and how to check.` diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index 27421281ccf..dd3bf4c49b2 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -25,6 +25,7 @@ import { printLine } from '../../output/io' import { styles } from '../../output/presentation' import { bytes, printDocument, sanitize } from '../../output/render' import { CliUsageError, LocalRefusal } from './local-errors' +import { sourceExitCodesHelp } from './source-exit-codes' import { codeSpan, type Diagnostic, @@ -72,20 +73,16 @@ export interface StatusReport extends SourceStatus { next: NextStep | null } -/** What a status prints and its exit codes, documented in the commands' help. */ -export const STATUS_EXIT_CODES_HELP = ` +/** The `--help` of `command` (a status) after its options: its `--json` output and exit codes. */ +export function statusHelp( + command: 'workflows source status' | 'workspaces source status' +): string { + return ` With --json, \`plan\` is what applying would do as \`apply --dry-run --allow-delete\` reports it (its errors and warnings counted the same, a conflict as an error), and \`next\` the command to run (with --allow-delete only when the plan deletes something). - -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was -read); ${SOURCE_LOCAL_CHANGES_EXIT_CODE} local changes only (applying writes them); ${SOURCE_DRIFT_EXIT_CODE} the server changed since the -directory was read: drift (a resource edited, added or deleted there that the directory leaves -alone) or a conflict (also changed here, so applying it is refused as stale), with or without -local changes; ${SOURCE_TOO_LARGE_EXIT_CODE} the source is too large for the server to read in one dry run; 1 the command -failed; ${AUTH_REQUIRED_EXIT_CODE} not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the -local changes only, then run \`sim login\`. A server that cannot be reached is not a failure: the -status shows the local changes only and says so (exit 0 or ${SOURCE_LOCAL_CHANGES_EXIT_CODE}).` +${sourceExitCodesHelp(command)}` +} /** What `diff` compares, and its exit codes. */ export const DIFF_HELP = ` 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 7a6bdf08467..1d6ada083f9 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 @@ -82,7 +82,12 @@ function outcome(overrides: { dryRun?: boolean; diagnostics?: unknown[]; notes?: modified: [] as Array<{ id: string; key: string; fields: string[] }>, }, edges: { added: 1, removed: 0 }, - variables: { added: [] as string[], removed: [] as string[], modified: [] as string[] }, + variables: { + added: [] as string[], + removed: [] as string[], + renamed: [] as Array<{ from: string; to: string }>, + modified: [] as string[], + }, }, diagnostics: overrides.diagnostics ?? [], files: { 'workflow.ts': `${ENTRY}// stored\n` }, @@ -238,7 +243,12 @@ describe('sim workflows source apply', () => { const answer = outcome({ dryRun: true }) answer.data.diff.blocks.added = [] answer.data.diff.edges = { added: 0, removed: 0 } - answer.data.diff.variables = { added: ['limit'], removed: [], modified: ['region'] } + answer.data.diff.variables = { + added: ['limit'], + removed: [], + renamed: [], + modified: ['region'], + } request.mockResolvedValue(answer) const file = join(dir, 'plan.md') @@ -636,7 +646,12 @@ describe('sim workflows source apply', () => { it('names each changed variable in the result and the preview', async () => { setTerminal(true) const changed = outcome({ dryRun: true }) - changed.data.diff.variables = { added: ['retries'], removed: [], modified: ['threshold'] } + changed.data.diff.variables = { + added: ['retries'], + removed: [], + renamed: [], + modified: ['threshold'], + } request.mockResolvedValue(changed) prompt.question.mockResolvedValue('n') 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 dfa17ccd97d..274a72b1513 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -28,15 +28,16 @@ import { absoluteDirOption, assertSendableCodeFiles, assertSourceDirKind, + directoryWorkspace, readSourceText, - readStarterWorkspace, + recordedWorkspace, SOURCE_AGENTS_FILE, SOURCE_STARTER_FILE, updateSourceDir, withSourceCommandLock, writeBack, } from './source-dir' -import { SOURCE_WRITE_EXIT_CODES_HELP, sourceExitCodesHelp } from './source-exit-codes' +import { sourceExitCodesHelp } from './source-exit-codes' import { cachedCatalogByHash, printTreeResult, refreshWorkflowWorkspaceTypes } from './source-tree' import { type CreatedResource, @@ -101,7 +102,7 @@ function variableChangeList(variables: SourceApplyData['diff']['variables']): st ...(['added', 'removed', 'modified'] as const).flatMap((change) => variables[change].length > 0 ? [`${change} ${variables[change].join(', ')}`] : [] ), - ...renamedVariables(variables).map(({ from, to }) => `renamed ${from} → ${to}`), + ...variables.renamed.map(({ from, to }) => `renamed ${from} → ${to}`), ] } @@ -443,7 +444,7 @@ export function attachWorkflowSourceApply(source: Command): void { command .argument( '[workflowId]', - 'Workflow whose draft the source replaces (default: the workflowId in .sim/base.json)' + 'Refuse unless .sim/base.json names this workflow (default: the workflowId there)' ) .option('--dir ', DIR_DESCRIPTION, '.') .option('--dry-run', 'Check the source and show the outcome without saving or writing files') @@ -458,10 +459,7 @@ export function attachWorkflowSourceApply(source: Command): void { ) .allowExcessArguments(false) .description('Apply a workflow source directory to a workflow draft') - .addHelpText( - 'after', - `${sourceExitCodesHelp('workflows source apply')}${SOURCE_WRITE_EXIT_CODES_HELP}` - ) + .addHelpText('after', sourceExitCodesHelp('workflows source apply')) .action(async (named: string | undefined, options: SourceWriteOptions) => { const mode = writeMode(options) await withSourceCommandLock( @@ -547,10 +545,7 @@ export function attachWorkflowSourceCreate(source: Command): void { ) .allowExcessArguments(false) .description('Create a workflow from a workflow source directory') - .addHelpText( - 'after', - `${sourceExitCodesHelp('workflows source create')}${SOURCE_WRITE_EXIT_CODES_HELP}` - ) + .addHelpText('after', sourceExitCodesHelp('workflows source create')) .action(async (options: SourceWriteOptions & { name?: string; folder?: string }) => { const mode = writeMode(options) await withSourceCommandLock( @@ -582,11 +577,15 @@ export function attachWorkflowSourceCreate(source: Command): void { } assertDeployable(options) const { client, profile } = connectCreate() - // A starter is bound to the workspace its types were written for, as a get directory - // is to the one it was read from; --workspace still chooses another. - const starterWorkspace = - profile.sources.workspaceId === 'flag' ? null : await readStarterWorkspace(options.dir) - const workspaceId = client.requireWorkspace(starterWorkspace ?? undefined) + // 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. + const recorded = directoryWorkspace( + options.dir, + await recordedWorkspace(options.dir, profile.sources.workspaceId === 'flag'), + profile, + (from) => `Run it without --workspace to create it in ${from}.` + ) + const workspaceId = client.requireWorkspace(recorded ?? undefined) const files = await readSourceFiles(options.dir, null) if (!isReadOnly(mode)) { await refreshWorkflowWorkspaceTypes(client, options.dir, workspaceId) @@ -619,19 +618,12 @@ export function attachWorkflowSourceCreate(source: Command): void { }) } -/** The variables a diff renames, none when the answer lists none. */ -function renamedVariables( - variables: SourceApplyData['diff']['variables'] -): ReadonlyArray<{ from: string; to: string }> { - return variables.renamed ?? [] -} - /** Whether a diff adds, removes or changes any workflow variable. */ function variablesChanged(variables: SourceApplyData['diff']['variables']): boolean { return ( variables.added.length > 0 || variables.removed.length > 0 || - renamedVariables(variables).length > 0 || + variables.renamed.length > 0 || variables.modified.length > 0 ) } 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 a2d1c646a8d..d648062b187 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 @@ -1,8 +1,9 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { hostname, tmpdir } from 'node:os' import { join } from 'node:path' import { Command } from 'commander' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SOURCE_BUSY_EXIT_CODE } from '../../exit-codes' import type { SimApiError } from '../../http/client' import { cacheCatalogText } from '../../test/catalog-cache' import { contextMockFns, mockedProfile } from '../../test/context-mock' @@ -480,6 +481,23 @@ describe('sim workflows source check', () => { expect(process.exitCode).toBeUndefined() }) + it('refuses a workflow folder while another command holds the workspace directory, writing no types', async () => { + cacheCatalog() + writeWorkspace() + const folder = writeWorkflowFolder('notify', workspaceWorkflow()) + mkdirSync(join(dir, '.sim/command.lock')) + writeFileSync( + join(dir, '.sim/command.lock/owner.json'), + JSON.stringify({ pid: process.pid, host: hostname() }) + ) + + const error = (await checkIn(folder).catch((caught: unknown) => caught)) as SimApiError + + expect(error.code).toBe('SOURCE_DIR_BUSY') + expect(error.exitCode).toBe(SOURCE_BUSY_EXIT_CODE) + expect(existsSync(join(dir, '.sim/sdk/workspace.d.ts'))).toBe(false) + }) + it('refuses a table or credential key the workspace directory does not declare', async () => { cacheCatalog() writeWorkspace() 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 752cc471f74..e1089ecb1c5 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -1,4 +1,3 @@ -import { toRecord } from '@sim/utils/object' import { SOURCE_BASE_FILE } from '@sim/workflow-code/limits' import { KIND_DIRS } from '@sim/workspace-code' import type { Command } from 'commander' @@ -8,31 +7,24 @@ import { cachedOrRefuse, checkWorkflowDir, readCheckDeclarations, - refreshWorkspaceTsconfigs, reportCheck, type StrictOptions, strictFlags, strictHelp, strictMode, - withWorkflowInputs, - writtenWorkspaceTypes, + typeCheckWorkspace, } from './source-check' import { absoluteDirOption, assertSourceDirKind, directoryWorkspace, - readSourceJson, - readStarterWorkspace, - type Written, + recordedWorkspace, + SOURCE_DIR_BUSY_HELP, + withSourceCommandLock, workspaceFolderOf, } from './source-dir' -import { - cachedCatalog, - cachedSourceCatalog, - refreshTsconfigs, - refreshWorkspaceTypes, -} from './source-tree' -import { TYPES_HELP, type TypesOptions, typeCheck, typesFlag } from './source-types' +import { cachedCatalog, cachedSourceCatalog, refreshTsconfigs } from './source-tree' +import { TYPES_HELP, type TypeCheck, type TypesOptions, typeCheck, typesFlag } from './source-types' import { verboseFlag } from './source-ui' import { requireEntry, WORKFLOW_TREE } from './workflow-dir' @@ -69,7 +61,7 @@ export function attachWorkflowSourceCheck(source: Command): void { ) .allowExcessArguments(false) .description('Compile and type-check a workflow source directory locally, without the server') - .addHelpText('after', CHECK_HELP) + .addHelpText('after', `${CHECK_HELP}\n${SOURCE_DIR_BUSY_HELP}`) .action( async ( options: { dir: string; verbose?: boolean } & StrictOptions & TypesOptions, @@ -77,19 +69,11 @@ export function attachWorkflowSourceCheck(source: Command): void { ) => { const profile = profileFrom(command) await assertSourceDirKind(options.dir, 'workflow') - const base = toRecord(await readSourceJson(options.dir, SOURCE_BASE_FILE)) await requireEntry(options.dir) const workspace = await workspaceFolderOf(options.dir) - const recorded = - typeof base.workspaceId === 'string' - ? base.workspaceId - : (workspace?.workspaceId ?? - (profile.sources.workspaceId === 'flag' - ? null - : await readStarterWorkspace(options.dir))) const workspaceId = directoryWorkspace( options.dir, - recorded, + await recordedWorkspace(options.dir, profile.sources.workspaceId === 'flag'), profile, (from) => `Run it without --workspace to check it against the catalog of ${from}.` ) @@ -98,56 +82,56 @@ export function attachWorkflowSourceCheck(source: Command): void { `${options.dir} has no ${SOURCE_BASE_FILE} and no workspace is selected: pass --workspace .` ) } - const catalog = cachedOrRefuse( - (await cachedSourceCatalog(options.dir)) ?? cachedCatalog(workspaceId), - workspaceId, - workspace - ? `\`sim workspaces source get --dir ${workspace.root}\`` - : `\`sim workflows source get --dir ${options.dir}\` (or \`create\`)` - ) - const declarations = workspace - ? await readCheckDeclarations(workspace.root, catalog) - : undefined - const { findings, entry, unlisted } = await checkWorkflowDir(options.dir, catalog, { - strict: strictMode(options), - ...(declarations ? { declarations } : {}), - }) - if (workspace && declarations) { - await refreshWorkspaceTypes( - workspace.root, - withWorkflowInputs(declarations.local, declarations.workflowInputs) - ) - await refreshWorkspaceTsconfigs(workspace.root, workspaceId) - } else { - await refreshTsconfigs( - options.dir, - workspaceId, - WORKFLOW_TREE, - { sources: [entry] }, - { incremental: true } - ) - } - const types = await typeCheck(workspace ? workspace.root : options.dir, { - enabled: options.types !== false, - compiled: findings, - ...(workspace && declarations - ? { + // A check rewrites the types and tsconfig files, so it holds the lock an apply or get + // takes: it never reads a directory one is halfway through rewriting (exit 10 meanwhile). + await withSourceCommandLock( + options.dir, + async () => { + const catalog = cachedOrRefuse( + (await cachedSourceCatalog(options.dir)) ?? cachedCatalog(workspaceId), + workspaceId, + workspace + ? `\`sim workspaces source get --dir ${workspace.root}\`` + : `\`sim workflows source get --dir ${options.dir}\` (or \`create\`)` + ) + const declarations = workspace + ? await readCheckDeclarations(workspace.root, catalog) + : undefined + const { findings, entry, unlisted } = await checkWorkflowDir(options.dir, catalog, { + strict: strictMode(options), + ...(declarations ? { declarations } : {}), + }) + const enabled = options.types !== false + let types: TypeCheck + if (workspace && declarations) { + types = await typeCheckWorkspace(workspace.root, workspaceId, declarations, { + enabled, + compiled: findings, scope: `${KIND_DIRS.workflow}/${workspace.key}/`, - writtenTypes: (written: Written) => - writtenWorkspaceTypes(workspace.root, declarations.workflowInputs, written), + }) + } else { + await refreshTsconfigs( + options.dir, + workspaceId, + WORKFLOW_TREE, + { sources: [entry] }, + { incremental: true } + ) + types = await typeCheck(options.dir, { enabled, compiled: findings }) + } + reportCheck( + profile.output, + findings, + { catalogHash: catalog.hash }, + { + verbose: options.verbose === true, + unlisted, + dir: options.dir, + types, } - : {}), - }) - reportCheck( - profile.output, - findings, - { catalogHash: catalog.hash }, - { - verbose: options.verbose === true, - unlisted, - dir: options.dir, - types, - } + ) + }, + { readOnly: true } ) } ) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts index 2dcc4a2067d..3b46a1447a4 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts @@ -137,6 +137,20 @@ describe('sim workflows source params', () => { expect(error.message).toContain('Did you mean slack.sendMessage?') }) + it('reads the catalog of the workspace a starter directory was written for', async () => { + cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT) + writeFileSync(join(dir, '.sim/starter.json'), JSON.stringify({ workspaceId: WORKSPACE_ID })) + contextMockFns.mockProfileFrom.mockReturnValue({ + ...mockedProfile(), + workspaceId: null, + output: 'json', + }) + + await params('agent') + + expect(stdoutJson()).toMatchObject({ builder: { key: 'agent' } }) + }) + it('refuses without a cached catalog, making no request', async () => { writeBase() diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts index 8e0f226918f..4a009fb2c18 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts @@ -1,6 +1,4 @@ -import { toRecord } from '@sim/utils/object' import type { BlockCatalog } from '@sim/workflow-code' -import { SOURCE_BASE_FILE } from '@sim/workflow-code/limits' import { compactBuilder, lookupBuilder, @@ -9,10 +7,11 @@ import { } from '@sim/workflow-sdk/codegen' import type { Command } from 'commander' import { printLine } from '#sim-cli/output/io' +import type { ResolvedProfile } from '../../config/index' import { profileFrom } from '../../context' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' -import { readSourceJson, workspaceFolderOf } from './source-dir' +import { recordedWorkspace } from './source-dir' import { cachedCatalog, cachedSourceCatalog } from './source-tree' import { isMachine } from './source-ui' @@ -32,16 +31,16 @@ cached catalog (run a get once).` /** * The catalog the directory was printed with (its `.sim/base.json` hash), else the one cached for - * its workspace, the workspace a workflow folder belongs to, or the profile's. + * the workspace it records ({@link recordedWorkspace}), or the profile's. */ -async function lookupCatalog(dir: string, profileWorkspace: string | null): Promise { +async function lookupCatalog( + dir: string, + profile: Pick +): Promise { const printedWith = await cachedSourceCatalog(dir) if (printedWith) return printedWith - const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)) const workspaceId = - typeof base.workspaceId === 'string' - ? base.workspaceId - : ((await workspaceFolderOf(dir))?.workspaceId ?? profileWorkspace) + (await recordedWorkspace(dir, profile.sources.workspaceId === 'flag')) ?? profile.workspaceId const cached = workspaceId ? cachedCatalog(workspaceId) : null if (cached) return cached throw new SourceDirError( @@ -69,7 +68,7 @@ export function attachWorkflowSourceParams(source: Command): void { .addHelpText('after', PARAMS_HELP) .action(async (query: string, options: { dir: string; full?: boolean }, command: Command) => { const profile = profileFrom(command) - const catalog = await lookupCatalog(options.dir, profile.workspaceId) + const catalog = await lookupCatalog(options.dir, profile) const found = lookupBuilder(catalog, query) const machine = isMachine(profile.output) switch (found.kind) { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts index 38a3d3f81ee..d7eae4d685e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts @@ -1,8 +1,9 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' +import { hostname, tmpdir } from 'node:os' import { basename, dirname, join } from 'node:path' import { Command } from 'commander' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SOURCE_BUSY_EXIT_CODE } from '../../exit-codes' import { REQUEST_CANCELLED, SimApiError } from '../../http/client' import { contextMockFns, contextMockState, mockedProfile } from '../../test/context-mock' import { digest } from './source-dir' @@ -130,6 +131,20 @@ describe('workflows source status', () => { } ) + it('refuses while another command holds the directory, asking the server nothing', async () => { + mkdirSync(join(root, '.sim/command.lock')) + writeFileSync( + join(root, '.sim/command.lock/owner.json'), + JSON.stringify({ pid: process.pid, host: hostname() }) + ) + + const error = (await run(root, 'status').catch((caught: unknown) => caught)) as SimApiError + + expect(error.code).toBe('SOURCE_DIR_BUSY') + expect(error.exitCode).toBe(SOURCE_BUSY_EXIT_CODE) + expect(mockRequest).not.toHaveBeenCalled() + }) + it('is clean, exit 0, with nothing changed on either side', async () => { mockRequest.mockResolvedValue(dryRun()) 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 188d5b2efe6..66729a61675 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts @@ -30,6 +30,7 @@ import { readPreviousLock, readSourceText, type Written, + withSourceCommandLock, } from './source-dir' import { baseUnavailable, @@ -43,9 +44,9 @@ import { printDiffReport, printStatusReport, type ServerCheck, - STATUS_EXIT_CODES_HELP, type StatusReport, statusExitCode, + statusHelp, textDiff, unreachableReason, } from './source-status' @@ -154,7 +155,6 @@ interface StatusOptions { export function attachWorkflowSourceStatus(source: Command): void { const [command, connect] = apiCommand(source, 'status', [ 'planWorkflowSource', - 'applyWorkflowSource', 'getSourceResources', ]) absoluteDirOption(command) @@ -165,89 +165,100 @@ export function attachWorkflowSourceStatus(source: Command): void { .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', STATUS_EXIT_CODES_HELP) + .addHelpText('after', statusHelp('workflows source status')) .action(async (options: StatusOptions, invoked: Command) => { const output = options.json ? 'json' : profileFrom(invoked).output - const local = await readLocalWorkflow(options.dir) - const { workflowId } = local - const locals: LocalResourceChange[] = - local.changed.length > 0 - ? [ - { - kind: 'workflow', - key: workflowId, - change: resourceChange(local.changed), - files: local.changed, - }, - ] - : [] - let server: ServerCheck = options.offline ? 'offline' : 'checked' - let note: string | undefined = options.offline ? 'Skipped with --offline.' : undefined - let data: PlanData | null = null - let serverChanges: ServerResourceChange[] = [] - let login: string | null = null - if (!options.offline) { - const { client, profile } = connect() - const lock = await readLock(options.dir) - const files = await readSourceFiles(options.dir, lock) - try { - const body = { files, lock, base: local.base } - const response = await client.request('planWorkflowSource', { - params: { workflowId }, - query: { allowDelete: true }, - body, - retryRateLimited: true, - }) - data = response.data - await refreshWorkflowWorkspaceTypes(client, options.dir, local.base.workspaceId) - if (data.diagnostics.some((finding) => finding.code === 'E_APPLY_STALE')) { - serverChanges = [{ kind: 'workflow', key: workflowId, server: 'changed' }] + // 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 { workflowId } = local + const locals: LocalResourceChange[] = + local.changed.length > 0 + ? [ + { + kind: 'workflow', + key: workflowId, + change: resourceChange(local.changed), + files: local.changed, + }, + ] + : [] + let server: ServerCheck = options.offline ? 'offline' : 'checked' + let note: string | undefined = options.offline ? 'Skipped with --offline.' : undefined + let data: PlanData | null = null + let serverChanges: ServerResourceChange[] = [] + let login: string | null = null + if (!options.offline) { + const { client, profile } = connect() + const lock = await readLock(options.dir) + const files = await readSourceFiles(options.dir, lock) + try { + const body = { files, lock, base: local.base } + const response = await client.request( + 'planWorkflowSource', + { + params: { workflowId }, + query: { allowDelete: true }, + body, + retryRateLimited: true, + } + ) + data = response.data + await refreshWorkflowWorkspaceTypes(client, options.dir, local.base.workspaceId) + if (data.diagnostics.some((finding) => finding.code === 'E_APPLY_STALE')) { + serverChanges = [{ kind: 'workflow', key: workflowId, server: 'changed' }] + } + } catch (error) { + if (error instanceof SimApiError && error.status === 404) { + serverChanges = [{ kind: 'workflow', key: workflowId, server: 'deleted' }] + note = 'The server has no workflow by this id that this profile can read.' + } else { + const reason = unreachableReason(error) + if (reason === null) throw withSourceExitCode(error) + login = loginCommand(error, profile.authProfile) + server = 'unreachable' + note = `${reason} Showing local changes only.` + } + } } - } catch (error) { - if (error instanceof SimApiError && error.status === 404) { - serverChanges = [{ kind: 'workflow', key: workflowId, server: 'deleted' }] - note = 'The server has no workflow by this id that this profile can read.' - } else { - const reason = unreachableReason(error) - if (reason === null) throw withSourceExitCode(error) - login = loginCommand(error, profile.authProfile) - server = 'unreachable' - note = `${reason} Showing local changes only.` + const status = sourceStatus(locals, serverChanges) + // A plan against a base the server moved past says nothing: applying it is refused as stale. + const plan = data && serverChanges.length === 0 ? planSummary(data) : null + const report: StatusReport & { workflowId: string } = { + workflowId, + dir: options.dir, + server, + ...(note ? { note } : {}), + ...status, + ...(local.unnamed.length > 0 ? { unnamed: local.unnamed } : {}), + plan, + next: nextStep(status, { + prefix: PREFIX, + dir: options.dir, + getArgs: `${workflowId} `, + server, + errors: plan?.errors ?? 0, + deletes: (plan?.blocksRemoved ?? 0) + (plan?.variablesRemoved ?? 0) > 0, + scope: '', + summaryFile: options.summaryFile, + login, + }), } - } - } - const status = sourceStatus(locals, serverChanges) - // A plan against a base the server moved past says nothing: applying it is refused as stale. - const plan = data && serverChanges.length === 0 ? planSummary(data) : null - const report: StatusReport & { workflowId: string } = { - workflowId, - dir: options.dir, - server, - ...(note ? { note } : {}), - ...status, - ...(local.unnamed.length > 0 ? { unnamed: local.unnamed } : {}), - plan, - next: nextStep(status, { - prefix: PREFIX, - dir: options.dir, - getArgs: `${workflowId} `, - server, - errors: plan?.errors ?? 0, - deletes: (plan?.blocksRemoved ?? 0) + (plan?.variablesRemoved ?? 0) > 0, - scope: '', - summaryFile: options.summaryFile, - login, - }), - } - printStatusReport( - output, - `Workflow ${workflowId} in ${options.dir}`, - report, - planLine, - data ? workflowPlanFindings(data) : [], - options.summaryFile + printStatusReport( + output, + `Workflow ${workflowId} in ${options.dir}`, + report, + planLine, + data ? workflowPlanFindings(data) : [], + options.summaryFile + ) + setSoftExitCode(statusExitCode(status.state, login)) + }, + { readOnly: true } ) - setSoftExitCode(statusExitCode(status.state, login)) }) } diff --git a/packages/sim-cli/src/commands/protocol/workspace-operation-wait.ts b/packages/sim-cli/src/commands/protocol/workspace-operation-wait.ts index f6213a530d1..30b00a68e82 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-operation-wait.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-operation-wait.ts @@ -107,7 +107,7 @@ export async function waitWorkspaceOperation( 0, 'OPERATION_WAIT_TIMEOUT', { workspaceId, operationId }, - 4 + STILL_RUNNING_EXIT_CODE ) } try { @@ -134,7 +134,7 @@ export async function waitWorkspaceOperation( 0, 'OPERATION_WAIT_TIMEOUT', { workspaceId, operationId }, - 4 + STILL_RUNNING_EXIT_CODE ) } const failure = 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 34788744ba6..072ee9abac7 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -54,7 +54,7 @@ import { writtenFiles, writtenRecord, } from './source-dir' -import { SOURCE_WRITE_EXIT_CODES_HELP, sourceExitCodesHelp } from './source-exit-codes' +import { sourceExitCodesHelp } from './source-exit-codes' import { destructiveChanges } from './source-status' import { cachedCatalog } from './source-tree' import { @@ -721,10 +721,7 @@ export function attachWorkspaceSourceApply(source: Command): void { ) .allowExcessArguments(false) .description('Apply a workspace source directory') - .addHelpText( - 'after', - `${sourceExitCodesHelp('workspaces source apply')}${SOURCE_WRITE_EXIT_CODES_HELP}` - ) + .addHelpText('after', sourceExitCodesHelp('workspaces source apply')) .action(async (options: ApplyOptions) => { assertTargetOnlyDeletable(options) const mode = writeMode(options) 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 4c217702ea1..cf98b190708 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 @@ -182,21 +182,6 @@ describe('sim workspaces source check', () => { ) }) - it('refuses without a cached catalog or credentials, naming the workspace get that caches one', async () => { - rmSync(join(dir, 'config'), { recursive: true }) - writeFile('workflows/first/workflow.ts', insertWorkflow()) - contextMockFns.mockClientFrom.mockImplementationOnce(() => { - throw new Error('Not signed in') - }) - - const error = await check().catch((caught: unknown) => caught) - - expect(error).toMatchObject({ - code: 'CATALOG_NOT_CACHED', - message: expect.stringContaining('sim workspaces source get'), - }) - }) - it('offline with no cached catalog, refuses naming the get; without a login, keeps exit 13', async () => { rmSync(join(dir, 'config'), { recursive: true }) writeFile('workflows/first/workflow.ts', insertWorkflow()) 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 a82b989f686..59c04333373 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -4,22 +4,20 @@ import { KIND_DIRS, WORKSPACE_ANSWER_BOUND } from '@sim/workspace-code' import { WORKSPACE_BASE_FILE } from '@sim/workspace-code/layout' import type { Command } from 'commander' import { profileFrom } from '../../context' +import { AUTH_REQUIRED_EXIT_CODE } from '../../exit-codes' import { apiCommand, type Connection } from '../../runtime/called-operations' import { CliUsageError, SourceDirError } from './local-errors' import { type CheckFinding, checkWorkflowDir, readCheckDeclarations, - refreshWorkspaceTsconfigs, reportCheck, - requireCachedCatalog, type StrictOptions, strictFlags, strictHelp, strictMode, - withWorkflowInputs, + typeCheckWorkspace, workspaceWorkflowKeys, - writtenWorkspaceTypes, } from './source-check' import { absoluteDirOption, @@ -29,8 +27,8 @@ import { withSourceDirLock, } from './source-dir' import { credentialRefused, unreachableReason } from './source-status' -import { cachedCatalog, loadCatalog, refreshWorkspaceTypes } from './source-tree' -import { TYPES_HELP, type TypesOptions, typeCheck, typesFlag } from './source-types' +import { cachedCatalog, loadCatalog } from './source-tree' +import { TYPES_HELP, type TypesOptions, typesFlag } from './source-types' import { verboseFlag } from './source-ui' import { assertWorkspaceDir } from './workspace-source-dir' @@ -56,23 +54,19 @@ deployments, credential bindings), so run it before applying. A check also regen workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. ${TYPES_HELP} -${strictHelp("no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials)")}` +${strictHelp(`no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials; ${AUTH_REQUIRED_EXIT_CODE} when there is no login to download it with)`)}` /** * The workspace's catalog for a check with none cached (a fresh clone in CI), downloaded and - * cached with the profile's credentials; without credentials, the refusal that names the get. + * cached with the profile's credentials. No login, or a refused credential, is refused as such + * (`AUTH_REQUIRED`, exit 13, naming `sim login`). */ async function fetchedCatalog( connect: () => Connection<'getSourceCatalog'>, workspaceId: string, dir: string ) { - let connection: Connection<'getSourceCatalog'> - try { - connection = connect() - } catch { - return requireCachedCatalog(workspaceId, `\`sim workspaces source get --dir ${dir}\``) - } + const connection = connect() try { return await loadCatalog(connection.client, { workspaceId, blockTypes: [] }) } catch (error) { @@ -170,16 +164,9 @@ export function attachWorkspaceSourceCheck(source: Command): void { column, }) } - await refreshWorkspaceTypes( - options.dir, - withWorkflowInputs(declarations.local, declarations.workflowInputs) - ) - await refreshWorkspaceTsconfigs(options.dir, workspaceId) - const types = await typeCheck(options.dir, { + const types = await typeCheckWorkspace(options.dir, workspaceId, declarations, { enabled: options.types !== false, compiled: findings, - writtenTypes: (written) => - writtenWorkspaceTypes(options.dir, declarations.workflowInputs, written), }) reportCheck( profile.output, 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 c6868cde10f..065f6a325fc 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -62,9 +62,9 @@ import { printDiffReport, printStatusReport, type ServerCheck, - STATUS_EXIT_CODES_HELP, type StatusReport, statusExitCode, + statusHelp, textDiff, unreachableReason, } from './source-status' @@ -160,7 +160,7 @@ function localPaths(local: LocalWorkspace): string[] { * naming another is refused), else the profile's. */ function targetWorkspace( - connection: Connection<'planWorkspaceSource' | 'applyWorkspaceSource' | 'getWorkspaceSource'>, + connection: Connection<'planWorkspaceSource' | 'getWorkspaceSource'>, dir: string, readFrom: string | null ): string { @@ -344,10 +344,7 @@ interface StatusOptions { * the server since: drift, and conflicts where both sides changed. Ends with the next command. */ export function attachWorkspaceSourceStatus(source: Command): void { - const [command, connect] = apiCommand(source, 'status', [ - 'planWorkspaceSource', - 'applyWorkspaceSource', - ]) + const [command, connect] = apiCommand(source, 'status', ['planWorkspaceSource']) absoluteDirOption(command) summaryFileOption(command) command @@ -357,7 +354,7 @@ export function attachWorkspaceSourceStatus(source: Command): void { .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', `${STATUS_EXIT_CODES_HELP}\n${SOURCE_DIR_BUSY_HELP}`) + .addHelpText('after', statusHelp('workspaces source status')) .action(async (options: StatusOptions, invoked: Command) => { const only = parseKinds(options.only) const output = options.json ? 'json' : profileFrom(invoked).output diff --git a/packages/sim-cli/src/commands/secrets.ts b/packages/sim-cli/src/commands/secrets.ts index f68cd6a86b6..3e86ccac395 100644 --- a/packages/sim-cli/src/commands/secrets.ts +++ b/packages/sim-cli/src/commands/secrets.ts @@ -3,6 +3,7 @@ import { exitCli } from '#sim-cli/embed-context' import { printError } from '#sim-cli/output/io' import { styles } from '#sim-cli/output/presentation' import type { CommandSpec } from '../contract/types' +import { INTERRUPTED_EXIT_CODE } from '../exit-codes' import { type SetSecretResponse, V2_OPERATIONS } from '../generated/v2-api' import { SimApiError } from '../http/client' import { describeOperation } from '../runtime/build' @@ -12,8 +13,6 @@ import { renderResult } from '../runtime/result' import { promptSecret, SecretInputCancelledError } from '../terminal/secret-input' const MAX_SECRET_LENGTH = 65_536 -/** Conventional shell exit code for a command the user aborted at a prompt. */ -const CANCELLED_EXIT_CODE = 130 const SECRET_SCOPES = ['workspace', 'personal'] as const const SECRET_RESULT: CommandSpec = { @@ -111,7 +110,7 @@ async function readSecretValue(options: SetSecretOptions): Promise Date: Tue, 24 Nov 2026 11:48:32 -0800 Subject: [PATCH 4/7] chore(workflow-code): the workflow guide's file-shape example names the SDK major from its constant --- packages/sim-cli/src/commands/protocol/workflow-dir.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 51e9d979dcf..3168211b708 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -233,7 +233,7 @@ Editing the \`workflow('…')\` name or description renames or redescribes the w ## File shape \`\`\`ts -// @sim-sdk 1 +// @sim-sdk ${SDK_MAJOR} import { response, trigger, workflow } from '@sim/workflow-sdk' export default workflow('Workflow name', {}, () => { From fd76d2b5bca3d01a211abf6de9d97e3a8c742cba Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 11:57:10 -0800 Subject: [PATCH 5/7] =?UTF-8?q?chore(workflow-code):=20simplify=20round=20?= =?UTF-8?q?11=20=E2=80=94=20the=20reporter=20records=20where=20each=20code?= =?UTF-8?q?=20was=20reported,=20one=20env-name=20pattern,=20one=20createdB?= =?UTF-8?q?y,=20recordedWorkspace=20reads=20the=20flag?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../application/source-pipeline/load.ts | 6 +--- .../application/source-pipeline/plan.ts | 2 +- .../commands/protocol/source-dir/dir-kind.ts | 11 +++--- .../src/commands/protocol/source-ui.ts | 3 +- .../protocol/workflow-source-apply.ts | 2 +- .../protocol/workflow-source-check.ts | 2 +- .../protocol/workflow-source-params.ts | 3 +- .../workflow-code/src/code-files/index.ts | 1 + packages/workflow-code/src/compile/context.ts | 5 --- packages/workflow-code/src/compile/index.ts | 4 +-- packages/workflow-code/src/compile/report.ts | 13 ++++++- packages/workflow-code/src/compile/values.ts | 36 ++++--------------- .../workflow-code/src/diagnostics/index.ts | 1 - .../workflow-code/src/diagnostics/refusals.ts | 3 -- packages/workflow-code/src/index.ts | 1 + .../workspace-code/src/declaration/read.ts | 10 +++--- packages/workspace-code/src/kinds/mcp.ts | 15 +++++--- 17 files changed, 51 insertions(+), 67 deletions(-) diff --git a/apps/sim/lib/workflows/application/source-pipeline/load.ts b/apps/sim/lib/workflows/application/source-pipeline/load.ts index 1c2684d7d88..33f29a2a8e8 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/load.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/load.ts @@ -85,8 +85,6 @@ export interface LoadedTarget { /** The stored draft's fingerprint when loaded; a commit refuses a draft that moved off it. */ storedFingerprint: SourceFingerprint envNames: string[] - /** Attribution for resource keys the write allocates. */ - createdBy: string scope: SourceScope } @@ -129,7 +127,6 @@ export async function loadSourceTarget( options: { loads?: SourceLoads; allocate: boolean } ): Promise { const scope = sourceScope(principal, target) - const createdBy = scope.subjectUserId const loads = options.loads ?? {} const context = target.kind === 'existing' @@ -142,7 +139,7 @@ export async function loadSourceTarget( prefetchStoredResources({ workflowId: scope.workflowId, workspaceId: scope.workspaceId, - createdBy, + createdBy: scope.subjectUserId, allocate: options.allocate, }), (loads.envNames ??= loadEnvNames(scope.workspaceId, scope.subjectUserId)), @@ -170,7 +167,6 @@ export async function loadSourceTarget( storedCanonical.resources ), envNames, - createdBy, scope, } }) diff --git a/apps/sim/lib/workflows/application/source-pipeline/plan.ts b/apps/sim/lib/workflows/application/source-pipeline/plan.ts index 25ab5d03316..a2c5e027911 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/plan.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/plan.ts @@ -272,7 +272,7 @@ export async function planSource( storedSourceMeta: loaded.storedSourceMeta, catalog, envNames: new Set(loaded.envNames), - createdBy: loaded.createdBy, + createdBy: loaded.scope.subjectUserId, files: submission.files, lock: submission.lock, ...(submission.pendingResources ? { pendingResources: submission.pendingResources } : {}), 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 dbde47468cf..5bfbcbed08d 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 @@ -101,15 +101,18 @@ export async function readStarterWorkspace(dir: string): Promise /** * The workspace `dir` records it belongs to: the one its `.sim/base.json` was read from, else the * workspace directory it is a workflow folder of, else the one its starter's types were written - * for (`null` when none). A starter yields to a `--workspace` flag (`flagged`), which chooses - * another; a base or workspace folder does not ({@link directoryWorkspace} refuses that flag). + * for (`null` when none). A starter yields to a `--workspace` flag, which chooses another; a base + * or workspace folder does not ({@link directoryWorkspace} refuses that flag). */ -export async function recordedWorkspace(dir: string, flagged: boolean): Promise { +export async function recordedWorkspace( + dir: string, + profile: Pick +): Promise { const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)) if (typeof base.workspaceId === 'string') return base.workspaceId const folder = await workspaceFolderOf(dir) if (folder) return folder.workspaceId - return flagged ? null : readStarterWorkspace(dir) + return profile.sources.workspaceId === 'flag' ? null : readStarterWorkspace(dir) } /** diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index 7a0aa5d497f..40e7cc9fd03 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -9,7 +9,6 @@ import { boundFindingText, type RefusalClass, SOURCE_REFUSAL_CODES, - type SourceRefusalCode, } from '@sim/workflow-code/diagnostics' import { SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { type FlatDiagnostic, refusalClass } from '@sim/workspace-code' @@ -365,7 +364,7 @@ export async function confirm(question: string): Promise { } /** The exit status of each `409` the server tells apart by `details.code`; any other exits 1. */ -const CONFLICT_EXIT_CODES: ReadonlyMap = new Map([ +const CONFLICT_EXIT_CODES: ReadonlyMap = new Map([ [SOURCE_REFUSAL_CODES.stale, SOURCE_STALE_EXIT_CODE], [SOURCE_REFUSAL_CODES.busy, SOURCE_BUSY_EXIT_CODE], ]) 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 274a72b1513..fa37c9e7176 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -581,7 +581,7 @@ export function attachWorkflowSourceCreate(source: Command): void { // written for (--workspace still chooses another), a workspace folder to its workspace. const recorded = directoryWorkspace( options.dir, - await recordedWorkspace(options.dir, profile.sources.workspaceId === 'flag'), + await recordedWorkspace(options.dir, profile), profile, (from) => `Run it without --workspace to create it in ${from}.` ) 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 e1089ecb1c5..6978f473f83 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -73,7 +73,7 @@ export function attachWorkflowSourceCheck(source: Command): void { const workspace = await workspaceFolderOf(options.dir) const workspaceId = directoryWorkspace( options.dir, - await recordedWorkspace(options.dir, profile.sources.workspaceId === 'flag'), + await recordedWorkspace(options.dir, profile), profile, (from) => `Run it without --workspace to check it against the catalog of ${from}.` ) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts index 4a009fb2c18..d3c4f2d76ce 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts @@ -39,8 +39,7 @@ async function lookupCatalog( ): Promise { const printedWith = await cachedSourceCatalog(dir) if (printedWith) return printedWith - const workspaceId = - (await recordedWorkspace(dir, profile.sources.workspaceId === 'flag')) ?? profile.workspaceId + const workspaceId = (await recordedWorkspace(dir, profile)) ?? profile.workspaceId const cached = workspaceId ? cachedCatalog(workspaceId) : null if (cached) return cached throw new SourceDirError( diff --git a/packages/workflow-code/src/code-files/index.ts b/packages/workflow-code/src/code-files/index.ts index cf532131a2f..a1ff2d0cfba 100644 --- a/packages/workflow-code/src/code-files/index.ts +++ b/packages/workflow-code/src/code-files/index.ts @@ -2,6 +2,7 @@ export { checkCodeFileBijection } from './bijection' export { type CodeFileRef, fromCodeFile } from './from-file' export { createJsContextScanner } from './lexer' export { + ENV_VAR_NAME, formatStoredPath, isIdentifierName, LOOP_PROPERTIES, diff --git a/packages/workflow-code/src/compile/context.ts b/packages/workflow-code/src/compile/context.ts index a8debf6da23..347b13a8e8a 100644 --- a/packages/workflow-code/src/compile/context.ts +++ b/packages/workflow-code/src/compile/context.ts @@ -192,11 +192,6 @@ export interface CompileContext { * `x.errorMessage`), checked once the edges are known (`checkErrorOutputRefs`). */ errorOutputRefs: Array & { output: string }> - /** - * Where each reference that reads nothing was reported (`file:start`), listed or not, so the JSON - * field check leaves it out of `W_JSON_REF_UNTYPED`. - */ - unknownRefAt: Set /** * Branch keys already refused with an error, by block key. Wiring and branch meta that name one * stay quiet instead of adding `E_UNKNOWN_BRANCH` for the same mistake. diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index 9e4f17747c2..5febf8c5759 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -594,7 +594,6 @@ function compileEntry( dynamicOutputRefs: [], unresolvedTags: [], errorOutputRefs: [], - unknownRefAt: new Set(), refusedBranches: new Map(), valueConsts: new Set(), } @@ -774,7 +773,8 @@ function compileEntry( // one finding: whether text there would break the JSON is moot until the path is fixed. An input // the start does not declare is not: a caller may still pass text there. const unknownAt = new Set([ - ...ctx.unknownRefAt, + ...reporter.reportedAt('W_UNKNOWN_OUTPUT_PATH'), + ...reporter.reportedAt('W_UNRESOLVED_REF'), ...ctx.errorOutputRefs .filter(({ target }) => !erroring.has(target.key)) .map(({ at }) => `${at.file}:${at.start}`), diff --git a/packages/workflow-code/src/compile/report.ts b/packages/workflow-code/src/compile/report.ts index a5c992223a5..ff7e1b8ce33 100644 --- a/packages/workflow-code/src/compile/report.ts +++ b/packages/workflow-code/src/compile/report.ts @@ -53,7 +53,7 @@ export interface Range { end: number } -export interface ReportExtras { +interface ReportExtras { /** * A function is called only when the diagnostic is recorded, so a costly did-you-mean is never * computed for a warning past {@link MAX_LISTED}; a withheld warning computes it when its @@ -126,6 +126,8 @@ export class Reporter { private readonly warningsByCode = new Map() /** What each recorded finding says where, so the same finding is listed once. */ private readonly seen = new Set() + /** Where each code was reported (`file:start`), listed or past a cap. */ + private readonly sites = new Map>() addFile(path: string, text: string): void { this.indexes.set(path, new LineIndex(text)) @@ -151,6 +153,11 @@ export class Reporter { } } + /** Where `code` was reported (`file:start`), including the reports a cap left out of the listing. */ + reportedAt(code: CompileDiagnosticCode): ReadonlySet { + return this.sites.get(code) ?? new Set() + } + /** * Records a diagnostic, once: a finding with the same code, message and range as one already * recorded is dropped. The error after the {@link MAX_ERRORS}th is recorded as @@ -164,6 +171,10 @@ export class Reporter { const key = `${code}\u0000${at.file}\u0000${at.start}\u0000${at.end}\u0000${message}` if (this.seen.has(key)) return this.seen.add(key) + const site = `${at.file}:${at.start}` + const sites = this.sites.get(code) + if (sites) sites.add(site) + else this.sites.set(code, new Set([site])) const severity = severityOf(code) if (severity === 'error') { if (this.errorCount === MAX_ERRORS) { diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index c92e41d80f9..32486939295 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -66,7 +66,7 @@ import { unsupported, } from './context' import { didYouMean, HINTS, hintForNode, nodeLabel } from './hints' -import type { Range, ReportExtras } from './report' +import type { Range } from './report' /** Where a value is compiled: the block it belongs to and the scope its identifiers resolve in. */ export interface ValueSite { @@ -300,22 +300,6 @@ function reportNotNormalized(ctx: CompileContext, tag: LiteralTag): void { ) } -/** - * Reports a reference that reads nothing (`W_UNKNOWN_OUTPUT_PATH`, `W_UNRESOLVED_REF`) and records - * where it is, so the JSON field check does not also call it untyped, even when the warning cap - * leaves the finding out of the listing. - */ -function reportUnknownRef( - ctx: CompileContext, - code: 'W_UNKNOWN_OUTPUT_PATH' | 'W_UNRESOLVED_REF', - message: string, - at: Range, - extras: ReportExtras -): void { - ctx.unknownRefAt.add(`${at.file}:${at.start}`) - ctx.reporter.report(code, message, at, extras) -} - /** * Reports each literal `` whose head names no block once the apply's renames are known * (`renamed`, stored key → source key). The apply rewrites a renamed block's stored key to its new @@ -332,8 +316,7 @@ export function checkUnresolvedTags( reportNotNormalized(ctx, tag) continue } - reportUnknownRef( - ctx, + ctx.reporter.report( 'W_UNRESOLVED_REF', `${tag.token} names no block, so it does not resolve at run time.`, tag.at, @@ -824,8 +807,7 @@ function checkOutputPath( ...(containerKind === 'loop' ? LOOP_PROPERTIES : PARALLEL_PROPERTIES), ] if (first.kind === 'name' && !known.includes(first.name)) { - reportUnknownRef( - ctx, + ctx.reporter.report( 'W_UNKNOWN_OUTPUT_PATH', `A ${containerKind} has no output ${first.name}.`, at, @@ -854,8 +836,7 @@ function checkOutputPath( ctx.errorOutputRefs.push({ at, target, blockKey, output: errorOutput }) return } - reportUnknownRef( - ctx, + ctx.reporter.report( 'W_UNKNOWN_OUTPUT_PATH', `${target.name} has no output ${formatStoredPath(segments)}.`, at, @@ -964,8 +945,7 @@ export function checkDynamicOutputRefs( ) continue } - reportUnknownRef( - ctx, + ctx.reporter.report( 'W_UNKNOWN_OUTPUT_PATH', fields.length > 0 ? `${target.name} has no output ${path}: its responseFormat declares ${fields.join(', ')}.` @@ -1014,8 +994,7 @@ export function checkCodeFileRefs( if (head.name === 'variable') { const name = rest[0]?.kind === 'name' ? rest[0].name : null if (name !== null && !ctx.variables.has(name)) { - reportUnknownRef( - ctx, + ctx.reporter.report( 'W_UNRESOLVED_REF', `${written}: no workflow variable is keyed ${name}.`, at, @@ -1046,8 +1025,7 @@ export function checkCodeFileRefs( const byName = ctx.declsByKey.get(normalizeWorkflowBlockName(head.name)) const suggested = byIdent ?? byName const rewritten = (key: BlockKey) => spell([{ kind: 'name', name: key }, ...rest]) - reportUnknownRef( - ctx, + ctx.reporter.report( 'W_UNRESOLVED_REF', `${written} names no block, so it does not resolve at run time.`, at, diff --git a/packages/workflow-code/src/diagnostics/index.ts b/packages/workflow-code/src/diagnostics/index.ts index 421842ea830..f418544a524 100644 --- a/packages/workflow-code/src/diagnostics/index.ts +++ b/packages/workflow-code/src/diagnostics/index.ts @@ -22,6 +22,5 @@ export { refuseEditedFindings, refusesEdited, SOURCE_REFUSAL_CODES, - type SourceRefusalCode, } from './refusals' export type { DiagnosticSeverity, SeverityOf } from './severity' diff --git a/packages/workflow-code/src/diagnostics/refusals.ts b/packages/workflow-code/src/diagnostics/refusals.ts index ac1334254bc..03c45d36005 100644 --- a/packages/workflow-code/src/diagnostics/refusals.ts +++ b/packages/workflow-code/src/diagnostics/refusals.ts @@ -77,9 +77,6 @@ export const SOURCE_REFUSAL_CODES = { stagingFull: 'SOURCE_STAGING_FULL', } as const -/** One of {@link SOURCE_REFUSAL_CODES}. */ -export type SourceRefusalCode = (typeof SOURCE_REFUSAL_CODES)[keyof typeof SOURCE_REFUSAL_CODES] - /** The error codes an edited block's warning is refused under. */ export type EditRefusalCode = | 'E_APPLY_UNRESOLVED_REF' diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index c798e458eb5..2bd77a84f44 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -32,6 +32,7 @@ export { export { checkCodeFileBijection, createJsContextScanner, + ENV_VAR_NAME, formatStoredPath, fromCodeFile, isIdentifierName, diff --git a/packages/workspace-code/src/declaration/read.ts b/packages/workspace-code/src/declaration/read.ts index f7b920e1a00..1284dcb4a1a 100644 --- a/packages/workspace-code/src/declaration/read.ts +++ b/packages/workspace-code/src/declaration/read.ts @@ -23,6 +23,7 @@ import { babelErrorShape, babelMessage, bracketDepthOverflow, + ENV_VAR_NAME, type Json, pointerSegment, type SourceSpan, @@ -65,9 +66,6 @@ export function isDeclarableKey(key: string): boolean { return key !== CALL_KEY && key !== ENV_KEY && key !== '__proto__' } -/** An environment variable name `env.NAME` may spell: an identifier. */ -const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/ - interface ReadDeclarationOptions { /** The function the file default-exports a call of: `defineTable`. */ callee: string @@ -108,7 +106,9 @@ export function isStoredCall(value: unknown): boolean { /** Whether a decoded value is an `env.NAME` reference the reader produced. */ export function isDeclarationEnvRef(value: unknown): value is DeclarationEnvRef { - return isRecordLike(value) && typeof value[ENV_KEY] === 'string' && ENV_NAME.test(value[ENV_KEY]) + return ( + isRecordLike(value) && typeof value[ENV_KEY] === 'string' && ENV_VAR_NAME.test(value[ENV_KEY]) + ) } /** @@ -439,7 +439,7 @@ export function readDeclaration( ) return undefined } - return ENV_NAME.test(node.property.name) + return ENV_VAR_NAME.test(node.property.name) ? { [ENV_KEY]: node.property.name } : unsupported( node.property, diff --git a/packages/workspace-code/src/kinds/mcp.ts b/packages/workspace-code/src/kinds/mcp.ts index 8528543816c..817f213e20b 100644 --- a/packages/workspace-code/src/kinds/mcp.ts +++ b/packages/workspace-code/src/kinds/mcp.ts @@ -23,7 +23,7 @@ * An OAuth client secret is set in the server's settings, never in source. */ import { compareStrings } from '@sim/utils/string' -import { holdsSecret, type Json, withoutAuthScheme } from '@sim/workflow-code' +import { ENV_VAR_NAME, holdsSecret, type Json, withoutAuthScheme } from '@sim/workflow-code' import { asDeclared, booleanField, @@ -110,14 +110,19 @@ export interface McpServerDecl { } const CALLEE = 'defineMcpServer' -/** A whole value that is one env reference: `{{NAME}}`. */ -const WHOLE_ENV_REFERENCE = /^\{\{([A-Za-z_][A-Za-z0-9_]*)\}\}$/ /** An HTTP header name (RFC 9110 token). */ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** A credential-bearing header name, by its words. */ const CREDENTIAL_HEADER = /^(authorization|proxy-authorization|cookie)$|key|token|secret|auth|password|session|signature|credential/i +/** The name of a header value that is one whole env reference (`{{NAME}}`), else null. */ +function wholeEnvName(value: string): string | null { + if (!value.startsWith('{{') || !value.endsWith('}}')) return null + const name = value.slice(2, -2) + return ENV_VAR_NAME.test(name) ? name : null +} + /** `mcp/.ts`. */ export function mcpDeclarationPath(key: string): string { return `${KIND_DIRS['mcp-server']}/${key}${DECLARATION_EXTENSION}` @@ -261,8 +266,8 @@ const headersField: DeclField = { : Object.fromEntries( Object.entries(headers).map(([name, header]) => { if (isStoredHeader(header)) return [name, call(STORED_CALL)] - const env = WHOLE_ENV_REFERENCE.exec(header) - return [name, env ? envRef(env[1]) : header] + const env = wholeEnvName(header) + return [name, env === null ? header : envRef(env)] }) ), canonical: (headers) => From 24daf6bf1e9130e616eed00c85417a92fc7fff1e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 12:00:13 -0800 Subject: [PATCH 6/7] test(workflow-code): the warning-cap test derives its count from FINDING_LIMITS and asserts the cap was hit --- packages/workflow-code/src/compile/checks.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 37c140dfb5f..9f1a7b9dd25 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -4,6 +4,7 @@ */ import { describe, expect, it } from 'vitest' import type { BlockCatalog, CatalogBlock } from '../catalog/types' +import { FINDING_LIMITS } from '../diagnostics/bound' import type { CanonicalWorkflow } from '../model' import { TEST_CATALOG } from './catalog.test-helpers' import type { CompileResult } from './index' @@ -601,7 +602,10 @@ describe('typed references in JSON fields', () => { }) it('keeps a reference to an output the block lacks out of W_JSON_REF_UNTYPED past the warning cap', () => { - const fields = Array.from({ length: 25 }, (_, i) => `k${i}: a.missing${i}`).join(', ') + const fields = Array.from( + { length: FINDING_LIMITS.warningsPerCode + 5 }, + (_, i) => `k${i}: a.missing${i}` + ).join(', ') const result = run( [ START, @@ -611,6 +615,8 @@ describe('typed references in JSON fields', () => { 'a.to(b)', ].join('\n') ) + expect(findings(result, 'W_UNKNOWN_OUTPUT_PATH')).toHaveLength(FINDING_LIMITS.warningsPerCode) + expect(findings(result, 'I_FINDINGS_TRUNCATED')).toHaveLength(1) expect(findings(result, 'W_JSON_REF_UNTYPED')).toEqual([]) }) From 60aa8460d6dfcc3d469a03bee4aa45bf28b56beb Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 12:24:10 -0800 Subject: [PATCH 7/7] fix(workflow-code): status help names exit 9, a 429 that outlasts the retries --- apps/docs/content/docs/cli/reference.mdx | 4 ++-- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- packages/sim-cli/src/commands/protocol/source-exit-codes.ts | 4 ++++ 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index e79c9e0d427..273001782dc 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8755,7 +8755,7 @@ sim workflows source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). @@ -10143,7 +10143,7 @@ sim workspaces source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource). diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 719ad5b8881..406609a9d65 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1413,7 +1413,7 @@ sim workflows source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index d23130cf101..4ee1e4b049a 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -734,7 +734,7 @@ sim workspaces source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource). diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index 758218316f0..4040a106e12 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -184,10 +184,14 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo "rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again", 'workflows source get': "rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again", + 'workflows source status': + "rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again", 'workspaces source apply': "rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again)", 'workspaces source get': "rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest", + 'workspaces source status': + "rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again", }, }, {