/** * Generates the reference tables of the workflows-as-code docs from the code that owns them, so * the exit codes, diagnostic codes and limits a reader looks up can never drift from the CLI and * the engines: * * - `exit-codes`: `sourceExitCodeRows` (`packages/sim-cli/.../source-exit-codes.ts`), the one * table `--help`, the generated CLI pages and `.sim/AGENTS.md` are already built from. * - `diagnostics`: the Diagnostics tables of `packages/workflow-code/src/compile/SYNTAX.md` * (workflow codes) and the TSDoc of each code in `packages/workspace-code/src/diagnostics/codes.ts` * (workspace codes), each set required to equal the code list the engines export. * - `directory-kinds`: the one line per resource kind (`WORKSPACE_KIND_SPECS[kind].guide`) that the * workspace directory's `.sim/AGENTS.md` prints. * - `limits`: `SOURCE_LIMITS` and `WORKSPACE_SOURCE_LIMITS`. The values come from code; the label of * each limit is authored here, and every limit must have one. * * Content is rewritten between the `workflow-code-docs:` markers of the pages under * `apps/docs/content/docs/workflows/code/`. The check also fails on a diagnostic code a page * names that no engine emits, on a `typescript@x.y.z` pin in the docs other than the release * the CLI type-checks a directory with, and on a `troubleshooting.mdx` without exactly one * `[#exit-]` section per non-zero code `sourceExitCodeRows` lists. * * Usage: * bun run scripts/sync-workflow-code-docs.ts # write * bun run scripts/sync-workflow-code-docs.ts --check # fail on drift */ import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { compareStrings } from '@sim/utils/string' import { type SourceCommandGroup, sourceExitCodeRows, } from '../packages/sim-cli/src/commands/protocol/source-exit-codes' import { DIAGNOSTIC_CODES } from '../packages/workflow-code/src/diagnostics/codes' import { SOURCE_LIMITS } from '../packages/workflow-code/src/limits' import { SOURCE_TYPESCRIPT_VERSION } from '../packages/workflow-sdk/src/codegen/tsconfig' import { WORKSPACE_DIAGNOSTIC_CODES } from '../packages/workspace-code/src/diagnostics/codes' import { APPLY_ORDER } from '../packages/workspace-code/src/kind' import { WORKSPACE_SOURCE_LIMITS } from '../packages/workspace-code/src/limits' import { WORKSPACE_KIND_SPECS } from '../packages/workspace-code/src/specs' const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') const DOCS_DIR = path.join(rootDir, 'apps/docs/content/docs') const PAGES_DIR = path.join(DOCS_DIR, 'workflows/code') const SYNTAX_PATH = path.join(rootDir, 'packages/workflow-code/src/compile/SYNTAX.md') const WORKSPACE_CODES_PATH = path.join(rootDir, 'packages/workspace-code/src/diagnostics/codes.ts') const REGIONS = { 'exit-codes': 'exit-codes.mdx', diagnostics: 'diagnostics.mdx', limits: 'limits.mdx', 'directory-kinds': 'directory.mdx', } as const type Region = keyof typeof REGIONS const beginMarker = (region: Region) => `{/* workflow-code-docs:${region}:begin — generated by \`bun run generate:workflow-code-docs\`; do not edit between markers */}` const endMarker = (region: Region) => `{/* workflow-code-docs:${region}:end */}` /** Text safe for MDX prose: braces and angle brackets escaped outside code spans. */ function mdx(text: string): string { return text .split(/(`[^`]*`)/) .map((part, index) => index % 2 === 1 ? part : part.replaceAll('{', '\\{').replaceAll('}', '\\}').replaceAll('<', '<') ) .join('') } /** A TSDoc body as one line of prose: `{@link X}` becomes `X`, a hard wrap becomes a space. */ function tsdocText(lines: string[]): string { return lines .map((line) => line.replace(/^\s*\*\s?/, '').trim()) .filter(Boolean) .join(' ') .replace(/\{@link ([^}]+)\}/g, '`$1`') .trim() } function cell(text: string): string { return mdx(text.replaceAll('\n', ' ')).replaceAll('|', '\\|') } const SOURCE_GROUPS: readonly SourceCommandGroup[] = [ 'sim workflows source', 'sim workspaces source', ] const indent = (block: string, spaces: number) => block .split('\n') .map((line) => (line ? ' '.repeat(spaces) + line : line)) .join('\n') function exitCodeTable(group: SourceCommandGroup): string { return [ '| Code | Meaning | What to do |', '| --- | --- | --- |', ...sourceExitCodeRows(group).map( ({ code, meaning, next }) => `| \`${code}\` | ${cell(meaning)} | ${cell(next)} |` ), ].join('\n') } function buildExitCodes(): string { return [ '', "", ' ', '', indent(exitCodeTable(SOURCE_GROUPS[0]), 4), '', ' ', ' ', '', indent(exitCodeTable(SOURCE_GROUPS[1]), 4), '', ' ', '', '', ].join('\n') } interface DiagnosticRow { codes: string[] meaning: string } interface DiagnosticGroup { title: string note: string rows: DiagnosticRow[] } /** The groups of the Diagnostics section of SYNTAX.md: a bold title, then a table of code rows. */ function parseWorkflowDiagnostics(): DiagnosticGroup[] { const syntax = fs.readFileSync(SYNTAX_PATH, 'utf8') const start = syntax.indexOf('\n## Diagnostics') if (start === -1) throw new Error('SYNTAX.md has no "## Diagnostics" section') const groups: DiagnosticGroup[] = [] let heading: string[] | null = null let current: DiagnosticGroup | null = null for (const line of syntax.slice(start).split('\n').slice(2)) { if (line.startsWith('**')) { heading = [line] continue } if (heading && line.trim() !== '') { heading.push(line) continue } if (heading) { const text = heading.join(' ') const match = /^\*\*(.+?)\*\*\s*(.*)$/.exec(text) if (!match) throw new Error(`Cannot read the SYNTAX.md diagnostics heading: ${text}`) current = { title: match[1], note: match[2].replace(/^\((.*)\)$/, '$1'), rows: [] } groups.push(current) heading = null continue } const row = /^\| (`[EWI]_[A-Z0-9_]+`(?:, `[EWI]_[A-Z0-9_]+`)*) \| (.*) \|$/.exec(line) if (row && current) { current.rows.push({ codes: row[1].split(', ').map((code) => code.slice(1, -1)), meaning: row[2].replaceAll('\\|', '|'), }) } } return groups } interface WorkspaceCodeGroup { title: string rows: DiagnosticRow[] } /** * The `const X_CODES = [...]` arrays of the workspace codes file: the TSDoc above an array is the * group's title and the TSDoc above each string is that code's meaning. */ function parseWorkspaceDiagnostics(): { groups: WorkspaceCodeGroup[]; undocumented: string[] } { const lines = fs.readFileSync(WORKSPACE_CODES_PATH, 'utf8').split('\n') const groups: WorkspaceCodeGroup[] = [] const undocumented: string[] = [] let doc: string[] = [] let inDoc = false let groupTitle: string | null = null let current: WorkspaceCodeGroup | null = null let sharedLine = false for (const line of lines) { const trimmed = line.trim() if (inDoc) { if (trimmed.endsWith('*/')) { inDoc = false const body = trimmed.replace(/\*\/$/, '').trim() if (body && body !== '*') doc.push(body) } else doc.push(trimmed) continue } if (trimmed.startsWith('/**')) { doc = [] const rest = trimmed.replace(/^\/\*\*/, '') if (rest.endsWith('*/')) doc.push(rest.replace(/\*\/$/, '').trim()) else { inDoc = true if (rest.trim()) doc.push(rest.trim()) } continue } const arrayStart = /^const ([A-Z_]+_CODES) = \[/.exec(trimmed) if (arrayStart) { sharedLine = arrayStart[1] === 'SHARED_CODES' || arrayStart[1] === 'OWN_CODES' current = null if (!sharedLine) { groupTitle = tsdocText(doc).replace(/\.$/, '') current = { title: groupTitle, rows: [] } groups.push(current) } doc = [] continue } if (trimmed.startsWith(']')) { current = null continue } const code = /^'([EWI]_[A-Z0-9_]+)',?$/.exec(trimmed) if (code && current) { const meaning = tsdocText(doc) if (!meaning) undocumented.push(code[1]) current.rows.push({ codes: [code[1]], meaning }) doc = [] } else if (trimmed !== '' && !trimmed.startsWith('//')) { doc = [] } } return { groups, undocumented } } const codeCell = (codes: string[]) => codes.map((code) => `\`${code}\``).join(', ') function diagnosticTable(rows: DiagnosticRow[]): string { return [ '| Code | Meaning |', '| --- | --- |', ...rows.map(({ codes, meaning }) => `| ${codeCell(codes)} | ${cell(meaning)} |`), ].join('\n') } const WORKFLOW_GROUP_LEAD: Record = { 'Compile and print': 'Reading and writing `workflow.ts`.', 'Lock and source meta': 'Reading `.sim/lock.json`. Each finding names a JSON `path`.', Canonicalize: 'Reading the stored workflow in a get.', Materialize: 'Matching the compiled file to the stored blocks.', Apply: 'Saving the workflow draft.', 'Type check': '`sim workflows source check` and `sim workspaces source check` type-checking the directory with TypeScript after the compile. The server never reports these.', } /** One error per code `documented` names that `exported` does not hold, and per code it lacks. */ function codeDiff( what: string, documented: readonly string[], exported: readonly string[] ): string[] { const have = new Set(documented) const want = new Set(exported) const extra = documented.filter((code) => !want.has(code)) const missing = exported.filter((code) => !have.has(code)) return [ ...(extra.length ? [`${what} names codes no engine emits: ${extra.join(', ')}`] : []), ...(missing.length ? [`${what} has no entry for: ${missing.join(', ')}`] : []), ] } function buildDiagnostics(errors: string[]): string { const workflow = parseWorkflowDiagnostics() const workflowRows = workflow.flatMap((group) => group.rows) const workflowMeaning = new Map( workflowRows.flatMap((row) => row.codes.map((code) => [code, row.meaning])) ) errors.push(...codeDiff('SYNTAX.md Diagnostics', [...workflowMeaning.keys()], DIAGNOSTIC_CODES)) const { groups: workspace, undocumented } = parseWorkspaceDiagnostics() if (undocumented.length) errors.push( `workspace-code/src/diagnostics/codes.ts has no TSDoc for: ${undocumented.join(', ')}` ) const ownCodes = new Set(workspace.flatMap((group) => group.rows.flatMap((row) => row.codes))) const exportedWorkspace: readonly string[] = WORKSPACE_DIAGNOSTIC_CODES errors.push( ...codeDiff( 'workspace-code code arrays', [...ownCodes], exportedWorkspace.filter((code) => ownCodes.has(code) || !workflowMeaning.has(code)) ) ) const shared: DiagnosticRow[] = exportedWorkspace .filter((code) => !ownCodes.has(code)) .map((code) => ({ codes: [code], meaning: workflowMeaning.get(code) ?? '' })) const lines: string[] = ['', '### Workflow source', ''] for (const group of workflow) { lines.push(`#### ${group.title}`, '') const lead = WORKFLOW_GROUP_LEAD[group.title] const note = lead ?? (group.note ? `${group.note}.` : '') if (!lead) errors.push(`No lead sentence for the diagnostics group "${group.title}"`) if (note) lines.push(mdx(note), '') lines.push(diagnosticTable(group.rows), '') } lines.push('### Workspace source', '') lines.push( 'Workspace source reports every workflow code above for the files of `workflows//`, with that path as the file, and these codes for the rest of the directory.', '' ) for (const group of workspace) { lines.push(`#### ${mdx(group.title)}`, '', diagnosticTable(group.rows), '') } lines.push( '#### Shared with workflow source', '', 'A workspace finding with the same meaning as a workflow finding uses its code.', '', diagnosticTable(shared), '' ) return lines.join('\n') } function buildDirectoryKinds(): string { return ['', ...APPLY_ORDER.map((kind) => `- ${mdx(WORKSPACE_KIND_SPECS[kind].guide)}`), ''].join( '\n' ) } /** The label of each limit in the docs. A limit added to code without one fails the check. */ const WORKFLOW_LIMIT_LABELS: Record = { maxBlocks: 'Blocks in one workflow', maxEdges: 'Connections (edges) in one workflow', maxVariables: 'Variables in one workflow', maxFiles: 'Files in one source: `workflow.ts` plus one function file per block', maxTotalBytes: 'Bytes of all files together, `workflow.ts` and function files', maxDepth: 'Nesting depth of `workflow.ts`, and of each JavaScript function file', } const WORKSPACE_LIMIT_LABELS: Record = { maxResourcesPerKind: 'Resources of one kind in one directory', maxDeclarationBytes: 'Bytes of every declaration file together, workflow files excluded', maxWorkflows: 'Edited workflows one apply sends', maxWorkflowBytes: 'Bytes of every workflow file one apply sends', maxDirectoryWorkflowBytes: 'Bytes of every workflow file one get writes; a workflow past it is left out', maxChanges: 'Changes one apply makes, no-ops excluded', maxTableRows: 'Rows in one `tables/.rows.jsonl`', maxRowsBytes: 'Bytes of every rows file together', maxColumns: 'Columns in one table', maxBlobBytes: 'Bytes of one workspace file or knowledge base document', maxBlobs: 'Workspace files and knowledge base documents together in one directory', maxBlobBytesPerRequest: 'Bytes of files one upload request carries; a larger file goes in a request of its own', maxBlobsPerRequest: 'Files in one upload request', maxHashBytesPerRequest: 'Bytes of stored files one get or apply downloads to compare', maxStagedBlobs: 'Files one caller may hold staged in one workspace at once', maxStagedBytes: 'Bytes one caller may hold staged in one workspace at once', maxDepth: 'Nesting depth of a declaration file', } const LIMIT_GROUPS: Array<{ title: string limits: Record labels: Record keys: string[] }> = [ { title: 'One workflow', limits: SOURCE_LIMITS, labels: WORKFLOW_LIMIT_LABELS, keys: Object.keys(WORKFLOW_LIMIT_LABELS), }, { title: 'A workspace directory', limits: WORKSPACE_SOURCE_LIMITS, labels: WORKSPACE_LIMIT_LABELS, keys: [ 'maxResourcesPerKind', 'maxDeclarationBytes', 'maxWorkflows', 'maxWorkflowBytes', 'maxDirectoryWorkflowBytes', 'maxChanges', 'maxTableRows', 'maxRowsBytes', 'maxColumns', 'maxBlobBytes', 'maxBlobs', 'maxDepth', ], }, { title: 'Uploading and downloading files', limits: WORKSPACE_SOURCE_LIMITS, labels: WORKSPACE_LIMIT_LABELS, keys: [ 'maxBlobBytesPerRequest', 'maxBlobsPerRequest', 'maxHashBytesPerRequest', 'maxStagedBlobs', 'maxStagedBytes', ], }, ] /** A limit whose label starts with "Bytes" is a byte count. */ function formatLimit(label: string, value: number): string { const formatted = value.toLocaleString('en-US') return label.startsWith('Bytes') ? `${formatted} bytes` : formatted } function buildLimits(errors: string[]): string { for (const [name, limits, labels] of [ ['SOURCE_LIMITS', SOURCE_LIMITS, WORKFLOW_LIMIT_LABELS], ['WORKSPACE_SOURCE_LIMITS', WORKSPACE_SOURCE_LIMITS, WORKSPACE_LIMIT_LABELS], ] as const) { const unlabeled = Object.keys(limits).filter((key) => !(key in labels)) if (unlabeled.length) errors.push(`${name} has limits with no docs label: ${unlabeled.join(', ')}`) } for (const key of Object.keys(WORKSPACE_SOURCE_LIMITS)) { const placed = LIMIT_GROUPS.slice(1).filter((group) => group.keys.includes(key)).length if (placed !== 1) errors.push(`WORKSPACE_SOURCE_LIMITS.${key} is in ${placed} limits groups, not 1`) } const lines: string[] = [''] for (const group of LIMIT_GROUPS) { lines.push(`### ${group.title}`, '', '| Limit | Value |', '| --- | --- |') for (const key of group.keys) { lines.push( `| ${cell(group.labels[key])} | ${formatLimit(group.labels[key], group.limits[key])} |` ) } lines.push('') } return lines.join('\n') } function rewrite(region: Region, doc: string, content: string, file: string): string { const begin = doc.indexOf(beginMarker(region)) const end = doc.indexOf(endMarker(region)) if (begin === -1 || end === -1 || end < begin) { throw new Error(`workflow-code-docs: ${region} markers not found in ${file}`) } return `${doc.slice(0, begin + beginMarker(region).length)}\n${content}\n${doc.slice(end)}` } function walkMdx(dir: string): string[] { return fs .readdirSync(dir, { recursive: true, encoding: 'utf8' }) .filter((entry) => entry.endsWith('.mdx')) .map((entry) => path.join(dir, entry)) } /** A generated region, which the owners already check, so stale rows never block regenerating it. */ const GENERATED_REGION = /\{\/\* workflow-code-docs:[\w-]+:begin[\s\S]*?\{\/\* workflow-code-docs:[\w-]+:end \*\/\}/g function checkProse(errors: string[]): void { const known = new Set([...DIAGNOSTIC_CODES, ...WORKSPACE_DIAGNOSTIC_CODES]) for (const file of walkMdx(PAGES_DIR)) { const rel = path.relative(rootDir, file) const text = fs.readFileSync(file, 'utf8') const prose = text.replace(GENERATED_REGION, '') for (const match of prose.matchAll(/`([EWI]_[A-Z0-9_]+)`/g)) { if (!known.has(match[1])) errors.push(`${rel} names ${match[1]}, which no engine emits`) } } const pinned = SOURCE_TYPESCRIPT_VERSION for (const file of walkMdx(DOCS_DIR)) { for (const match of fs.readFileSync(file, 'utf8').matchAll(/typescript@(\d+\.\d+\.\d+)/g)) { if (match[1] !== pinned) { errors.push( `${path.relative(rootDir, file)} pins typescript@${match[1]}, but the CLI type-checks with ${pinned}` ) } } } } /** * The troubleshooting page explains each exit code in depth, so it needs exactly one `#exit-` * section per non-zero code a source command exits with. */ function checkTroubleshooting(errors: string[]): void { const file = path.join(PAGES_DIR, 'troubleshooting.mdx') const expected = [ ...new Set(SOURCE_GROUPS.flatMap((group) => sourceExitCodeRows(group).map((row) => row.code))), ] .filter(Boolean) .sort((a, b) => a - b) const found = [...fs.readFileSync(file, 'utf8').matchAll(/^#+ .*\[#exit-(\d+)\]$/gm)] .map((match) => Number(match[1])) .sort((a, b) => a - b) if (found.join() !== expected.join()) { errors.push( `${path.relative(rootDir, file)} needs one [#exit-] section per source exit code: expected ${expected.join(', ')}, found ${found.join(', ')}` ) } } function main(): void { const checkMode = process.argv.includes('--check') const errors: string[] = [] const generated: Record = { 'exit-codes': buildExitCodes(), diagnostics: buildDiagnostics(errors), limits: buildLimits(errors), 'directory-kinds': buildDirectoryKinds(), } checkProse(errors) checkTroubleshooting(errors) const writes: Array<{ rel: string; file: string; next: string }> = [] for (const region of Object.keys(REGIONS) as Region[]) { const file = path.join(PAGES_DIR, REGIONS[region]) const rel = path.relative(rootDir, file) if (!fs.existsSync(file)) { errors.push(`${rel} does not exist`) continue } const doc = fs.readFileSync(file, 'utf8') const next = rewrite(region, doc, generated[region], rel) if (next !== doc) writes.push({ rel, file, next }) } if (errors.length > 0) { console.error('workflow-code-docs:') for (const error of [...new Set(errors)].sort(compareStrings)) console.error(` - ${error}`) process.exit(1) } if (checkMode) { if (writes.length > 0) { console.error( `workflow-code-docs: out of date: ${writes.map((write) => write.rel).join(', ')}. Run \`bun run generate:workflow-code-docs\`.` ) process.exit(1) } console.log('workflow-code-docs: up to date.') return } for (const { rel, file, next } of writes) { fs.writeFileSync(file, next) console.log(`workflow-code-docs: updated ${rel}`) } } main()