diff --git a/.claude/rules/sim-workflow-code.md b/.claude/rules/sim-workflow-code.md index 86f2404658c..d7435063c05 100644 --- a/.claude/rules/sim-workflow-code.md +++ b/.claude/rules/sim-workflow-code.md @@ -157,8 +157,7 @@ satisfy. 2. A codec `packages/workspace-code/src/kinds/.ts` with tests; `KIND_LAYOUTS`, and `BLOB_KIND_CODECS` if it holds blobs (`src/kinds/registry.ts`); its diagnostic codes. 3. An adapter `apps/sim/lib/workspace-source/application/kinds//adapter.ts` calling the - kind's own use cases; `KIND_ADAPTERS` (`application/registry.ts`) and `NOUNS` - (`application/findings.ts`); an integration test. + kind's own use cases; `KIND_ADAPTERS` (`application/registry.ts`); an integration test. 4. If workflows name it by key: `WORKFLOW_RESOURCE_KINDS`, the live loader in `lib/workspaces/resource-keys.ts`, the manifest in `read-source-resources.ts` and `codegen/workspace.ts`, and `PENDABLE_REFERENCES` in @@ -222,5 +221,6 @@ Behaviour is proven by properties over the real registry, not restated unit test - The Code tab and the CLI have HTTP e2e scripts (`apps/sim/scripts/test-workflow-code-ui-e2e.ts`, `test-workflow-source-e2e.ts`, `test-workspace-source-e2e.ts`). - Generated artifacts and their checks: `generate:sdk-names` (`check:sdk-names`, - `check:sdk-names-frozen`), the SDK embedded text (its `*-text.test.ts`), goldens - (`check:workflow-code-golden`). + `check:sdk-names-frozen`), `generate:workflow-sdk-embedded-text` + (`check:workflow-sdk-embedded-text`), `generate:sdk-fixture-catalog` + (`check:sdk-fixture-catalog`), goldens (`check:workflow-code-golden`). diff --git a/.cursor/rules/sim-workflow-code.mdc b/.cursor/rules/sim-workflow-code.mdc index 65c08f7ef36..77d1474b0f1 100644 --- a/.cursor/rules/sim-workflow-code.mdc +++ b/.cursor/rules/sim-workflow-code.mdc @@ -137,8 +137,7 @@ satisfy. 2. A codec `packages/workspace-code/src/kinds/.ts` with tests; `KIND_LAYOUTS`, and `BLOB_KIND_CODECS` if it holds blobs (`src/kinds/registry.ts`); its diagnostic codes. 3. An adapter `apps/sim/lib/workspace-source/application/kinds//adapter.ts` calling the - kind's own use cases; `KIND_ADAPTERS` (`application/registry.ts`) and `NOUNS` - (`application/findings.ts`); an integration test. + kind's own use cases; `KIND_ADAPTERS` (`application/registry.ts`); an integration test. 4. If workflows name it by key: `WORKFLOW_RESOURCE_KINDS`, the live loader in `lib/workspaces/resource-keys.ts`, the manifest in `read-source-resources.ts` and `codegen/workspace.ts`, and `PENDABLE_REFERENCES` in @@ -202,5 +201,6 @@ Behaviour is proven by properties over the real registry, not restated unit test - The Code tab and the CLI have HTTP e2e scripts (`apps/sim/scripts/test-workflow-code-ui-e2e.ts`, `test-workflow-source-e2e.ts`, `test-workspace-source-e2e.ts`). - Generated artifacts and their checks: `generate:sdk-names` (`check:sdk-names`, - `check:sdk-names-frozen`), the SDK embedded text (its `*-text.test.ts`), goldens - (`check:workflow-code-golden`). + `check:sdk-names-frozen`), `generate:workflow-sdk-embedded-text` + (`check:workflow-sdk-embedded-text`), `generate:sdk-fixture-catalog` + (`check:sdk-fixture-catalog`), goldens (`check:workflow-code-golden`). diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx index dfa8e9b675b..81d14deb04d 100644 --- a/apps/docs/content/docs/workflows/code.mdx +++ b/apps/docs/content/docs/workflows/code.mdx @@ -49,7 +49,7 @@ Nothing in the file runs on your machine. Sim reads it statically, checks it aga sim workflows source check --dir ./support-triage ``` - It exits 1 on an error, and on a missing required field, an unknown option or output path, a wrong value kind, an out-of-range value, an unwired condition or router branch or a literal secret in a block you added since the get (`--strict` fails on these in every block, except an unwired branch on a block the get printed, which the stored workflow may hold; `--no-strict` never fails on a warning). It also adds the blocks the workflow now uses to `tsconfig.json`. Your editor type-checks the file against the generated declarations, and `bunx -p typescript@7.0.2 tsc -p ./support-triage` checks it from the command line with the TypeScript release the declarations are built for; `-p ./support-triage/tsconfig.full.json` type-checks against every block. + It exits 1 on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get (`--strict` fails on these in every block, except an unwired branch on a block the get printed, which the stored workflow may hold; `--no-strict` never fails on a warning). It also adds the blocks the workflow now uses to `tsconfig.json`. Your editor type-checks the file against the generated declarations, and `bunx -p typescript@7.0.2 tsc -p ./support-triage` checks it from the command line with the TypeScript release the declarations are built for; `-p ./support-triage/tsconfig.full.json` type-checks against every block. 3. See what changed, and whether someone changed the workflow since your `get`: diff --git a/apps/sim/lib/workspace-source/api/route-policies.ts b/apps/sim/lib/workspace-source/api/route-policies.ts index df2067f817d..2efea163b55 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 { utf8Bytes } from '@sim/workflow-code/limits' 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' @@ -78,7 +78,7 @@ export function workspaceApplyRateCost( const kind = kindOfPath(path) if (kind === 'workflow') workflowPaths.push(path) else if (kind && budgetOfPath(KIND_LAYOUTS[kind], path) !== 'workflow') { - textBytes += utf8Bytes(text) + textBytes += utf8ByteLength(text) } } const { groups } = workflowCodec.group(workflowPaths) diff --git a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts index 435995f014e..20839593681 100644 --- a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts @@ -23,8 +23,7 @@ import { createLogger } from '@sim/logger' import { mapWithConcurrency } from '@sim/utils/concurrency' import { getErrorMessage } from '@sim/utils/errors' -import { isRecordLike } from '@sim/utils/object' -import { didYouMean, type Json, type SourceSpan } from '@sim/workflow-code' +import { didYouMean, type SourceSpan } from '@sim/workflow-code' import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' import { type BaseResource, @@ -75,6 +74,7 @@ import { resolveStoredHeaders, storedFingerprint, } from '@/lib/workspace-source/application/kinds/mcp/stored' +import { changedFields } from '@/lib/workspace-source/application/kinds/named' import { holdsIn, refuseUnreadAdopt, @@ -122,16 +122,6 @@ function serverIdOf(ctx: SourceContext, url: string): string { return generateMcpServerId(ctx.workspace.workspaceId, url) } -/** The top-level declaration fields whose canonical values differ. */ -function changedFields(before: McpServerDecl, after: McpServerDecl): string[] { - const a = mcpCodec.canonical(before) - const b = mcpCodec.canonical(after) - if (!isRecordLike(a) || !isRecordLike(b)) return [] - return Object.keys(b).filter( - (field) => fingerprintOf(b[field] as Json) !== fingerprintOf(a[field] as Json) - ) -} - function baseOf(record: StoredServer): BaseResource { return { id: record.id, fingerprint: storedFingerprint(record.state) } } @@ -243,7 +233,7 @@ async function planServer( } } const record = planned.stored - const changed = changedFields(declOf(record.state), decl) + const changed = changedFields(mcpCodec.canonical(declOf(record.state)), mcpCodec.canonical(decl)) if (planned.action === 'adopt' && !resumed) { const refused = refuseUnreadAdopt(change, record, changed) if (refused) return refused diff --git a/apps/sim/lib/workspace-source/application/kinds/named.ts b/apps/sim/lib/workspace-source/application/kinds/named.ts index 5acca3c1489..302969cbcce 100644 --- a/apps/sim/lib/workspace-source/application/kinds/named.ts +++ b/apps/sim/lib/workspace-source/application/kinds/named.ts @@ -90,7 +90,7 @@ export function planNamedUndeclared( } /** The top-level declaration fields whose canonical values differ. */ -function changedFields(before: Json, after: Json): string[] { +export function changedFields(before: Json, after: Json): string[] { if (!isRecordLike(before) || !isRecordLike(after)) return [] return Object.keys(after).filter( (field) => fingerprintOf(after[field] as Json) !== fingerprintOf(before[field] as Json) diff --git a/apps/sim/lib/workspace-source/application/plan.ts b/apps/sim/lib/workspace-source/application/plan.ts index 7bb241d948a..9a65e58c071 100644 --- a/apps/sim/lib/workspace-source/application/plan.ts +++ b/apps/sim/lib/workspace-source/application/plan.ts @@ -7,7 +7,7 @@ */ import { mapWithConcurrency } from '@sim/utils/concurrency' -import { utf8Bytes } from '@sim/workflow-code/limits' +import { utf8ByteLength } from '@sim/utils/paste' import { APPLY_ORDER, type BlobEntry, @@ -227,7 +227,7 @@ function checkLimits( const bytes: Record = { declaration: 0, workflow: 0, rows: 0 } for (const [path, text] of Object.entries(files)) { const kind = kindOfPath(path) - if (kind) bytes[budgetOfPath(KIND_LAYOUTS[kind], path)] += utf8Bytes(text) + if (kind) bytes[budgetOfPath(KIND_LAYOUTS[kind], path)] += utf8ByteLength(text) } const { maxDeclarationBytes, maxRowsBytes, maxWorkflowBytes } = WORKSPACE_SOURCE_LIMITS if (bytes.rows > maxRowsBytes) { diff --git a/apps/sim/lib/workspace-source/application/read-workspace-source.ts b/apps/sim/lib/workspace-source/application/read-workspace-source.ts index a3c88f69b6b..f4f9117b721 100644 --- a/apps/sim/lib/workspace-source/application/read-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/read-workspace-source.ts @@ -1,5 +1,5 @@ import { chunkArray } from '@sim/utils/helpers' -import { utf8Bytes } from '@sim/workflow-code/limits' +import { utf8ByteLength } from '@sim/utils/paste' import { APPLY_ORDER, budgetOfPath, @@ -76,7 +76,7 @@ function directoryBudget() { spend(kind: WorkspaceKind, read: { text: Record; blobs: ReadBlob[] }) { const bytes: DirectoryBudgets = { declaration: 0, workflow: 0, rows: 0 } for (const [path, text] of Object.entries(read.text)) { - bytes[budgetOfPath(adapterOf(kind).codec, path)] += utf8Bytes(text) + bytes[budgetOfPath(adapterOf(kind).codec, path)] += utf8ByteLength(text) } for (const budget of SOURCE_BUDGETS) { if (spent[budget] + bytes[budget] > limits[budget]) { diff --git a/apps/sim/lib/workspace-source/staging/store.ts b/apps/sim/lib/workspace-source/staging/store.ts index cd4d8adf183..f4de918ebb4 100644 --- a/apps/sim/lib/workspace-source/staging/store.ts +++ b/apps/sim/lib/workspace-source/staging/store.ts @@ -15,6 +15,7 @@ import { db } from '@sim/db' import { workspace, workspaceSourceStagedBlob } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { sha256Hex } from '@sim/security/hash' +import { mapWithConcurrency } from '@sim/utils/concurrency' import { generateId, generateShortId } from '@sim/utils/id' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' import { and, asc, eq, gt, inArray, isNull, lt, lte, notInArray, sql } from 'drizzle-orm' @@ -50,6 +51,9 @@ const SWEEP_BATCH = 500 const STORAGE_CONTEXT = 'workspace' as const +/** Blob uploads one staging request runs at once; the bytes are already in memory. */ +const UPLOAD_CONCURRENCY = 4 + const QUOTA_UNAVAILABLE = 'Could not check the storage quota for staging; retry shortly.' /** A staged blob as an apply reads it. */ @@ -268,7 +272,9 @@ export async function stageBlobs( : null, ]) try { - for (const blob of fresh) { + // A failed upload starts no more, and throws once those running have settled, so every object + // written is in `keys` by the time `finally` removes the ones no row recorded. + await mapWithConcurrency(fresh, UPLOAD_CONCURRENCY, async (blob) => { const key = newStorageKey(target, blob.sha256) await uploadFile({ file: blob.bytes, @@ -280,7 +286,7 @@ export async function stageBlobs( persistMetadata: false, }) keys.set(blob.sha256, key) - } + }) recorded = await db.transaction(async (tx) => { await acquireAdvisoryXactLock( tx, diff --git a/bun.lock b/bun.lock index 52dbfeedb0a..a706ff74361 100644 --- a/bun.lock +++ b/bun.lock @@ -774,6 +774,7 @@ "@sim/utils": "workspace:*", "@sim/workflow-code": "workspace:*", "@sim/workflow-sdk": "workspace:*", + "@sim/workflow-types": "workspace:*", "@sim/workspace-code": "workspace:*", "@types/js-yaml": "4.0.9", "@types/node": "24.19.2", diff --git a/packages/sim-cli/package.json b/packages/sim-cli/package.json index 79417a22522..8193f5aa1b5 100644 --- a/packages/sim-cli/package.json +++ b/packages/sim-cli/package.json @@ -64,6 +64,7 @@ "@sim/utils": "workspace:*", "@sim/workflow-code": "workspace:*", "@sim/workflow-sdk": "workspace:*", + "@sim/workflow-types": "workspace:*", "@sim/workspace-code": "workspace:*", "@types/js-yaml": "4.0.9", "@types/node": "24.19.2", diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 86334d61b5b..b97b96c7765 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -41,6 +41,7 @@ import { setSoftExitCode } from '../../embed-context' import { SourceDirError } from './local-errors' import { printProtocolResult } from './result' import { digest, readFolderWritten, readSourceText } from './source-dir' +import { STRICT_FINDINGS } from './source-strict' import { cachedCatalog, cachedSourceCatalog, @@ -68,21 +69,7 @@ const SERVER_ONLY_CODES: ReadonlySet = new Set(['E_STORED_VALUE_MISSING' * Warnings an apply saves as written although the block they name is broken: a strict check * fails on them (see {@link StrictMode}). */ -const STRICT_CODES: ReadonlySet = new Set([ - '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', -]) +const STRICT_CODES: ReadonlySet = new Set(STRICT_FINDINGS.keys()) /** * {@link STRICT_CODES} warnings the stored workflow exempts, which a check never fails on a block 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 06cf8d8e4c9..c159398d877 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 @@ -24,6 +24,27 @@ const WORKFLOW_SDK_README = readFileSync( 'utf8' ) +const SCRIPTING_DOCS = readFileSync( + join(import.meta.dirname, '../../../../../apps/docs/content/docs/cli/scripting.mdx'), + 'utf8' +) + +/** The codes of each `| Code | |` table in the scripting docs, by its header cell. */ +const DOCS_TABLES = new Map( + SCRIPTING_DOCS.split(/\n\s*\n/).flatMap((block) => { + const header = block.match(/^\| Code \| (.+) \|$/m) + if (!header) return [] + const codes = [...block.matchAll(/^\| `(\d+)` \|/gm)].map((match) => Number(match[1])) + return [[header[1], codes] as const] + }) +) + +function docsTable(heading: string): number[] { + const codes = DOCS_TABLES.get(heading) + if (!codes) throw new Error(`scripting.mdx has no exit-code table headed ${heading}`) + return codes +} + describe('the exit-code tables an agent or a reader relies on', () => { it.each([ ['the workflow directory guide', WORKFLOW_TREE.agents], @@ -35,6 +56,28 @@ describe('the exit-code tables an agent or a reader relies on', () => { }) }) +describe('the exit-code tables of the CLI scripting docs', () => { + it.each([ + ['workflows source apply', '`sim workflows source apply` or `create`'], + ['workflows source create', '`sim workflows source apply` or `create`'], + ['workflows source get', '`sim workflows source get --dir` or `sim workspaces source get`'], + ['workspaces source get', '`sim workflows source get --dir` or `sim workspaces source get`'], + ['workspaces source apply', '`sim workspaces source apply`'], + ] as const)('list every code %s names in its --help', (command, heading) => { + const help = sourceExitCodesHelp(command).replace(/\s+/g, ' ') + const named = [...help.matchAll(/(?:: |; )(\d+) /g)].map((match) => Number(match[1])) + expect(named.length).toBeGreaterThan(0) + expect(docsTable(heading)).toEqual(expect.arrayContaining(named)) + }) + + it('name only codes a source command exits with', () => { + const sourceTables = [...DOCS_TABLES].filter(([heading]) => heading.includes(' source ')) + expect(sourceTables.length).toBeGreaterThanOrEqual(5) + for (const [, codes] of sourceTables) + expect(SOURCE_EXIT_CODES).toEqual(expect.arrayContaining(codes)) + }) +}) + describe('the exit codes a get names in its --help', () => { it.each(['workflows source get', 'workspaces source get'] as const)( '%s names exit 13 for a missing or refused login', diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index 8c75733cdd5..67f37039858 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -344,6 +344,11 @@ function realPath(path: string): string { } } +/** A relative filter as given, with `/` separators and its leading `./` and trailing `/` dropped. */ +export function givenFilterPath(filter: string): string { + return stripTrailingSlashes(filter.replace(/\\/g, '/').replace(/^(\.\/)+/, '')) +} + /** * The directory-relative forms of one filter: as given (`./` and a trailing `/` dropped, an empty * one meaning the whole directory) and resolved from the current directory, so both @@ -353,7 +358,7 @@ function realPath(path: string): string { function filterForms(filter: string, dir: string): string[] { const forms = new Set() if (!isAbsolute(filter)) { - const given = stripTrailingSlashes(filter.replace(/\\/g, '/').replace(/^(\.\/)+/, '')) + const given = givenFilterPath(filter) forms.add(given === '' ? '.' : given) } const resolved = relative(realPath(resolve(dir)), realPath(resolve(filter))) diff --git a/packages/sim-cli/src/commands/protocol/source-strict.ts b/packages/sim-cli/src/commands/protocol/source-strict.ts new file mode 100644 index 00000000000..12799b4aa31 --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/source-strict.ts @@ -0,0 +1,28 @@ +/** + * The warnings a check fails on as errors: an apply saves each as written although the block it + * names is broken. One table, so `check --help` and the directory guides name the same findings. + */ + +import type { DiagnosticCode } from '@sim/workflow-code/diagnostics/codes' + +/** Each strict warning code with what it finds, as the guides phrase it. */ +export const STRICT_FINDINGS: ReadonlyMap = new Map([ + ['W_REQUIRED_MISSING', 'a missing required field'], + ['W_UNKNOWN_OPTION', 'an unknown option'], + ['W_UNKNOWN_OUTPUT_PATH', 'an unknown output path'], + ['W_VALUE_KIND', 'a wrong value kind'], + ['W_OUT_OF_RANGE', 'an out-of-range value'], + ['W_LITERAL_SECRET', 'a literal secret'], + ['W_TABLE_UNKNOWN_COLUMN', 'a table write to an unknown column'], + ['W_CHILD_INPUT_UNKNOWN', 'an input a child workflow does not declare'], + ['W_CHILD_RESULT_PATH', "a path a child workflow's result does not hold"], + ['W_BRANCH_UNWIRED', 'an unwired condition or router branch'], + ['W_UNRESOLVED_REF', 'a reference that names nothing'], + ['W_REF_OUT_OF_SCOPE', 'an iteration field read outside its loop or parallel'], + ['W_LOOP_CONDITION_SYNTAX', 'a loop condition that is not a JavaScript expression'], +] satisfies Array<[DiagnosticCode, string]>) + +const phrases = [...STRICT_FINDINGS.values()] + +/** Every {@link STRICT_FINDINGS} phrase as one clause: `a, b, … or z`. */ +export const STRICT_FINDINGS_CLAUSE = `${phrases.slice(0, -1).join(', ')} or ${phrases.at(-1)}` diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 18ddafa169a..f724628b90c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -38,6 +38,7 @@ import { writeBack, } from './source-dir' import { sourceExitCodesTable } from './source-exit-codes' +import { STRICT_FINDINGS_CLAUSE } from './source-strict' import { assertSdkMajor, finishTree, @@ -221,7 +222,7 @@ The primer above is enough to edit; read a section here when a step needs it. ## Edit loop in detail 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. -2. \`sim workflows source check --dir .\`: compiles offline with the server's compiler, in milliseconds. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on a missing required field, an unknown option or output path, a wrong value kind, an out-of-range value, an unwired condition or router branch or a literal secret in a block you added (\`--strict\`: in every block). It also adds the blocks the source now uses to \`tsconfig.json\`. +2. \`sim workflows source check --dir .\`: compiles offline with the server's compiler, in milliseconds. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It also adds the blocks the source now uses to \`tsconfig.json\`. 3. \`${typecheckCommand()}\`: about a second; catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It runs the TypeScript release the declarations are built for (the directory has no \`package.json\`; plain \`bunx tsc\` would run whatever version it finds). \`tsconfig.json\` includes only the blocks the source used at the last check, get or apply: a builder from another block fails with \`has no exported member\` until you run step 2 (or use \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). The dry run is the authority: a printed line you did not edit that \`tsc\` flags and the dry run accepts is fine. 4. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry-run\` until it exits 0. 5. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--deploy\` also deploys it; without it, a deployed workflow's next \`sim workflows deploy --expected-draft-fingerprint \` is printed, which deploys only the draft this apply saved. It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). @@ -254,7 +255,7 @@ The \`// @sim-sdk 1\` header must be the first line, and the file has exactly on - \`sim workflows source params \`: one builder's params (required first, enums, defaults) and outputs; a namespace (\`gmail\`) lists its builders; a miss names the closest. Builders are named for the service, not the block type: \`gmail_v2\` is \`gmail.*\`, \`workflow_input\` is \`runWorkflow\`, the HTTP request block is \`api\`, and \`legacy.*\` builders are old versions not to write. - \`${SDK_DIR}/core.d.ts\`: the SDK (\`workflow\`, \`t\`, \`env\`, \`credential\`, \`table\`, \`loop\`, \`parallel\`, \`BlockMeta\`). - \`${SDK_DIR}/blocks/.d.ts\`: the builders of a block the source uses, with their params and outputs (check adds the file of a block an edit starts using). Do not read them, or \`${SDK_DIR}/models.d.ts\`, whole: \`params\` prints the part you need, and \`grep\` finds a model id. -- \`${WORKSPACE_TYPES_FILE}\`: this workspace's tables, knowledge bases, credentials, workflows and env names. +- \`${WORKSPACE_TYPES_FILE}\`: this workspace's tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names. ## Rules diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index 21ee1274d9b..01b7749d6c7 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -1,4 +1,5 @@ import { isRecordLike, toRecord } from '@sim/utils/object' +import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import type { Command } from 'commander' import { writeStderr } from '#sim-cli/output/io' import { styles } from '#sim-cli/output/presentation' @@ -16,7 +17,7 @@ import { buildRequest } from '../../runtime/request' import { renderResult } from '../../runtime/result' import type { OperationSpec } from '../../runtime/types' import { printRunFailureSite } from './run-source-location' -import { BLOCK_ID, normalizeBlockName } from './workflow-run-get' +import { BLOCK_ID } from './workflow-run-get' import { parseWaitTimeout, type RunSnapshot, @@ -43,7 +44,7 @@ const WORKFLOW_RESULT_STREAM_CONTENT_TYPE = 'application/x-ndjson' const DONE_SENTINEL = '[DONE]' /** The sink live commentary is written to; `process.stderr` satisfies it. */ -export interface CommentaryWriter { +interface CommentaryWriter { write(text: string): unknown } @@ -62,7 +63,7 @@ type WorkflowRunSelection = { } /** Projects friendly CLI flags into the API's strict nested run selector. */ -export function resolveWorkflowRunSelection( +function resolveWorkflowRunSelection( flags: Record ): WorkflowRunSelection | undefined { const trigger = typeof flags.trigger === 'string' ? flags.trigger : undefined @@ -493,7 +494,7 @@ async function followRun(workflowId: string, command: Command): Promise { * The selection a `--stop-after` run sends when the caller selected nothing: the stop block's * whole output, so `blockOutputs` (with `--follow`, the final frame's `output`) names the block * the run stopped after and holds what it produced (no Response block ran). The block is sent as - * the executor compares names ({@link normalizeBlockName}), so a display name with a dot is not read + * the executor compares names (`normalizeWorkflowBlockName`), so a display name with a dot is not read * as a path; an id is sent as it is. */ function stopBlockSelection( @@ -503,7 +504,7 @@ function stopBlockSelection( const stopAfter = selection?.stopAfterBlockId if (stopAfter === undefined) return null if (Array.isArray(flags.selectOutput) && flags.selectOutput.length > 0) return null - return [BLOCK_ID.test(stopAfter) ? stopAfter : normalizeBlockName(stopAfter)] + return [BLOCK_ID.test(stopAfter) ? stopAfter : normalizeWorkflowBlockName(stopAfter)] } /** diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-get.ts b/packages/sim-cli/src/commands/protocol/workflow-run-get.ts index b5babc58768..21a77cd6118 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-get.ts @@ -1,4 +1,5 @@ import { isRecordLike } from '@sim/utils/object' +import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import type { Command } from 'commander' import { CLI_CONTRACT } from '../../contract/commands' import { V2_OPERATIONS } from '../../generated/v2-api' @@ -23,21 +24,6 @@ export const BLOCK_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a- const SELECT_OUTPUT_FLAG = 'select-output' -/** - * A block name as the executor compares one: lowercased, whitespace and dots - * removed. - * - * `normalizeWorkflowBlockName` in `@sim/workflow-types`, restated. It is the - * rule `workflows run --select-output` resolves names with server-side and the - * one every block-name conflict check applies, so `Summarize Result` and - * `summarizeresult` name the same block on both commands. Restated rather than - * imported because this package ships standalone and carries no workspace - * dependency. - */ -export function normalizeBlockName(name: string): string { - return name.toLowerCase().replace(/\s+/g, '').replace(/\./g, '') -} - interface WorkflowBlock { id: string name: string @@ -105,9 +91,9 @@ function resolveSelection( const { head, path } = splitSelector(selector) let blockId = head if (!BLOCK_ID.test(head)) { - const wanted = normalizeBlockName(head) + const wanted = normalizeWorkflowBlockName(head) const matches = blocks.filter( - (block) => block.id === head || normalizeBlockName(block.name) === wanted + (block) => block.id === head || normalizeWorkflowBlockName(block.name) === wanted ) if (matches.length === 0) { unresolved.push(selector) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.test.ts new file mode 100644 index 00000000000..6322fe7efa5 --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.test.ts @@ -0,0 +1,12 @@ +import { expectLinearGrowth } from '@sim/testing/helpers/scaling' +import { describe, it } from 'vitest' +import { seedRowsFiles } from './workspace-source-dir' + +describe('seedRowsFiles', () => { + it('reads a table declaration of unclosed column calls in linear time', () => { + expectLinearGrowth((n) => { + const files = { 'tables/leads.ts': 'column.text('.repeat(n) } + return () => seedRowsFiles(files) + }, 4_000) + }) +}) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 8cd2c6d2729..0f1c7b089d1 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -75,6 +75,7 @@ import { type Written, } from './source-dir' import { sourceExitCodesTable } from './source-exit-codes' +import { STRICT_FINDINGS_CLAUSE } from './source-strict' import { type LocalDeclarations, type SourceTreeProfile, @@ -144,7 +145,7 @@ Secrets never appear in source: a workflow reads an environment variable as \`en ## Edit loop in detail 1. Edit the files. -2. \`sim workspaces source check --dir .\`: compiles every workflow offline with the server's compiler, against what this directory declares: an unknown resource key (skills included) or table column, a child workflow's inputs, and an env name \`${KIND_DIRS.secret}\` lacks (a warning); and checks each \`${KIND_DIRS.table}/.rows.jsonl\` line against its table as the apply would. It fails (exit 1) on errors and on a missing required field, an unknown option or output path, a wrong value kind, an out-of-range value, an unwired condition or router branch or a literal secret in a block you added (\`--strict\`: in every block), regenerates \`.sim/sdk/workspace.d.ts\` and adds the blocks the workflows now use to \`tsconfig.json\`. In a workflow folder, \`sim workflows source check --dir .\` checks that one workflow the same way. Fix and rerun until it exits 0. +2. \`sim workspaces source check --dir .\`: compiles every workflow offline with the server's compiler, against what this directory declares: an unknown resource key (skills included) or table column, a child workflow's inputs, and an env name \`${KIND_DIRS.secret}\` lacks (a warning); and checks each \`${KIND_DIRS.table}/.rows.jsonl\` line against its table as the apply would. It fails (exit 1) on errors and on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block), regenerates \`.sim/sdk/workspace.d.ts\` and adds the blocks the workflows now use to \`tsconfig.json\`. In a workflow folder, \`sim workflows source check --dir .\` checks that one workflow the same way. Fix and rerun until it exits 0. 3. Run \`${typecheckCommand()}\` after every edit, before any dry run or apply, and fix what it reports: it takes about a second and catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It type-checks the files with the TypeScript release the declarations are built for. \`tsconfig.json\` includes only the blocks the workflows used at the last check or get, which keeps it fast: a builder from another block fails with \`has no exported member\` until you run step 2 (or check with \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). \`sim workflows source params \` prints one builder's params and outputs; do not read the declarations whole. The dry run is the authority: a printed file you did not edit that \`tsc\` flags and the dry run accepts is fine, so leave it as it is. 4. \`sim workspaces source status --dir .\` before applying: your changes by resource (\`sim workspaces source diff --dir .\` shows the edits), what changed on the server since the get (a workflow edited in the editor included), the conflicts, and the command to run next. Exit 0 nothing changed, ${SOURCE_LOCAL_CHANGES_EXIT_CODE} only your edits, ${SOURCE_DRIFT_EXIT_CODE} the server changed since (\`--offline\`: skip the server). Then \`sim workspaces source apply --dir . --dry-run\`: shows the plan (\`+\` create, \`~\` update, \`=\` adopt an existing resource of the same name, \`-\` delete) and every error; fix and rerun until it exits 0. 5. \`sim workspaces source apply --dir . --yes\`: writes it and rewrites this directory from what was stored; it prints the plan it applied (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}, writing nothing). @@ -424,8 +425,21 @@ function tableRowFindings(key: string, decl: TableDecl, text: string | undefined /** A table declaration as the codec reads it, with its findings. */ type ParsedTable = ReturnType['parse']> -/** A column helper call and its arguments' text: `column.select({ options: [...] })`. */ -const COLUMN_CALL = /\bcolumn\.(\w+)\s*\(([^)]*)\)/g +/** + * Each column helper call in `source` with its arguments' text up to the first `)`: + * `column.select({ options: [...] })`. The next call is looked for after that `)`, and the walk + * stops at the first call no `)` follows, so a file of unclosed calls is read once. + */ +function* columnCalls(source: string): Generator<[type: string, args: string]> { + const head = /\bcolumn\.(\w+)\s*\(/g + for (let match = head.exec(source); match !== null; match = head.exec(source)) { + const open = match.index + match[0].length + const close = source.indexOf(')', open) + if (close === -1) return + yield [match[1], source.slice(open, close)] + head.lastIndex = close + 1 + } +} /** * A table declaration as the codec reads it. The server's column-type catalog @@ -441,7 +455,7 @@ function declaredTable( const text = Object.fromEntries(paths.map((path) => [path, files[path] ?? ''])) const owned = new Map>() for (const source of Object.values(text)) { - for (const [, type, args] of source.matchAll(COLUMN_CALL)) { + for (const [type, args] of columnCalls(source)) { const owns = owned.get(type) ?? new Set() for (const option of TABLE_COLUMN_METADATA_KEYS) { if (new RegExp(`\\b${option}\\s*:`).test(args)) owns.add(option) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts index 4c1e7be4d48..3f82e5f1f83 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts @@ -834,6 +834,15 @@ describe('workspaces source diff', () => { expect((printed().files as unknown[]).length).toBe(1) }) + it('asks the server for the kind of a filter written with repeated ./ alone', async () => { + write('tables/leads.ts', `${LEADS}// edited\n`) + mockRequest.mockResolvedValue(served({ 'tables/leads.ts': LEADS })) + + await run('diff', '--server', './././tables/leads.ts') + + expect(mockRequest.mock.calls[0][1]).toMatchObject({ query: { kinds: 'table' } }) + }) + it('reports a binary file by its sizes', async () => { const sha256 = createHash('sha256').update(NOTES).digest('hex') write('files/notes.bin', Buffer.concat([NOTES, Buffer.from(' and two')])) 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 55f71dda9b1..722791675e0 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -8,8 +8,8 @@ * at. */ import { isRecordLike, toRecord } from '@sim/utils/object' +import { utf8ByteLength } from '@sim/utils/paste' import { compareStrings } from '@sim/utils/string' -import { utf8Bytes } from '@sim/workflow-code/limits' import { isWorkspaceKind, KIND_DIRS, type WorkspaceKind } from '@sim/workspace-code' import { isFolderEvaluationFinding } from '@sim/workspace-code/diagnostics/codes' import { isBlobPath, KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' @@ -53,6 +53,7 @@ import { type DiffReport, destructiveChanges, type FileDiff, + givenFilterPath, loginCommand, type NextStep, nextStep, @@ -300,7 +301,7 @@ function planLine(plan: WorkspacePlanSummary): string { function fitsWhole(files: Readonly>): boolean { const paths = Object.keys(files).filter((path) => kindOfPath(path) === 'workflow') const folders = KIND_LAYOUTS.workflow.group(paths).groups.size - const bytes = paths.reduce((sum, path) => sum + utf8Bytes(files[path]), 0) + const bytes = paths.reduce((sum, path) => sum + utf8ByteLength(files[path]), 0) return ( folders <= WORKSPACE_SOURCE_LIMITS.maxWorkflows && bytes <= WORKSPACE_SOURCE_LIMITS.maxWorkflowBytes @@ -492,9 +493,7 @@ function filteredKinds(filters: readonly string[]): WorkspaceKind[] | undefined const kinds = new Set() for (const filter of filters) { const named = filter.split(':', 1)[0] - const kind = isWorkspaceKind(named) - ? named - : kindOfPath(filter.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')) + const kind = isWorkspaceKind(named) ? named : kindOfPath(givenFilterPath(filter)) if (kind === null) return undefined kinds.add(kind) } diff --git a/packages/utils/src/paste.test.ts b/packages/utils/src/paste.test.ts index 12c999c4ae4..9d7151c304f 100644 --- a/packages/utils/src/paste.test.ts +++ b/packages/utils/src/paste.test.ts @@ -3,7 +3,16 @@ import { assessTextPaste, utf8ByteLength } from './paste' describe('utf8ByteLength', () => { it('matches UTF-8 for ASCII, BMP, astral, and malformed UTF-16', () => { - for (const value of ['plain text', 'café', '你好', '💡', '\ud800']) { + for (const value of [ + 'plain text', + 'café', + '你好', + '💡', + '\ud800', + '\udc00', + '\ud800é', + '\ud800𐀀', + ]) { expect(utf8ByteLength(value)).toBe(new TextEncoder().encode(value).byteLength) } }) diff --git a/packages/utils/src/timezone.test.ts b/packages/utils/src/timezone.test.ts index 8bd18a5499c..ead877dd777 100644 --- a/packages/utils/src/timezone.test.ts +++ b/packages/utils/src/timezone.test.ts @@ -1,7 +1,6 @@ import { getTimezoneOptions, getWallClockParts, - zonedClockDate, zonedWallClock, zonedWallClockToUtc, zonedWallClockWithOffset, @@ -178,25 +177,3 @@ describe('getTimezoneOptions', () => { ).toMatch(/^(Kolkata|Calcutta) \(GMT\+05:30\)$/) }) }) - -describe('zonedClockDate', () => { - const instant = new Date('2026-06-15T13:00:00.000Z') - - it('exposes the zone wall-clock through device-local fields', () => { - const ny = zonedClockDate(instant, 'America/New_York') - expect(ny.getHours()).toBe(9) - expect(ny.getMinutes()).toBe(0) - expect(ny.getDate()).toBe(15) - }) - - it('rolls the date when the zone is on the other side of midnight', () => { - const tokyo = zonedClockDate(instant, 'Asia/Tokyo') - expect(tokyo.getDate()).toBe(15) - expect(tokyo.getHours()).toBe(22) - - const earlyUtc = new Date('2026-06-15T01:00:00.000Z') - const la = zonedClockDate(earlyUtc, 'America/Los_Angeles') - expect(la.getDate()).toBe(14) - expect(la.getHours()).toBe(18) - }) -}) diff --git a/packages/utils/src/timezone.ts b/packages/utils/src/timezone.ts index 5a5f1b93eaf..5e8de916fa8 100644 --- a/packages/utils/src/timezone.ts +++ b/packages/utils/src/timezone.ts @@ -120,7 +120,7 @@ export function assertValidTimezone(timezone: string): void { * Every IANA timezone identifier the runtime knows, for populating a picker; * falls back to a curated common set on runtimes without `Intl.supportedValuesOf`. */ -export function getSupportedTimezones(): string[] { +function getSupportedTimezones(): string[] { const zones = typeof Intl.supportedValuesOf === 'function' ? Intl.supportedValuesOf('timeZone') @@ -222,21 +222,6 @@ export function zonedWallClock(instant: Date, timeZone: string): string { return `${formatIsoYear(wall.year)}-${pad(wall.month)}-${pad(wall.day)}T${pad(wall.hour)}:${pad(wall.minute)}` } -/** - * A `Date` whose device-local fields (year…minute) equal the wall-clock time of - * `instant` in `timeZone`. It deliberately does NOT represent the same instant — - * it is a positioning coordinate that lets naive-local layout code (the calendar - * grid, {@link zonedWallClock}-free pixel offsets) render in `timeZone` without - * itself being timezone-aware. Never read its `getTime()` as a real timestamp; - * the true instant always lives alongside it (e.g. a task's `runAt`). - */ -export function zonedClockDate(instant: Date, timeZone: string): Date { - const [datePart, timePart] = zonedWallClock(instant, timeZone).split('T') - const [year, month, day] = datePart.split('-').map(Number) - const [hour, minute] = timePart.split(':').map(Number) - return new Date(year, month - 1, day, hour, minute) -} - /** The UTC offset (ms, east-positive) of `timeZone` at a given instant. */ function timezoneOffsetMs(instant: Date, timeZone: string): number { return offsetMsFromWallClock(instant, getWallClockParts(instant, timeZone)) diff --git a/packages/workflow-code/src/babel.ts b/packages/workflow-code/src/babel.ts index ff235e1b23e..bb3f94cdf1b 100644 --- a/packages/workflow-code/src/babel.ts +++ b/packages/workflow-code/src/babel.ts @@ -47,6 +47,13 @@ export function childNodes(node: Node): Node[] { return children } +/** The name a member access reads: `.name` or `['name']` (optional or not); `null` otherwise. */ +export function memberName(node: Node): string | null { + if (node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression') return null + if (!node.computed && node.property.type === 'Identifier') return node.property.name + return node.property.type === 'StringLiteral' ? node.property.value : null +} + /** * The reference path segment a member access writes: `.name`, `['name']` or `[0]`; `null` for any * other property, which no stored reference path can spell. diff --git a/packages/workflow-code/src/canonicalize/subflows.ts b/packages/workflow-code/src/canonicalize/subflows.ts index a181df6ca64..71ec22aa4ad 100644 --- a/packages/workflow-code/src/canonicalize/subflows.ts +++ b/packages/workflow-code/src/canonicalize/subflows.ts @@ -15,6 +15,8 @@ const PARALLEL_BATCH_MIN = 1 export const PARALLEL_BATCH_MAX = 20 /** `count || 5` in `convertLoopBlockToLoop` and the loop orchestrator. */ export const DEFAULT_LOOP_ITERATIONS = 5 +/** `data.count || 5` in `convertParallelBlockToParallel`. */ +export const DEFAULT_PARALLEL_COUNT = 5 /** `clampParallelBatchSize`: a missing or non-numeric size is 20, anything else 1–20. */ export function effectiveBatchSize(batchSize: number | undefined): number { @@ -124,7 +126,11 @@ export function loopSpec( if (typeof data.count === 'number') { spec.iterations = data.count if (data.count === 0) { - repaired(context, blockKey, 'Loop count is 0; the runtime runs 5 iterations') + repaired( + context, + blockKey, + `Loop count is 0; the runtime runs ${DEFAULT_LOOP_ITERATIONS} iterations` + ) } } else if (data.count !== undefined) { rejected.push('count') @@ -181,10 +187,15 @@ export function parallelSpec( const count = firstDefined(data.count, parallel?.count) if (typeof count === 'number') { spec.count = count - if (count === 0) repaired(context, blockKey, 'Parallel count is 0; the runtime runs 5') + if (count === 0) + repaired(context, blockKey, `Parallel count is 0; the runtime runs ${DEFAULT_PARALLEL_COUNT}`) } else if (count !== undefined) { rejectIfFromData(rejected, data, 'count') - repaired(context, blockKey, 'Parallel count is not a number; the runtime runs 5') + repaired( + context, + blockKey, + `Parallel count is not a number; the runtime runs ${DEFAULT_PARALLEL_COUNT}` + ) } const distribution = jsonField(firstDefined(data.collection, parallel?.distribution), context) @@ -194,11 +205,19 @@ export function parallelSpec( if (typeof batchSize === 'number') { spec.batchSize = batchSize if (batchSize < PARALLEL_BATCH_MIN || batchSize > PARALLEL_BATCH_MAX) { - repaired(context, blockKey, `Parallel batch size ${batchSize} is clamped to 1–20 at run time`) + repaired( + context, + blockKey, + `Parallel batch size ${batchSize} is clamped to ${PARALLEL_BATCH_MIN}–${PARALLEL_BATCH_MAX} at run time` + ) } } else if (batchSize !== undefined) { rejectIfFromData(rejected, data, 'batchSize') - repaired(context, blockKey, 'Parallel batch size is not a number; the runtime uses 20') + repaired( + context, + blockKey, + `Parallel batch size is not a number; the runtime uses ${PARALLEL_BATCH_MAX}` + ) } return { spec, rejectedDataKeys: rejected } } diff --git a/packages/workflow-code/src/code-files/references.ts b/packages/workflow-code/src/code-files/references.ts index 1d1a50efec5..f8ff9faad6d 100644 --- a/packages/workflow-code/src/code-files/references.ts +++ b/packages/workflow-code/src/code-files/references.ts @@ -1,8 +1,9 @@ import { parse } from '@babel/parser' import type { Node } from '@babel/types' +import { utf8ByteLength } from '@sim/utils/paste' import { childNodes, literalText } from '../babel' import { bracketDepthOverflow, PARSER_OPTIONS } from '../compile/parse' -import { SOURCE_LIMITS, utf8Bytes } from '../limits' +import { SOURCE_LIMITS } from '../limits' import { SDK_MODULE } from '../sdk' /** The SDK export a function block's code file is read through. */ @@ -17,7 +18,7 @@ const CODE_FILE_EXPORT = 'codeFile' * can (possibly nothing): the server refuses it with the full diagnostics. */ export function codeFileReferences(text: string): string[] { - if (utf8Bytes(text, SOURCE_LIMITS.maxTotalBytes) > SOURCE_LIMITS.maxTotalBytes) return [] + if (utf8ByteLength(text, SOURCE_LIMITS.maxTotalBytes) > SOURCE_LIMITS.maxTotalBytes) return [] if (bracketDepthOverflow(text, SOURCE_LIMITS.maxDepth) !== -1) return [] let program: Node try { diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index 9b453752e78..dc51abb63a6 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -444,9 +444,13 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `W_OUTPUT_PATH_UNDECLARED` | A path the block does not declare that the run still accepts: an undeclared `inputFormat` input, or `x.error` with no error edge. Never refused. | | `W_JSON_REF_UNTYPED` | A bare ref in a JSON literal whose type nothing declares. | | `W_LOOP_CONDITION_SYNTAX` | A while or do-while condition that is not a JavaScript expression once each reference stands in as a value, as the run evaluates it (`return Boolean()`): the run fails there. Refused as `E_APPLY_LOOP_CONDITION_SYNTAX` on a loop the edit added or changed. A loop reading its own `index` (or `currentItem`, `items`) by its name in its condition is `W_REF_OUT_OF_SCOPE`: the condition is evaluated outside the loop's body, so only `` reads the iteration there. | +| `W_REF_OUT_OF_SCOPE` | A loop or parallel iteration field (`index`, `currentItem`, `items`) read from a block outside that container: `lp.index` after the loop, `$ref.loop.index` or `` in a block in no loop. The run fails (or reads nothing) there. Refused as `E_APPLY_REF_OUT_OF_SCOPE` on a block the edit changed. | +| `W_UNKNOWN_BLOCK_TYPE` | A new block of a type the catalog does not hold; refused as `E_APPLY_INVALID_BLOCK_TYPE`. A block the stored workflow or the lock already holds keeps its type quietly. | +| `W_TYPE_NOT_ADDABLE` | A new block of a type the catalog keeps only for blocks already using it; refused as `E_APPLY_TYPE_NOT_ADDABLE`. | | `E_CODE_FILE_MISSING` | `codeFile()` names a file the request did not send. | | `E_CODE_FILE_PATH` | A code file path outside the directory, or with the wrong extension. | | `W_CODE_FILE_INLINED` | Print: the code could not round-trip through a file and was inlined. | +| `W_CODE_FILE_REF_SYNTAX` | `$ref.key.path` or `$env.NAME` in a Python or shell code file, which runs as text; the hint names the `` or `{{NAME}}` form. Refused as `E_APPLY_CODE_FILE_REF_SYNTAX` in a file the edit changed. | | `W_UNRESOLVED_REF` | Print: a stored `` token that resolves to nothing. Compile: a code file `$ref` chain that does. Either is kept as text. | | `W_FORWARD_REF_LITERALIZED` | Print: a ref in a cycle printed as text. | | `W_COMMENT_MOVED` | A comment hoisted to the nearest anchor. | @@ -525,7 +529,12 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `W_APPLY_TRIGGER_REMOVED` | A deleted or retyped block still serves a live webhook, schedule, chat output or MCP tool until the next deploy. | | `W_APPLY_CATALOG_MOVED` | Compile failed and the block catalog changed since the read: get the source again. | | `E_APPLY_LINT`, `W_APPLY_LINT` | A workflow lint finding, mapped to a source line. | +| `E_APPLY_UNRESOLVED_REF` | A `$ref` naming no block or variable, or a path no output has, in code or a block the edit changed (`W_UNRESOLVED_REF`, `W_UNKNOWN_OUTPUT_PATH` elsewhere). | +| `E_APPLY_REF_OUT_OF_SCOPE` | A `W_REF_OUT_OF_SCOPE` iteration reference on a block the edit added, changed or moved. | +| `E_APPLY_CODE_FILE_REF_SYNTAX` | A `W_CODE_FILE_REF_SYNTAX` in a code file the edit changed. | +| `E_APPLY_LOOP_CONDITION_SYNTAX` | A `W_LOOP_CONDITION_SYNTAX` on a loop the edit added or changed. | | `E_APPLY_BLOCK_DELETE` | The apply deletes blocks the source no longer declares; pass `--allow-delete`. When it also adds blocks of a deleted one's type, it names them as possible renames and says how to keep the ids. | +| `E_APPLY_VARIABLE_DELETE` | The apply removes workflow variables the source no longer declares; pass `--allow-delete`, as for blocks. | | `W_APPLY_PROBABLE_RENAME` | With `--allow-delete`, a deleted block and an added one share a type and parent: a probable rename that gets a new id. | | `E_NAME_TAKEN` | The `workflow('…')` name renames the workflow to one another workflow in its folder holds. | | `E_WORKFLOW_META_INVALID` | The `workflow('…')` name is empty or over 255 characters, or its description is over 50,000 characters: limits the workflow API holds every workflow to. | diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index aa906c0c742..22b47b1a6d6 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -1,6 +1,7 @@ import { parse } from '@babel/parser' import type { Node, ObjectExpression, ObjectProperty } from '@babel/types' import { isRecordLike } from '@sim/utils/object' +import { utf8ByteLength } from '@sim/utils/paste' import { findWorkflowReferenceTokens, isLikelyWorkflowReferenceSegment, @@ -49,7 +50,7 @@ import { isIdentifierName, LOOP_PROPERTIES, parseStoredPath } from '../code-file import { branchesAtTopLevel, ELSE_KEY, isElseTrue } from '../forms/condition' import { compileResponseParam, usesResponseForm } from '../forms/response' import { type ConfigField, type ContainerForm, loopForm, parallelForm } from '../forms/subflow' -import { CODE_FILE_EXTENSIONS, isCodeFilePath, SOURCE_CODE_DIR, utf8Bytes } from '../limits' +import { CODE_FILE_EXTENSIONS, isCodeFilePath, SOURCE_CODE_DIR } from '../limits' import { isJson } from '../lock' import { type AnchorKey, @@ -83,7 +84,7 @@ import { unsupported, } from './context' import { closest, didYouMean } from './hints' -import { bracketDepthOverflow } from './parse' +import { babelMessage, bracketDepthOverflow } from './parse' import type { Range } from './report' import { compileToolList } from './tools' import { @@ -423,7 +424,7 @@ function parseCodeFile( ): string | null { const { limits } = ctx const before = ctx.codeFiles.bytes - ctx.codeFiles.bytes += utf8Bytes(text, limits.maxTotalBytes) + ctx.codeFiles.bytes += utf8ByteLength(text, limits.maxTotalBytes) if (ctx.codeFiles.bytes > limits.maxTotalBytes) { // Reported once, on the file that crosses the cap; each file after it is skipped silently. if (before > limits.maxTotalBytes) return null @@ -1932,11 +1933,9 @@ function checkLoopCondition( failure = error } if (failure === null) return - const { message: raw } = babelErrorShape(failure) - const message = typeof raw === 'string' ? raw : 'Invalid JavaScript' ctx.reporter.report( 'W_LOOP_CONDITION_SYNTAX', - `${decl.name}'s condition is not a JavaScript expression (${message.replace(/\s*\(\d+:\d+\)$/, '')}), so the run fails when it evaluates it.`, + `${decl.name}'s condition is not a JavaScript expression (${babelMessage(babelErrorShape(failure))}), so the run fails when it evaluates it.`, at, { hint: "Write one JavaScript expression the loop repeats while it is true, e.g. condition: ' < 3'.", diff --git a/packages/workflow-code/src/compile/function-returns.ts b/packages/workflow-code/src/compile/function-returns.ts index 38af616f1a3..6fa5e4372ef 100644 --- a/packages/workflow-code/src/compile/function-returns.ts +++ b/packages/workflow-code/src/compile/function-returns.ts @@ -13,7 +13,7 @@ import { parse } from '@babel/parser' import type { Expression, Node, ObjectExpression, PatternLike } from '@babel/types' -import { childNodes } from '../babel' +import { childNodes, memberName } from '../babel' import { parseStoredPath } from '../code-files/ref-path' import { toCodeFile } from '../code-files/to-file' import type { BlockKey, CanonicalBlock } from '../model' @@ -206,13 +206,6 @@ function merge(a: JsKind | undefined, b: JsKind | undefined): JsKind | undefined return a !== 'string' && b !== 'string' ? 'typed' : undefined } -/** The member name a non-computed (or string-keyed) member expression or call reads. */ -function memberName(node: Node): string | null { - if (node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression') return null - if (!node.computed && node.property.type === 'Identifier') return node.property.name - return node.property.type === 'StringLiteral' ? node.property.value : null -} - /** Infers expression kinds over one program's bindings, guarding against self-reference. */ class Inference { private readonly resolving = new Set() diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index 506617fa696..67f41a030f3 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -1,4 +1,5 @@ import type { ArrowFunctionExpression, CallExpression, Node } from '@babel/types' +import { utf8ByteLength } from '@sim/utils/paste' import { compareStrings } from '@sim/utils/string' import { isVariableType, @@ -13,7 +14,6 @@ import type { BlockCatalog } from '../catalog/types' import type { CompileDiagnosticCode } from '../diagnostics/codes' import type { LocatedDiagnostic, SourceSpan } from '../diagnostics/frame' import { jsonFieldText, type RefTypeScope, refValueKind } from '../json-fields' -import { utf8Bytes } from '../limits' import { lockIdentRenames, type SourceHints, type WorkflowLockV1 } from '../lock' import { renamedReferenceRewriter } from '../materialize/values' import type { @@ -527,7 +527,7 @@ function compileEntry( reporter: Reporter ): CompileResult { const limits = { ...DEFAULT_LIMITS, ...input.limits } - if (utf8Bytes(text, limits.maxTotalBytes) <= limits.maxTotalBytes) + if (utf8ByteLength(text, limits.maxTotalBytes) <= limits.maxTotalBytes) checkStorableText(file, text, reporter) const parsed = parseWorkflowSource(file, text, limits, reporter) if (parsed.sdkMajor === null) { @@ -567,7 +567,13 @@ function compileEntry( catalog: input.catalog, files: input.files, limits, - codeFiles: { reads: new Map(), refs: 0, bytes: utf8Bytes(text), chains: [], sharedReads: [] }, + codeFiles: { + reads: new Map(), + refs: 0, + bytes: utf8ByteLength(text), + chains: [], + sharedReads: [], + }, comments: new CommentCollector(file, reporter), decls: [], declsByKey: new Map(), diff --git a/packages/workflow-code/src/compile/parse.ts b/packages/workflow-code/src/compile/parse.ts index 4114b08bad2..29ca14fa292 100644 --- a/packages/workflow-code/src/compile/parse.ts +++ b/packages/workflow-code/src/compile/parse.ts @@ -1,9 +1,10 @@ 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 { codeFileLanguage } from '../code-files' import { createJsContextScanner } from '../code-files/lexer' -import { SOURCE_LIMITS, utf8Bytes } from '../limits' +import { SOURCE_LIMITS } from '../limits' import type { Reporter } from './report' /** Caps on hostile input. Defaults are the shared `SOURCE_LIMITS` (`limits.ts`). */ @@ -123,7 +124,7 @@ export function parseWorkflowSource( ): ParsedSource { const parsed: ParsedSource = { ast: null, ...sdkHeader(text) } - if (utf8Bytes(text, limits.maxTotalBytes) > limits.maxTotalBytes) { + if (utf8ByteLength(text, limits.maxTotalBytes) > limits.maxTotalBytes) { reporter.report( 'E_LIMIT_EXCEEDED', `The file is larger than ${limits.maxTotalBytes} bytes, the limit for all source files together.`, diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index a523a69ef76..5b0d94fc2b6 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -14,7 +14,7 @@ import { isReservedWorkflowBlockName, normalizeWorkflowBlockName, } from '@sim/workflow-types/workflow' -import { literalText, memberSegment } from '../babel' +import { literalText, memberName, memberSegment } from '../babel' import { builderOutputSchemas } from '../catalog/activity' import type { CatalogOutput } from '../catalog/types' import { @@ -572,13 +572,6 @@ function compileMemberSegment( ) } -function memberName(member: MemberExpression): string | null { - const property = member.property - if (!member.computed && property.type === 'Identifier') return property.name - if (member.computed && property.type === 'StringLiteral') return property.value - return null -} - function outputKnown(outputs: Record, segments: RefSegment[]): boolean { let level: Record | undefined = outputs for (const segment of segments) { diff --git a/packages/workflow-code/src/diagnostics/refusals.ts b/packages/workflow-code/src/diagnostics/refusals.ts index 45b85d3f1cf..096d81fd9d0 100644 --- a/packages/workflow-code/src/diagnostics/refusals.ts +++ b/packages/workflow-code/src/diagnostics/refusals.ts @@ -88,6 +88,9 @@ export interface EditedBlocks { paramChanged?(blockKey: string, param: string): boolean } +/** A warning code and the error an apply refuses it under. */ +type RefusalRule = [warning: CompileDiagnosticCode, refusal: EditRefusalCode] + /** * An iteration field read outside its container (`W_REF_OUT_OF_SCOPE`), or a loop condition that * is not a JavaScript expression (`W_LOOP_CONDITION_SYNTAX`), refused in any file on a block the @@ -96,7 +99,7 @@ export interface EditedBlocks { const CHANGED_BLOCK_REFUSALS: ReadonlyMap = new Map([ ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], ['W_LOOP_CONDITION_SYNTAX', 'E_APPLY_LOOP_CONDITION_SYNTAX'], -]) +] satisfies RefusalRule[]) /** * In `workflow.ts` on a field the edit set ({@link EditedBlocks.paramChanged}) of a block it @@ -108,7 +111,7 @@ const CHANGED_BLOCK_REFUSALS: ReadonlyMap = new Map([ */ const PARAM_REFUSALS: ReadonlyMap = new Map([ ['W_UNKNOWN_OPTION', 'E_APPLY_INVALID_SUBBLOCK_FIELD'], -]) +] satisfies RefusalRule[]) /** * In `workflow.ts` on a block the edit changed: a path no output of the block has, or a literal @@ -121,7 +124,7 @@ const ENTRY_REFUSALS: ReadonlyMap = new Map([ ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], ['W_UNKNOWN_BLOCK_TYPE', 'E_APPLY_INVALID_BLOCK_TYPE'], ['W_TYPE_NOT_ADDABLE', 'E_APPLY_TYPE_NOT_ADDABLE'], -]) +] satisfies RefusalRule[]) /** * In a function code file whose text the edit changed: a `$ref` naming no block or variable, or a @@ -132,23 +135,18 @@ const CODE_FILE_REFUSALS: ReadonlyMap = new Map([ ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], ['W_UNKNOWN_OUTPUT_PATH', 'E_APPLY_UNRESOLVED_REF'], ['W_CODE_FILE_REF_SYNTAX', 'E_APPLY_CODE_FILE_REF_SYNTAX'], -]) +] satisfies RefusalRule[]) /** * Every warning code {@link refuseEditedFindings} may refuse: the compile keeps one of each code, * block and file that its caps leave out (`CompileResult.withheld`), so a cap never hides a * refusal. */ -export const REFUSABLE_WARNING_CODES: ReadonlySet = new Set([ - 'W_UNKNOWN_OPTION', - 'W_REF_OUT_OF_SCOPE', - 'W_LOOP_CONDITION_SYNTAX', - 'W_UNKNOWN_OUTPUT_PATH', - 'W_UNRESOLVED_REF', - 'W_CODE_FILE_REF_SYNTAX', - 'W_UNKNOWN_BLOCK_TYPE', - 'W_TYPE_NOT_ADDABLE', -]) +export const REFUSABLE_WARNING_CODES: ReadonlySet = new Set( + [CHANGED_BLOCK_REFUSALS, PARAM_REFUSALS, ENTRY_REFUSALS, CODE_FILE_REFUSALS].flatMap((rules) => [ + ...rules.keys(), + ]) +) /** The rules' error codes with the warning each refuses, for help text. */ export const EDIT_REFUSALS: ReadonlyArray<{ diff --git a/packages/workflow-code/src/forms/subflow.ts b/packages/workflow-code/src/forms/subflow.ts index 0a4219429fe..27f51087858 100644 --- a/packages/workflow-code/src/forms/subflow.ts +++ b/packages/workflow-code/src/forms/subflow.ts @@ -7,7 +7,11 @@ * until its form is stated. */ -import { DEFAULT_LOOP_ITERATIONS, effectiveBatchSize } from '../canonicalize/subflows' +import { + DEFAULT_LOOP_ITERATIONS, + DEFAULT_PARALLEL_COUNT, + effectiveBatchSize, +} from '../canonicalize/subflows' import type { Json, LoopSpec, LoopType, ParallelSpec, ParallelType } from '../model' /** A spec's config fields: everything but its kind and type. */ @@ -40,9 +44,6 @@ type ConfigEntry = { /** A container type's config keys, in print order. */ export type ContainerForm = Readonly>> -/** `data.count || 5` in `convertParallelBlockToParallel`. */ -const DEFAULT_PARALLEL_COUNT = 5 - /** * The parallel type the executor runs when storage has none: the loader reads a missing * `parallelType` as `count` (`loadWorkflowFromNormalizedTablesRaw`). diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index ec06d063d2f..2d6eef61272 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -115,7 +115,7 @@ export type { } from './model' export { isResourceKind } from './model' export { assignIdentifiers, printWorkflow } from './print' -export { hasSuspiciousCharacter, printKey, quoteString } from './print/strings' +export { hasSuspiciousCharacter, printKey, printNumber, quoteString } from './print/strings' export { getOwn, invertRecord, parseJsonContainer, setOrDelete, setOwn } from './records' export { respondsOnEveryRun } from './responds' export { JS_RESERVED_WORDS, RESPONSE_OUTPUTS, SDK_CORE_EXPORTS } from './sdk' diff --git a/packages/workflow-code/src/limits.test.ts b/packages/workflow-code/src/limits.test.ts deleted file mode 100644 index 5108512a0bb..00000000000 --- a/packages/workflow-code/src/limits.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { utf8Bytes } from './limits' - -describe('utf8Bytes', () => { - it('counts the bytes UTF-8 encoding writes, a lone surrogate as U+FFFD', () => { - const cases: Array<[string, number]> = [ - ['a', 1], - ['é', 2], - ['中', 3], - ['😀', 4], - ['\uD800', 3], - ['\uDC00', 3], - ['\uD800a', 4], - ['\uD800é', 5], - ['\uD800中', 6], - ['\uD800𐀀', 7], - ] - for (const [text, bytes] of cases) expect(utf8Bytes(text)).toBe(bytes) - }) -}) diff --git a/packages/workflow-code/src/limits.ts b/packages/workflow-code/src/limits.ts index f3a8033d215..20697310094 100644 --- a/packages/workflow-code/src/limits.ts +++ b/packages/workflow-code/src/limits.ts @@ -1,3 +1,5 @@ +import { utf8ByteLength } from '@sim/utils/paste' + /** * The limits workflow source shares across reading and writing. A get refuses to print a workflow * over them, and compile, the source contracts and the apply body cap enforce the same numbers, so @@ -85,25 +87,6 @@ export interface SourceLimitExcess { max: number } -function isLowSurrogate(code: number): boolean { - return code >= 0xdc00 && code <= 0xdfff -} - -/** UTF-8 length of `text`, counting at most `cap + 1` bytes when a cap is given. */ -export function utf8Bytes(text: string, cap = Number.POSITIVE_INFINITY): number { - let bytes = 0 - for (let i = 0; i < text.length && bytes <= cap; i++) { - const code = text.charCodeAt(i) - if (code < 0x80) bytes += 1 - else if (code < 0x800) bytes += 2 - else if (code >= 0xd800 && code <= 0xdbff && isLowSurrogate(text.charCodeAt(i + 1))) { - bytes += 4 - i++ - } else bytes += 3 - } - return bytes -} - /** * Every size limit a printed source of a workflow with `counts` blocks, edges and variables * exceeds, in limit order; empty when it fits. Depth is `sourceDepthOverflow`'s. @@ -131,7 +114,7 @@ export function sourceLimitExcesses( excesses.push({ limit: 'maxFiles', actual: paths.length, max: SOURCE_LIMITS.maxFiles }) } let total = 0 - for (const path of paths) total += utf8Bytes(files[path]) + for (const path of paths) total += utf8ByteLength(files[path]) if (total > SOURCE_LIMITS.maxTotalBytes) { excesses.push({ limit: 'maxTotalBytes', actual: total, max: SOURCE_LIMITS.maxTotalBytes }) } diff --git a/packages/workflow-code/vitest.config.ts b/packages/workflow-code/vitest.config.ts index 6f729af4c84..670f3ea5a37 100644 --- a/packages/workflow-code/vitest.config.ts +++ b/packages/workflow-code/vitest.config.ts @@ -6,6 +6,12 @@ export default mergeConfig( defineConfig({ test: { include: ['src/**/*.test.ts'], + /** + * The scaling cases (`expectLinearGrowth`) bound a ratio so a slow runner cannot fail them, + * but near the source caps they take seconds of wall clock, which vitest's 5s default turns + * back into a wall-clock budget under machine load. + */ + testTimeout: 30_000, }, }) ) diff --git a/packages/workflow-sdk/README.md b/packages/workflow-sdk/README.md index 6966af6e1dd..af0c4d36f83 100644 --- a/packages/workflow-sdk/README.md +++ b/packages/workflow-sdk/README.md @@ -23,9 +23,9 @@ have the CLI confirm the directory holds that workflow. 2. **Edit** `workflow.ts`. Declare blocks with `const x = builder('Name', params)` and wire them with `x.to(y)`. Then run `sim workflows source check --dir ./wf`: it compiles with the server's compiler against the cached catalog, without a request, in milliseconds, and catches what `tsc` - cannot (duplicate names, cycles, literal secrets). It exits 1 on errors and on a missing - required field, an unknown option or output path, a wrong value kind, an out-of-range value or - a literal secret in a block the lock does not bind yet (`--strict`: in every block; `--no-strict`: never on a + cannot (duplicate names, cycles, literal secrets). It exits 1 on errors and on the warnings + `sim workflows source check --help` lists (a missing required field, an unknown option, a + literal secret and more) in a block the lock does not bind yet (`--strict`: in every block; `--no-strict`: never on a warning). It also adds the blocks the source now uses to `tsconfig.json`. Then always run `bunx -p typescript@7.0.2 tsc -p ./wf` after an edit and fix what it reports: it takes about a second and catches what check and the dry run do not, such as a reference to a start input the @@ -71,7 +71,7 @@ command with `--yes` to write it. `--dry-run` never asks. | `.sim/sdk/blocks/{type}.d.ts` | One block type's builders with their params and outputs, for the blocks the source uses and the core builders' (`check` adds a block an edit starts using). `sim workflows source params` prints one builder rather than a file whole. | | `.sim/sdk/index.d.ts` | Names the catalog and generator the declarations come from, and imports the blocks the directory holds. | | `~/.sim/cache/source-catalog//sdk-/` | Every block's declarations and the full `INDEX.md`, generated once per catalog and shared by every directory; `tsconfig.full.json` includes its `index.d.ts` (every current block). | -| `.sim/sdk/workspace.d.ts` | This workspace's tables (with columns), knowledge bases, credentials, workflows (with inputs), skills, custom tools and env var names, so `table('tickets')`, `credential('support-slack')`, `skill('triage')` and `env.X` are checked. | +| `.sim/sdk/workspace.d.ts` | This workspace's tables (with columns), knowledge bases, credentials, workflows (with inputs), skills, custom tools, MCP servers (with tools) and env var names, so `table('tickets')`, `credential('support-slack')`, `skill('triage')` and `env.X` are checked. | | `tsconfig.json` | Resolves `@sim/workflow-sdk` to `.sim/sdk` and type-checks `workflow.ts` with the blocks it uses (from the source and the server's `blockTypes`) and the core builders' blocks: a few dozen files for `tsc` instead of every block. | | `tsconfig.full.json` | The same with every current block (the cached index, an absolute path on this machine), plus any legacy-only block the workflow uses. | | `.sim/AGENTS.md` | The authoring guide for agents: the primer `get` prints (edit loop, identity, references, deletes, deploy, exit codes, and a snippet for each builder the source calls), then a reference linking [the docs](https://docs.sim.ai/workflows/code). A top-level `AGENTS.md` of your own is never touched. | diff --git a/packages/workflow-sdk/scripts/generate-embedded-text.ts b/packages/workflow-sdk/scripts/generate-embedded-text.ts index 7df5fb29dba..0e6050c8f0f 100644 --- a/packages/workflow-sdk/scripts/generate-embedded-text.ts +++ b/packages/workflow-sdk/scripts/generate-embedded-text.ts @@ -5,8 +5,7 @@ * `cookbook/examples/*.ts` as `COOKBOOK_EXAMPLES` (the example workflows), the workspace declaration SDK * `src/workspace/*.d.ts` as `WORKSPACE_SDK_DTS`, and the example workspace directory * `cookbook/workspace/**` as `WORKSPACE_COOKBOOK`. The output is written as generated (biome - * skips these files), so `--check` compares it byte for byte; `core-text.test.ts`, - * `cookbook-text.test.ts` and `workspace-text.test.ts` also fail when any drifts. + * skips these files), so `--check` (run by `check:audits`) compares it byte for byte. * * bun run generate:workflow-sdk-embedded-text * bun run check:workflow-sdk-embedded-text diff --git a/packages/workflow-sdk/src/codegen/cookbook-text.test.ts b/packages/workflow-sdk/src/codegen/cookbook-text.test.ts deleted file mode 100644 index cd869879f6e..00000000000 --- a/packages/workflow-sdk/src/codegen/cookbook-text.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { readdirSync, readFileSync } from 'node:fs' -import path from 'node:path' -import { describe, expect, it } from 'vitest' -import { COOKBOOK_EXAMPLES } from './cookbook-text.generated' - -describe('COOKBOOK_EXAMPLES', () => { - it('matches cookbook/examples, so bundled consumers never write a stale example', () => { - const dir = path.join(import.meta.dirname, '..', '..', 'cookbook', 'examples') - const files = readdirSync(dir).filter((file) => file.endsWith('.ts')) - expect( - Object.fromEntries(files.map((file) => [file, readFileSync(path.join(dir, file), 'utf8')])) - ).toEqual(COOKBOOK_EXAMPLES) - }) -}) diff --git a/packages/workflow-sdk/src/codegen/core-text.test.ts b/packages/workflow-sdk/src/codegen/core-text.test.ts deleted file mode 100644 index 8b88bf2d89a..00000000000 --- a/packages/workflow-sdk/src/codegen/core-text.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { readFileSync } from 'node:fs' -import path from 'node:path' -import { describe, expect, it } from 'vitest' -import { CORE_DTS } from './core-text.generated' - -describe('CORE_DTS', () => { - it('matches src/core.d.ts, so bundled consumers never write stale declarations', () => { - const source = readFileSync(path.join(import.meta.dirname, '..', 'core.d.ts'), 'utf8') - expect(CORE_DTS).toBe(source) - }) -}) diff --git a/packages/workflow-sdk/src/codegen/embedded-files.test.ts b/packages/workflow-sdk/src/codegen/embedded-files.test.ts new file mode 100644 index 00000000000..20d1dfb4421 --- /dev/null +++ b/packages/workflow-sdk/src/codegen/embedded-files.test.ts @@ -0,0 +1,26 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { describe, expect, it } from 'vitest' +import { embeddedFolderTexts } from './embedded-files' + +describe('embeddedFolderTexts', () => { + it('never embeds a dotfile or a file under a dot folder', () => { + const dir = mkdtempSync(path.join(tmpdir(), 'embedded-')) + try { + mkdirSync(path.join(dir, 'tables')) + mkdirSync(path.join(dir, '.git')) + writeFileSync(path.join(dir, 'secrets.ts'), 'a') + writeFileSync(path.join(dir, 'tables', 'plans.ts'), 'b') + writeFileSync(path.join(dir, '.DS_Store'), 'c') + writeFileSync(path.join(dir, 'tables', '.plans.ts.swp'), 'd') + writeFileSync(path.join(dir, '.git', 'HEAD'), 'e') + expect(embeddedFolderTexts(dir, { recursive: true, include: () => true })).toEqual({ + 'secrets.ts': 'a', + 'tables/plans.ts': 'b', + }) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/workflow-sdk/src/codegen/generate.ts b/packages/workflow-sdk/src/codegen/generate.ts index 9cc59794e5d..a6291fd5ff6 100644 --- a/packages/workflow-sdk/src/codegen/generate.ts +++ b/packages/workflow-sdk/src/codegen/generate.ts @@ -526,7 +526,7 @@ export function builderTypes(catalog: BlockCatalog, entry: BuilderEntry): Builde } function stripComments(text: string): string { - return text.replace(/\/\*\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '') + return text.replace(/\/\*\*[\s\S]*?\*\//g, '').replace(/^[ \t]*\/\/.*$/gm, '') } function coreImports(text: string): string { diff --git a/packages/workflow-sdk/src/codegen/tsconfig.test.ts b/packages/workflow-sdk/src/codegen/tsconfig.test.ts new file mode 100644 index 00000000000..fde04fda69e --- /dev/null +++ b/packages/workflow-sdk/src/codegen/tsconfig.test.ts @@ -0,0 +1,10 @@ +import { createRequire } from 'node:module' +import { describe, expect, it } from 'vitest' +import { typecheckCommand } from './tsconfig' + +describe('typecheckCommand', () => { + it('runs the TypeScript release this repository type-checks the generated declarations with', () => { + const { version } = createRequire(import.meta.url)('typescript/package.json') + expect(typecheckCommand()).toBe(`bunx -p typescript@${version} tsc -p .`) + }) +}) diff --git a/packages/workflow-sdk/src/codegen/workspace-text.test.ts b/packages/workflow-sdk/src/codegen/workspace-text.test.ts deleted file mode 100644 index 3a6105eb05c..00000000000 --- a/packages/workflow-sdk/src/codegen/workspace-text.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import path from 'node:path' -import { describe, expect, it } from 'vitest' -import { embeddedFolderTexts } from './embedded-files' -import { WORKSPACE_COOKBOOK } from './workspace-cookbook-text.generated' -import { WORKSPACE_SDK_DTS } from './workspace-text.generated' - -describe('WORKSPACE_SDK_DTS', () => { - it('matches src/workspace/*.d.ts, so bundled consumers never write stale declarations', () => { - const dir = path.join(import.meta.dirname, '..', 'workspace') - const files = Object.fromEntries( - readdirSync(dir) - .filter((name) => name.endsWith('.d.ts')) - .map((name) => [name, readFileSync(path.join(dir, name), 'utf8')]) - ) - expect(WORKSPACE_SDK_DTS).toEqual(files) - }) - - it('matches cookbook/workspace, so bundled consumers never write a stale example', () => { - const dir = path.join(import.meta.dirname, '..', '..', 'cookbook', 'workspace') - const files = embeddedFolderTexts(dir, { recursive: true, include: () => true }) - expect(WORKSPACE_COOKBOOK).toEqual(files) - }) - - it('never embeds a dotfile or a file under a dot folder', () => { - const dir = mkdtempSync(path.join(tmpdir(), 'embedded-')) - try { - mkdirSync(path.join(dir, 'tables')) - mkdirSync(path.join(dir, '.git')) - writeFileSync(path.join(dir, 'secrets.ts'), 'a') - writeFileSync(path.join(dir, 'tables', 'plans.ts'), 'b') - writeFileSync(path.join(dir, '.DS_Store'), 'c') - writeFileSync(path.join(dir, 'tables', '.plans.ts.swp'), 'd') - writeFileSync(path.join(dir, '.git', 'HEAD'), 'e') - expect(embeddedFolderTexts(dir, { recursive: true, include: () => true })).toEqual({ - 'secrets.ts': 'a', - 'tables/plans.ts': 'b', - }) - } finally { - rmSync(dir, { recursive: true, force: true }) - } - }) -}) diff --git a/packages/workflow-sdk/src/diagnostics-table.test.ts b/packages/workflow-sdk/src/diagnostics-table.test.ts new file mode 100644 index 00000000000..55dda36ba61 --- /dev/null +++ b/packages/workflow-sdk/src/diagnostics-table.test.ts @@ -0,0 +1,18 @@ +import { readFileSync } from 'node:fs' +import path from 'node:path' +import { DIAGNOSTIC_CODES } from '@sim/workflow-code/diagnostics/codes' +import { describe, expect, it } from 'vitest' + +describe('the Diagnostics table the README points at', () => { + it('has a SYNTAX.md row for every diagnostic code, and names no other code', () => { + const syntax = readFileSync( + path.join(import.meta.dirname, '../../workflow-code/src/compile/SYNTAX.md'), + 'utf8' + ) + const firstCells = [...syntax.matchAll(/^\| (`[EWI]_[A-Z_]+`(?:, `[EWI]_[A-Z_]+`)*) \|/gm)] + const documented = firstCells.flatMap(([, cell]) => + cell.split(', ').map((code) => code.slice(1, -1)) + ) + expect(new Set(documented)).toEqual(new Set(DIAGNOSTIC_CODES)) + }) +}) diff --git a/packages/workspace-code/DESIGN.md b/packages/workspace-code/DESIGN.md index d462e7d66b1..6ab1a06c3a9 100644 --- a/packages/workspace-code/DESIGN.md +++ b/packages/workspace-code/DESIGN.md @@ -299,7 +299,8 @@ blobs its writes need against the staging area once, before any write: a missing staged, expired, or staged at another size) refuses the whole apply with `E_BLOB_MISSING`, and a dry run lists such paths in `needBlobs` instead. Writes then read each blob from staging one at a time (rechecking its hash). An apply never deletes what it read: staged blobs are reclaimed only -by expiry, a day after their last use (staging, asking for, or planning with them). Deleting them +by expiry, a day after each was last staged (asking for or planning with a blob never extends +it). Deleting them when an apply finished would take bytes from a concurrent apply by the same caller that planned with the same blob and has not written it yet, and no point in an apply can tell that no other one still needs them; leaving them also means a retry, or the next apply of the same bytes, uploads @@ -308,7 +309,7 @@ nothing. The server plans once per apply, whatever the directory's size. Staging (`apps/sim/lib/workspace-source/staging/store.ts`, use cases in `application/stage-blobs.ts`) is scoped to the workspace and the caller (a person's credentials share one scope; a workspace API key has its own), capped per scope at `maxStagedBlobs` and -`maxStagedBytes`, and expires a day after a blob was last staged, asked for or planned with; an +`maxStagedBytes`, and expires a day after a blob was last staged; an hourly cron (`/api/cron/cleanup-source-staging`) deletes expired rows and objects. Both staging calls need write access, as the apply does, and draw on their own rate bucket. A manifest entry never carries bytes: the contract refuses `blobs[].content`. @@ -405,8 +406,8 @@ refusal until a migration is written. `WorkspaceManifest`, and `env.NAME` and `credential('k')` from `secrets.ts` and `credentials.ts` live, through `typeof import(...)`, so a declared but unapplied entry type-checks). The CLI embeds them through - `packages/workflow-sdk/scripts/generate-embedded-text.ts`; the `*-text.test.ts` drift tests fail - until it is re-run. + `packages/workflow-sdk/scripts/generate-embedded-text.ts`; `check:workflow-sdk-embedded-text` + fails until it is re-run. - The CLI side is `packages/sim-cli/src/commands/protocol/workspace-source-*.ts`. `workspace-source-dir.ts` writes the directory's `tsconfig.json` (`workspaceTsconfig`), the agent guide (`AGENTS_GUIDE`) and the local declarations a get types (`localDeclarations`). diff --git a/packages/workspace-code/src/declaration/print.ts b/packages/workspace-code/src/declaration/print.ts index d33eb153b7e..72a6de544ab 100644 --- a/packages/workspace-code/src/declaration/print.ts +++ b/packages/workspace-code/src/declaration/print.ts @@ -5,7 +5,7 @@ * short and flat), so printing the same value twice gives the same bytes. */ import { compareStrings } from '@sim/utils/string' -import { type Json, printKey, quoteString } from '@sim/workflow-code' +import { type Json, printKey, printNumber, quoteString } from '@sim/workflow-code' import { CALL_KEY, DECLARATION_SDK_MAJOR, @@ -18,11 +18,6 @@ import { /** Lines no longer than this print a short, flat object or array on one line. */ const INLINE_WIDTH = 80 -/** A JSON number as a numeric literal (`String(n)` minus the exponent `+`). */ -function printNumber(value: number): string { - return String(value).replace('e+', 'e') -} - /** A helper call node for {@link printDeclaration}: `call('column.string', { required: true })`. */ export function call(name: string, ...args: Json[]): Json { return { [CALL_KEY]: name, args } diff --git a/packages/workspace-code/src/declaration/read.ts b/packages/workspace-code/src/declaration/read.ts index 78274de023f..97ed086b335 100644 --- a/packages/workspace-code/src/declaration/read.ts +++ b/packages/workspace-code/src/declaration/read.ts @@ -17,6 +17,7 @@ import { type ParserOptions, parse } from '@babel/parser' import type { Expression, Node, ObjectExpression } from '@babel/types' import { isRecordLike } from '@sim/utils/object' +import { utf8ByteLength } from '@sim/utils/paste' import { containsNulCharacter, toWellFormed } from '@sim/utils/string' import { babelErrorShape, @@ -27,7 +28,6 @@ import { type SourceSpan, sdkHeader, } from '@sim/workflow-code' -import { utf8Bytes } from '@sim/workflow-code/limits' import { diagnostic, findingLimitReached, @@ -167,7 +167,7 @@ export function readDeclaration( const nodeAt = (node: Node) => at(node.start ?? 0, node.end ?? node.start ?? 0) const fail = (): ReadDeclaration => ({ spans, diagnostics }) - const bytes = utf8Bytes(text, WORKSPACE_SOURCE_LIMITS.maxDeclarationBytes) + const bytes = utf8ByteLength(text, WORKSPACE_SOURCE_LIMITS.maxDeclarationBytes) if (bytes > WORKSPACE_SOURCE_LIMITS.maxDeclarationBytes) { diagnostics.push( diagnostic( diff --git a/packages/workspace-code/src/kinds/files.ts b/packages/workspace-code/src/kinds/files.ts index 98563cab2be..71c6601c49d 100644 --- a/packages/workspace-code/src/kinds/files.ts +++ b/packages/workspace-code/src/kinds/files.ts @@ -6,8 +6,8 @@ * A path is refused when no workspace file could hold it or when two paths would land on one file * on a case-insensitive disk, so a directory always round-trips through a get on any machine. */ +import { utf8ByteLength } from '@sim/utils/paste' import { hasSuspiciousCharacter, type Json } from '@sim/workflow-code' -import { utf8Bytes } from '@sim/workflow-code/limits' import type { ResourceFingerprint } from '../base' import { diagnostic, @@ -51,7 +51,7 @@ export function filePathProblem(key: string): string | null { if (segment.startsWith('.')) return `"${segment}" starts with a dot` if (/[ .]$/.test(segment)) return `"${segment}" ends with a space or a dot` if (RESERVED_NAME.test(segment)) return `"${segment}" is a reserved device name` - if (utf8Bytes(segment) > MAX_SEGMENT_BYTES) { + if (utf8ByteLength(segment) > MAX_SEGMENT_BYTES) { return `"${segment.slice(0, 32)}…" is over ${MAX_SEGMENT_BYTES} bytes` } } diff --git a/packages/workspace-code/src/kinds/table-rows.ts b/packages/workspace-code/src/kinds/table-rows.ts index fecda4e0e58..cd62f5a3342 100644 --- a/packages/workspace-code/src/kinds/table-rows.ts +++ b/packages/workspace-code/src/kinds/table-rows.ts @@ -20,9 +20,9 @@ */ import { isRecordLike } from '@sim/utils/object' +import { utf8ByteLength } from '@sim/utils/paste' import { compareStrings } from '@sim/utils/string' import type { Json } from '@sim/workflow-code' -import { utf8Bytes } from '@sim/workflow-code/limits' import type { ResourceFingerprint } from '../base' import { diagnostic, @@ -76,7 +76,7 @@ export function hasRowKey(row: TableRowCells, rowKey: string): boolean { /** The UTF-8 bytes `row` takes as one line of a rows file, its newline included. */ export function printedRowBytes(row: TableRowCells): number { - return utf8Bytes(JSON.stringify(filledCells(row))) + 1 + return utf8ByteLength(JSON.stringify(filledCells(row))) + 1 } /** A row without its empty cells (null, `''` and `[]`, which a table stores as no value). */ diff --git a/packages/workspace-code/src/status.test.ts b/packages/workspace-code/src/status.test.ts index c87d0141455..125bbe6b812 100644 --- a/packages/workspace-code/src/status.test.ts +++ b/packages/workspace-code/src/status.test.ts @@ -1,6 +1,6 @@ import { expectLinearGrowth } from '@sim/testing/helpers/scaling' import { describe, expect, it } from 'vitest' -import { localResourceChanges } from './status' +import { localResourceChanges, sourceStatus } from './status' function changedFiles(count: number) { return Array.from({ length: count }, (_, index) => ({ @@ -19,3 +19,36 @@ describe('localResourceChanges', () => { expectLinearGrowth(grouped, 10_000) }) }) + +describe('sourceStatus', () => { + it('meets many server changes with many local files in linear time', () => { + const local = localResourceChanges([ + ...changedFiles(100), + { path: 'secrets.ts', change: 'edited' as const }, + ]) + expect( + sourceStatus(local, [ + { kind: 'file', key: 'f7.txt', server: 'changed' }, + { kind: 'file', key: 'gone.txt', server: 'deleted' }, + { kind: 'secret', key: 'API_KEY', server: 'changed' }, + ]) + ).toMatchObject({ + state: 'conflict', + conflicts: [ + { key: 'f7.txt', change: 'created' }, + { kind: 'secret', key: 'API_KEY', change: 'edited' }, + ], + drift: [{ key: 'gone.txt' }], + }) + const met = (count: number) => { + const files = localResourceChanges(changedFiles(count)) + const server = Array.from({ length: count }, (_, index) => ({ + kind: 'file' as const, + key: `other${index}.txt`, + server: 'changed' as const, + })) + return () => sourceStatus(files, server) + } + expectLinearGrowth(met, 2_000) + }) +}) diff --git a/packages/workspace-code/src/status.ts b/packages/workspace-code/src/status.ts index 49cabfa88c4..f270be31672 100644 --- a/packages/workspace-code/src/status.ts +++ b/packages/workspace-code/src/status.ts @@ -178,12 +178,19 @@ export function sourceStatus( local: readonly LocalResourceChange[], server: readonly ServerResourceChange[] ): SourceStatus { + const firstOfResource = new Map() + const firstOfKind = new Map() + for (const entry of local) { + const address = `${entry.kind}:${entry.key}` + if (!firstOfResource.has(address)) firstOfResource.set(address, entry) + if (!firstOfKind.has(entry.kind)) firstOfKind.set(entry.kind, entry) + } const conflicts: ConflictingChange[] = [] const drift: ServerResourceChange[] = [] for (const change of server) { - const mine = local.find( - (entry) => entry.kind === change.kind && (entry.key === change.key || isFileKind(entry.kind)) - ) + const mine = isFileKind(change.kind) + ? firstOfKind.get(change.kind) + : firstOfResource.get(`${change.kind}:${change.key}`) if (mine) conflicts.push({ ...change, change: mine.change }) else drift.push(change) } diff --git a/scripts/check-unused-exports.baseline.json b/scripts/check-unused-exports.baseline.json index 6d07c816224..c842f94dd39 100644 --- a/scripts/check-unused-exports.baseline.json +++ b/scripts/check-unused-exports.baseline.json @@ -5808,8 +5808,6 @@ "packages/sim-cli/src/commands/protocol/logs-follow.ts#FollowStatus", "packages/sim-cli/src/commands/protocol/logs-follow.ts#MAX_CELL_WIDTH", "packages/sim-cli/src/commands/protocol/logs-follow.ts#followStatus", - "packages/sim-cli/src/commands/protocol/workflow-run-follow.ts#CommentaryWriter", - "packages/sim-cli/src/commands/protocol/workflow-run-follow.ts#resolveWorkflowRunSelection", "packages/sim-cli/src/commands/search.ts#searchCommand", "packages/sim-cli/src/config/index.ts#DEFAULT_ENDPOINT", "packages/sim-cli/src/config/index.ts#PROFILE_NAME_PATTERN", @@ -5895,6 +5893,5 @@ "packages/sim-setup/src/setup-status.ts#SetupStatusSource", "packages/sim-setup/src/twins.ts#getConfiguredMailProvider", "packages/sim-setup/src/wizard.ts#WizardMode", - "packages/utils/src/timezone.ts#getSupportedTimezones", "packages/workflow-renderer/src/note/search-highlight.ts#NOTE_SEARCH_MARK_INDEX_PROPERTY" ]