diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx index a6e30ebc5be..574378c05e5 100644 --- a/apps/docs/content/docs/workflows/code/diagnostics.mdx +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -237,7 +237,7 @@ Workspace source reports every workflow code above for the files of `workflows/< | Code | Meaning | | --- | --- | | `E_SECRET_NAME` | A declared name outside the secret name format. | -| `E_SECRET_MISSING` | A workflow uses a declared secret the workspace holds no value for: it is held back. | +| `E_SECRET_MISSING` | A workflow reads a declared secret the workspace holds no value for: it is held back. The finding points at the first line that reads it, and replaces `W_ENV_UNKNOWN` for that name. | | `W_SECRET_MISSING` | A declared secret the workspace holds no value for. | #### Credentials (`credentials.ts`) @@ -258,7 +258,7 @@ Workspace source reports every workflow code above for the files of `workflows/< | `E_TABLE_TOO_MANY_COLUMNS` | More columns than a table may hold: a size limit, classed like `E_LIMIT_EXCEEDED`. | | `E_TABLE_OPTIONS` | A select column without options, an option declared twice, or options on another type. | | `E_TABLE_TYPE_CONVERSION` | A type change the stored cells cannot convert to. | -| `E_TABLE_FOLDER` | A table folder that does not exist in the workspace. | +| `E_TABLE_FOLDER` | A table folder that does not exist in the workspace. The hint creates each missing folder, parent first. | | `E_TABLE_ROWS` | The declaration's `rows` or its `tables/.rows.jsonl`: a bad mode or key column, a line that is not a row of declared columns, a managed row without its key or repeating one. | | `I_TABLE_SEED_SKIPPED` | Seed rows declared for a table that already holds rows: only a new or empty table is seeded. | | `I_TABLE_ROWS_UNKEYED` | Managed rows whose key cell is empty (a row the table's "add row" made and nobody keyed): no file line can name them, so a get leaves them out and an apply keeps them as they are. | @@ -309,7 +309,7 @@ Workspace source reports every workflow code above for the files of `workflows/< | `E_KB_DOC_NAME` | A document file name or type the knowledge base cannot hold. | | `E_KB_DOC_EMPTY` | An empty document, which a knowledge base cannot index. | | `E_KB_CHUNKING` | Chunking settings outside what a knowledge base accepts. | -| `E_KB_FOLDER` | A knowledge base folder that does not exist in the workspace. | +| `E_KB_FOLDER` | A knowledge base folder that does not exist in the workspace. The hint creates each missing folder, parent first. | | `W_KB_DOC_UNCHECKED` | A stored document whose bytes this request had no budget left to download and compare. | | `W_KB_DOC_FAILED` | Documents whose indexing failed: search does not find them until they are indexed again. | | `I_KB_REEMBED` | How many documents the apply indexes (embeds) after it writes them. | @@ -344,7 +344,7 @@ Workspace source reports every workflow code above for the files of `workflows/< | `E_APPLY_REFUSED` | A change a child operation refused, with its message. | | `E_APPLY_FAILED` | A write failed for a reason that is not the source's (logged on the server). | | `E_PLAN_TOO_LARGE` | The apply would make more changes or touch more workflows than one request may. | -| `E_PLAN_REF_DELETED` | A declared resource references one this apply deletes. | +| `E_PLAN_REF_DELETED` | A declared resource references one this apply deletes. For an edited workflow, the finding points at the line that uses it. | | `E_PLAN_REF_HELD` | A declared resource references one this apply holds back, so it is held back too. | | `W_RESOURCE_IN_USE` | A resource this apply deletes is still used by stored workflows. | | `W_TABLE_COLUMN_RENAMED_IN_USE` | A table column this apply renames is still written, filtered or sorted by its old name in a stored workflow's Table block, which the run then drops. | diff --git a/apps/docs/content/docs/workflows/code/directory.mdx b/apps/docs/content/docs/workflows/code/directory.mdx index 3bd416acb86..7fe9834c462 100644 --- a/apps/docs/content/docs/workflows/code/directory.mdx +++ b/apps/docs/content/docs/workflows/code/directory.mdx @@ -54,7 +54,7 @@ A resource's key is its file or folder name, and a workflow names it by that key {/* workflow-code-docs:directory-kinds:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} -- `secrets.ts`: `export default defineSecrets({ NAME: { description? } })`, the workspace secrets workflows read, by name and description only (never a value: set one with `sim secrets set NAME --scope workspace`). A workflow: `env.NAME`; one using a declared secret the workspace has no value for is held back, and the rest apply. +- `secrets.ts`: `export default defineSecrets({ NAME: { description? } })`, the workspace secrets workflows read, by name and description only (never a value: set one with `sim secrets set NAME --scope workspace`). A workflow: `env.NAME`; one using a declared secret the workspace has no value for is held back, and the rest apply. A get prints only the secrets the workspace has a value for, so a declared secret without one stays only in your directory. - `credentials.ts`: `export default defineCredentials({ : { provider, name? } })`, binding each key to this workspace's credential for that provider (never a token): the one bound already, else the only one, else the one whose display name is `name`. A workflow: `credential('')`; one using a key no credential binds to is held back, and the rest apply. - `tools/.ts` (`defineTool({ title, schema, code: codeFile('./.js') })`) and its code in `tools/.js`, where each schema parameter is a variable. Code holding a literal credential prints as `code: stored()`, which keeps the stored code. A workflow: `customTool('')`. - `skills/.md`: a frontmatter block of `name` and `description`, then the content. A workflow: `skills: [skill('')]` on an agent. diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts index e57fb190a9d..2baaad13439 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts @@ -66,7 +66,7 @@ function withPendingResources( /** * Every `(kind, key)` resource reference in a compiled model, for ident lookup, and the tool each - * MCP agent tool (`mcp(key).tool(name)`) names on its server. + * MCP agent tool (`mcp(key).tool(name)`) names on its server, each at `span`. */ function collectResourceKeys( value: unknown, @@ -85,7 +85,7 @@ function collectResourceKeys( isResourceKind(record.kind) && typeof record.key === 'string' ) { - refs.push({ kind: record.kind, key: record.key }) + refs.push({ kind: record.kind, key: record.key, ...(span ? { span } : {}) }) } const tool = mcpToolReference(record) if (tool) refs.push(span ? { ...tool, span } : tool) @@ -163,10 +163,13 @@ export async function resolveSubmission( const compiledKeys: SourceReference[] = [] for (const [key, block] of Object.entries(compiledWorkflow.blocks)) { - const span = - compiled.spans[encodeAnchor({ kind: 'param', block: key, param: 'tools' })] ?? - compiled.spans[encodeAnchor({ kind: 'block', block: key })] - collectResourceKeys(block, compiledKeys, span) + const blockSpan = compiled.spans[encodeAnchor({ kind: 'block', block: key })] + const { params, ...rest } = block + for (const [param, value] of Object.entries(params)) { + const span = compiled.spans[encodeAnchor({ kind: 'param', block: key, param })] ?? blockSpan + collectResourceKeys(value, compiledKeys, span) + } + collectResourceKeys(rest, compiledKeys, blockSpan) } const storedResources = resources const newKeys = compiledKeys.filter(({ kind, key }) => storedResources.toId(kind, key) === null) diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts index 025ef5ccef6..580b5d7333b 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts @@ -4,6 +4,7 @@ import type { CanonicalWorkflow, CanonicalWorkflowMeta, ChildResultFields, + EnvReference, LockIdentity, ResourceKeyResolver, ResourceKind, @@ -77,7 +78,7 @@ export interface SourceEvaluationInput { */ export interface SourceReference extends ResourceKeyRef { member?: string - /** Where the entry file writes the reference, for an MCP tool: the agent's `tools`. */ + /** Where the source writes the reference: the block param that holds it, else the block. */ span?: SourceSpan } @@ -133,8 +134,8 @@ export interface SourcePlan { resources: ResourceKeyResolver /** Every resource the submitted source names by key, as the compiler read it. */ references: SourceReference[] - /** Every env name the submitted source reads, as the compiler read it. */ - envReferences: string[] + /** Every env name the submitted source reads, and where, as the compiler read it. */ + envReferences: EnvReference[] /** The child result fields the compile typed with, which every print of the plan types with. */ childResults?: ReadonlyMap } diff --git a/apps/sim/lib/workflows/application/source-pipeline/load.ts b/apps/sim/lib/workflows/application/source-pipeline/load.ts index a371d092c5d..45205e24e63 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/load.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/load.ts @@ -77,6 +77,12 @@ export type SourceTarget = export interface SourceLoads { catalogGate?: Promise envNames?: Promise + /** + * The env names the workspace directory's `secrets.ts` declares, which a plan reads as known, as + * the offline check does: a workflow that reads one the workspace holds no value for is held + * back (`E_SECRET_MISSING`, at the read) rather than warned about (`W_ENV_UNKNOWN`). + */ + declaredEnvNames?: readonly string[] /** The child workflows read to type their callers' results (`loadChildResults`). */ childResults?: ChildResultsMemo /** The workflow folders the workspace source apply writes, which its callers are typed by. */ @@ -174,7 +180,7 @@ export async function loadSourceTarget( storedCanonical.canonical, storedCanonical.resources ), - envNames, + envNames: [...envNames, ...(loads.declaredEnvNames ?? [])], scope, } }) diff --git a/apps/sim/lib/workflows/application/source-pipeline/plan.ts b/apps/sim/lib/workflows/application/source-pipeline/plan.ts index 48f4b10b48a..119658b1d56 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/plan.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/plan.ts @@ -1,6 +1,7 @@ import type { Principal } from '@sim/auth/principal' import type { BlockCatalog, + EnvReference, ResourceKind, SourceBase, SourceFingerprint, @@ -113,7 +114,7 @@ export interface SourcePlanSummary { diff: SourceDiffSummary /** What the source references, as the compiler read it; empty when it did not compile. */ references: readonly SourceReference[] - envReferences: readonly string[] + envReferences: readonly EnvReference[] /** Whether a graph no-op still changes source meta (idents, order or comments). */ sourceMetaChanged: boolean /** The workflow's name after the write; absent for a refusal. */ diff --git a/apps/sim/lib/workspace-source/application/apply.integration.ts b/apps/sim/lib/workspace-source/application/apply.integration.ts index e1495e0fa2a..ab815e46015 100644 --- a/apps/sim/lib/workspace-source/application/apply.integration.ts +++ b/apps/sim/lib/workspace-source/application/apply.integration.ts @@ -715,7 +715,36 @@ describe('workspace source apply', () => { const taken = await refusal( apply(workspaceId, { 'tables/other.ts': LEADS }, { kinds: ['table'], only: ['table'] }) ) - expect(codes(taken.diagnostics)).toContain('E_NAME_TAKEN') + expect(taken.diagnostics).toContainEqual( + expect.objectContaining({ + code: 'E_NAME_TAKEN', + file: 'tables/other.ts', + message: + 'tables/other declares the table name "leads", which belongs to the table under key "leads".', + }) + ) + } + ) + + check( + 'a missing nested table folder hints one create per missing level, parent first', + async () => { + const workspaceId = await newWorkspace() + const nested = LEADS.replace("name: 'leads',", "name: 'leads',\n folder: '/qa/sub',") + + const refused = await refusal( + apply(workspaceId, { 'tables/leads.ts': nested }, { kinds: ['table'], only: ['table'] }) + ) + + expect(refused.diagnostics).toEqual([ + expect.objectContaining({ + code: 'E_TABLE_FOLDER', + file: 'tables/leads.ts', + hint: expect.stringContaining( + 'Create it first (`sim tables folders create "qa"`, then `sim tables folders create "qa/sub"`)' + ), + }), + ]) } ) @@ -754,7 +783,13 @@ describe('workspace source apply', () => { ) expect(codes(refused.diagnostics)).toEqual(['E_PLAN_REF_DELETED']) - expect(refused.diagnostics[0]).toMatchObject({ kind: 'workflow', key: 'ingest' }) + const source = files['workflows/ingest/workflow.ts'].split('\n') + expect(refused.diagnostics[0]).toMatchObject({ + kind: 'workflow', + key: 'ingest', + file: 'workflows/ingest/workflow.ts', + line: source.findIndex((line) => line.includes("'Save Lead'")) + 1, + }) expect(await tables(workspaceId)).toHaveLength(1) } ) diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index 7c6dc1da5f7..4e6432a2ae3 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -987,6 +987,9 @@ export default workflow('Reader', {}, () => { .filter((finding) => finding.severity === 'error') .map((finding) => `${finding.code} ${finding.kind}:${finding.key}`) ).toEqual(['E_PLAN_REF_DELETED workflow:reader']) + expect( + refused.diagnostics.find((finding) => finding.code === 'E_PLAN_REF_DELETED') + ).toMatchObject({ file: 'workflows/reader/workflow.ts', line: expect.any(Number) }) } ) check( diff --git a/apps/sim/lib/workspace-source/application/findings.ts b/apps/sim/lib/workspace-source/application/findings.ts index 9812a047e2b..6f6fb1d6c75 100644 --- a/apps/sim/lib/workspace-source/application/findings.ts +++ b/apps/sim/lib/workspace-source/application/findings.ts @@ -2,7 +2,7 @@ * The findings every kind reports the same way, so the plan reads alike across kinds. */ -import { stableStringify } from '@sim/workflow-code' +import { type SourceSpan, stableStringify } from '@sim/workflow-code' import { diagnostic } from '@sim/workflow-code/diagnostics' import { type BaseResource, @@ -14,6 +14,8 @@ import { type WorkspaceDiagnosticCode, type WorkspaceKind, } from '@sim/workspace-code' +import { KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' +import { workflowFolder } from '@sim/workspace-code/kinds/workflow' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' import type { KindChange, @@ -63,25 +65,44 @@ export function where(kind: WorkspaceKind, key: string): string { return isFileKind(kind) ? `${KIND_DIRS[kind]} ${key}` : `${KIND_DIRS[kind]}/${key}` } +/** Where in the directory a finding points. */ +type FindingLocation = Pick + /** - * A finding about one resource, its severity fixed by the code's prefix; `file` pins it to the - * file that declares the resource. + * A finding about one resource, its severity fixed by the code's prefix. It points at the file + * that declares the resource unless `extras` points it elsewhere (a table's rows file, the line of + * a workflow that uses the resource). */ export function kindFinding( kind: WorkspaceKind, key: string, code: WorkspaceDiagnosticCode, message: string, - extras: { hint?: string; file?: string } = {} + extras: { hint?: string } & FindingLocation = {} ): WorkspaceSourceDiagnostic { + const { hint, file = KIND_LAYOUTS[kind].declarationPath(key), ...at } = extras return finding(code, message, { - ...(extras.hint !== undefined ? { hint: extras.hint } : {}), - ...(extras.file !== undefined ? { file: extras.file } : {}), + ...(hint !== undefined ? { hint } : {}), + file, + ...at, kind, key, }) } +/** + * Where `user`'s source writes a reference its compile located (`span`, relative to the workflow's + * folder); empty when it was not located, so the finding points at the file that declares `user`. + */ +export function referenceSite( + user: { kind: WorkspaceKind; key: string }, + span: SourceSpan | undefined +): FindingLocation { + if (user.kind !== 'workflow' || !span) return {} + const { line, column, endLine, endColumn } = span + return { file: `${workflowFolder(user.key)}/${span.file}`, line, column, endLine, endColumn } +} + /** `E_APPLY_STALE`: the resource changed on the server since the directory was read. */ export function staleFinding(kind: WorkspaceKind, key: string): WorkspaceSourceDiagnostic { return kindFinding( @@ -156,62 +177,78 @@ export function missingFolderFinding( folders: ReadonlySet ): WorkspaceSourceDiagnostic | undefined { if (!folder || folder === '/' || folders.has(folder)) return undefined + // A folder is created inside an existing parent, so each missing level is created in turn. + const segments = folder.slice(1).split('/') + const creates = segments + .map((_, depth) => segments.slice(0, depth + 1).join('/')) + .filter((path) => !folders.has(`/${path}`)) + .map((path) => `\`sim ${kind === 'table' ? 'tables' : 'knowledge'} folders create "${path}"\``) return kindFinding( kind, key, kind === 'table' ? 'E_TABLE_FOLDER' : 'E_KB_FOLDER', `The folder ${folder} does not exist in this workspace.`, { - hint: `Create it first (\`sim ${kind === 'table' ? 'tables' : 'knowledge'} folders create "${folder.replace(/^\//, '')}"\`), or drop \`folder\` to keep the ${WORKSPACE_KIND_SPECS[kind].noun} at the root.`, + hint: `Create it first (${creates.join(', then ')}), or drop \`folder\` to keep the ${WORKSPACE_KIND_SPECS[kind].noun} at the root.`, } ) } /** * `E_PLAN_REF_DELETED` on `user` (a declared workflow, say) for using `ref`, which the apply - * deletes. + * deletes, at the line that uses it when `ref.span` locates it. */ export function refDeletedFinding( user: { kind: WorkspaceKind; key: string }, - ref: { kind: WorkspaceKind; key: string } + ref: { kind: WorkspaceKind; key: string; span?: SourceSpan } ): WorkspaceSourceDiagnostic { return kindFinding( user.kind, user.key, 'E_PLAN_REF_DELETED', `${where(user.kind, user.key)} uses ${ref.kind} "${ref.key}", which this apply deletes.`, - { hint: `Keep ${where(ref.kind, ref.key)}, or stop using it first.` } + { + hint: `Keep ${where(ref.kind, ref.key)}, or stop using it first.`, + ...referenceSite(user, ref.span), + } ) } /** * The finding that holds back `user` (a declared workflow, say) for using `reference`, which this - * workspace cannot satisfy. + * workspace cannot satisfy, at the line that uses it when `span` locates it. */ export function refUnavailableFinding( user: { kind: WorkspaceKind; key: string }, - reference: UnavailableReference + reference: UnavailableReference, + span: SourceSpan | undefined ): WorkspaceSourceDiagnostic { return kindFinding( user.kind, user.key, reference.code, `${where(user.kind, user.key)} is held back: ${reference.message}`, - { hint: reference.hint } + { hint: reference.hint, ...referenceSite(user, span) } ) } -/** `E_PLAN_REF_HELD` on `user` for using `ref`, which this apply holds back. */ +/** + * `E_PLAN_REF_HELD` on `user` for using `ref`, which this apply holds back, at the line that uses + * it when `ref.span` locates it. + */ export function refHeldFinding( user: { kind: WorkspaceKind; key: string }, - ref: { kind: WorkspaceKind; key: string } + ref: { kind: WorkspaceKind; key: string; span?: SourceSpan } ): WorkspaceSourceDiagnostic { return kindFinding( user.kind, user.key, 'E_PLAN_REF_HELD', `${where(user.kind, user.key)} is held back: it uses ${where(ref.kind, ref.key)}, which this apply holds back.`, - { hint: `Fix what holds back ${where(ref.kind, ref.key)}, then apply again.` } + { + hint: `Fix what holds back ${where(ref.kind, ref.key)}, then apply again.`, + ...referenceSite(user, ref.span), + } ) } @@ -283,8 +320,7 @@ export function nameTakenFinding( kind: WorkspaceKind, key: string, name: string, - holder: NameHolder, - file?: string + holder: NameHolder ): WorkspaceSourceDiagnostic { const noun = WORKSPACE_KIND_SPECS[kind].noun const held = @@ -293,10 +329,13 @@ export function nameTakenFinding( : holder.key ? `the ${noun} under key "${holder.key}"` : `another ${noun} this directory does not manage` - return kindFinding(kind, key, 'E_NAME_TAKEN', `The ${noun} name "${name}" belongs to ${held}.`, { - hint: 'Rename one of them, or declare that resource under its own key.', - ...(file ? { file } : {}), - }) + return kindFinding( + kind, + key, + 'E_NAME_TAKEN', + `${where(kind, key)} declares the ${noun} name "${name}", which belongs to ${held}.`, + { hint: 'Rename one of them, or declare that resource under its own key.' } + ) } /** @@ -310,8 +349,7 @@ export function keyRenamedChange( change: KindChange, holder: StoredResource, desired: ReadonlyMap, - ctx: PlanContext, - file?: string + ctx: PlanContext ): KindChange | undefined { const { kind, key } = change if (!holder.key || desired.has(holder.key)) return undefined @@ -330,7 +368,6 @@ export function keyRenamedChange( `${where(kind, key)} declares the ${noun} "${holder.name}", which this directory read as ${where(kind, holder.key)}; a ${noun}'s key never changes, since workflows name it by its key.`, { hint: `Rename it back to ${where(kind, holder.key)}; to rename the ${noun}, change its name there. A new key with a new name creates a new ${noun}.`, - ...(file ? { file } : {}), } ), ], @@ -362,8 +399,7 @@ export function refuseDeclaredTwice( claimed: Map, change: Pick, name: string, - displayName: string = name, - file?: string + displayName: string = name ): void { if (change.diagnostics.some((finding) => finding.code === 'E_NAME_TAKEN')) return const first = claimed.get(name) @@ -372,7 +408,7 @@ export function refuseDeclaredTwice( return } change.diagnostics.push( - nameTakenFinding(change.kind, change.key, displayName, { declaredBy: first }, file) + nameTakenFinding(change.kind, change.key, displayName, { declaredBy: first }) ) } diff --git a/apps/sim/lib/workspace-source/application/kinds/credentials/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/credentials/adapter.ts index fc5c2d5b869..a6812cc1867 100644 --- a/apps/sim/lib/workspace-source/application/kinds/credentials/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/credentials/adapter.ts @@ -134,7 +134,7 @@ function unavailable( key, ambiguous ? 'W_CREDENTIAL_AMBIGUOUS' : 'W_CREDENTIAL_MISSING', `${where('credential', key)} binds to nothing: ${reason}`, - { hint, file: KIND_DIRS.credential } + { hint } ) ) return { diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts index 986029a8ae1..1f6d06bf374 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts @@ -226,10 +226,7 @@ function deploymentFinding( message: string, hint?: string ) { - return kindFinding('deployment', key, code, message, { - file: deploymentDeclarationPath(key), - ...(hint ? { hint } : {}), - }) + return kindFinding('deployment', key, code, message, { hint }) } /** The live workflow bound to `key`, by id, or `undefined`. */ diff --git a/apps/sim/lib/workspace-source/application/kinds/knowledge/diff.ts b/apps/sim/lib/workspace-source/application/kinds/knowledge/diff.ts index dd0d9cd2837..1fca0022fec 100644 --- a/apps/sim/lib/workspace-source/application/kinds/knowledge/diff.ts +++ b/apps/sim/lib/workspace-source/application/kinds/knowledge/diff.ts @@ -16,6 +16,7 @@ import { type KnowledgeBaseDecl, type KnowledgeChunkingDecl, type KnowledgeDocDecl, + knowledgeDocPath, resolvedChunking, } from '@sim/workspace-code/kinds/knowledge' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' @@ -108,10 +109,16 @@ export function checkWrites( const typeError = validateFileType(name, '') if (typeError) { diagnostics.push( - kindFinding(KIND, key, 'E_KB_DOC_NAME', `docs/${name}: ${typeError.message}`) + kindFinding(KIND, key, 'E_KB_DOC_NAME', `docs/${name}: ${typeError.message}`, { + file: knowledgeDocPath(key, name), + }) ) } else if (doc.size === 0) { - diagnostics.push(kindFinding(KIND, key, 'E_KB_DOC_EMPTY', `docs/${name} is empty.`)) + diagnostics.push( + kindFinding(KIND, key, 'E_KB_DOC_EMPTY', `docs/${name} is empty.`, { + file: knowledgeDocPath(key, name), + }) + ) } } return diagnostics @@ -287,6 +294,7 @@ export async function diffKnowledgeBase(input: { `Several stored documents are named "${name}", so docs/${name} cannot tell which one it is.`, { hint: 'Delete or rename the duplicates in the knowledge base, then get and apply again.', + file: knowledgeDocPath(key, name), } ) ) @@ -307,7 +315,7 @@ export async function diffKnowledgeBase(input: { key, 'W_KB_DOC_UNCHECKED', `docs/${name} was not compared with the stored document (this request reached its download budget, or the stored bytes could not be read), so it is left as it is.`, - { hint: 'Apply again to compare it.' } + { hint: 'Apply again to compare it.', file: knowledgeDocPath(key, name) } ) ) continue @@ -345,7 +353,8 @@ export async function diffKnowledgeBase(input: { KIND, key, 'W_UNDECLARED', - `Document "${name}" is in the knowledge base but not in docs/; it is kept.` + `Document "${name}" is in the knowledge base but not in docs/; it is kept.`, + { file: knowledgeDocPath(key, name) } ) ) } else if (ctx.allowDelete) { @@ -358,7 +367,10 @@ export async function diffKnowledgeBase(input: { key, 'E_APPLY_DELETE_NOT_ALLOWED', `docs/${name} is no longer declared; deleting the stored document needs --allow-delete.`, - { hint: 'Pass --allow-delete to delete it, or restore the file to keep it.' } + { + hint: 'Pass --allow-delete to delete it, or restore the file to keep it.', + file: knowledgeDocPath(key, name), + } ) ) } 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 20839593681..33bc42b2cb8 100644 --- a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts @@ -24,20 +24,8 @@ import { createLogger } from '@sim/logger' import { mapWithConcurrency } from '@sim/utils/concurrency' import { getErrorMessage } from '@sim/utils/errors' import { didYouMean, type SourceSpan } from '@sim/workflow-code' -import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' -import { - type BaseResource, - type FlatDiagnostic, - fingerprintOf, - resourceAddress, -} from '@sim/workspace-code' -import { - MCP_DEFAULTS, - type McpServerDecl, - mcpCodec, - mcpDeclarationPath, -} from '@sim/workspace-code/kinds/mcp' -import { workflowFolder } from '@sim/workspace-code/kinds/workflow' +import { type BaseResource, fingerprintOf, resourceAddress } from '@sim/workspace-code' +import { MCP_DEFAULTS, type McpServerDecl, mcpCodec } from '@sim/workspace-code/kinds/mcp' import type { CursorKey } from '@/lib/api/list-query' import { authorizeWorkspaceOperation, ForbiddenOperationError } from '@/lib/core/application' import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -56,9 +44,9 @@ import type { McpServerRow } from '@/lib/mcp/queries' import { generateMcpServerId } from '@/lib/mcp/utils' import { admitOnce } from '@/lib/workspace-source/application/context' import { - finding, kindFinding, planUndeclared, + referenceSite, serverGoneFinding, where, } from '@/lib/workspace-source/application/findings' @@ -137,12 +125,9 @@ async function planServer( ctx: PlanContext, claimed: Map ): Promise { - const file = mcpDeclarationPath(key) const change: McpChange = { kind: 'mcp-server', key, action: 'noop', diagnostics: [] } const finding = (code: Parameters[2], message: string, hint?: string) => - change.diagnostics.push( - kindFinding('mcp-server', key, code, message, { file, ...(hint ? { hint } : {}) }) - ) + change.diagnostics.push(kindFinding('mcp-server', key, code, message, { hint })) const id = serverIdOf(ctx, declared.url) const first = claimed.get(id) if (first !== undefined) { @@ -294,7 +279,6 @@ async function planReplace( ...(replacement ? { replacement: replacement.id } : {}), }, } - const file = mcpDeclarationPath(change.key) replaced.diagnostics.push( kindFinding( 'mcp-server', @@ -303,7 +287,7 @@ async function planReplace( replacement ? `The URL of ${where('mcp-server', change.key)} changed, and an earlier apply already created the server at ${change.decl?.url}: it takes the key and "${record.name}" is deleted.` : `The URL of ${where('mcp-server', change.key)} changed, which replaces the server: it is created at ${change.decl?.url} and "${record.name}" is deleted.`, - { file, hint: 'Its id derives from its URL; the key moves to the new server.' } + { hint: 'Its id derives from its URL; the key moves to the new server.' } ) ) if (using === null) { @@ -315,7 +299,7 @@ async function planReplace( change.key, 'E_APPLY_DELETE_NOT_ALLOWED', `Replacing "${record.name}" breaks ${users.length} stored workflow(s) that call it by id until they are applied again; it needs --allow-delete.`, - { file, hint: 'Pass --allow-delete, or keep the URL.' } + { hint: 'Pass --allow-delete, or keep the URL.' } ) ) } @@ -475,25 +459,6 @@ function toolUsers( return byServer } -/** - * Where a finding about the tools a change calls points: its workflow file, at the line that - * writes the tool when the workflow's compile located it. - */ -function fileOf(change: PlannedChange, span?: SourceSpan): Partial { - if (change.kind !== 'workflow') return {} - return { - file: `${workflowFolder(change.key)}/${SOURCE_ENTRY_FILE}`, - ...(span - ? { - line: span.line, - column: span.column, - endLine: span.endLine, - endColumn: span.endColumn, - } - : {}), - } -} - export const mcpAdapter: KindAdapter<'mcp-server', McpServerRow> = { codec: mcpCodec, keys: 'every-write', @@ -665,10 +630,7 @@ export const mcpAdapter: KindAdapter<'mcp-server', McpServerRow> = { change.key, 'W_MCP_TOOLS_UNCHECKED', `The tools ${where(change.kind, change.key)} calls on MCP server "${key}" are not checked: ${listed.reason}.`, - { - hint: 'A tool the server does not list fails when the agent calls it.', - ...fileOf(change), - } + { hint: 'A tool the server does not list fails when the agent calls it.' } ) ) } @@ -680,14 +642,14 @@ export const mcpAdapter: KindAdapter<'mcp-server', McpServerRow> = { if (names.has(tool)) continue const suggestion = didYouMean(tool, names, (name) => `"${name}"`) change.diagnostics.push( - finding( + kindFinding( + change.kind, + change.key, 'E_MCP_TOOL_UNKNOWN', `${where(change.kind, change.key)} calls tool "${tool}" on MCP server "${key}", which does not list it.${suggestion ? ` ${suggestion}` : ''}`, { hint: `The server lists: ${[...names].slice(0, 20).join(', ') || 'no tools'}.`, - ...fileOf(change, span), - kind: change.kind, - key: change.key, + ...referenceSite(change, span), } ) ) diff --git a/apps/sim/lib/workspace-source/application/kinds/named.ts b/apps/sim/lib/workspace-source/application/kinds/named.ts index 302969cbcce..9fe9f23e748 100644 --- a/apps/sim/lib/workspace-source/application/kinds/named.ts +++ b/apps/sim/lib/workspace-source/application/kinds/named.ts @@ -99,7 +99,7 @@ export function changedFields(before: Json, after: Json): string[] { /** * Plans one declared resource. `claimed` maps each name the directory declares so far to its key, - * so two declarations of one name refuse; `file` is where findings about it point. + * so two declarations of one name refuse. */ export function planNamed( named: NamedKind, @@ -108,13 +108,12 @@ export function planNamed( stored: StoredSet, desired: ReadonlyMap>, ctx: PlanContext, - file: string, claimed: Map ): KindChange { const { kind } = named const name = named.nameOf(decl) const change: KindChange = { kind, key, action: 'noop', decl, diagnostics: [] } - refuseDeclaredTwice(claimed, change, name, name, file) + refuseDeclaredTwice(claimed, change, name) const resolution = resolveDeclared({ local: fingerprintOf(named.codec.canonical(decl)), @@ -127,14 +126,14 @@ export function planNamed( const holderOf = (self?: string) => { const holder = nameHolder(stored, name, { self }) const refused = change.diagnostics.some((finding) => finding.code === 'E_NAME_TAKEN') - if (holder && !refused) change.diagnostics.push(nameTakenFinding(kind, key, name, holder, file)) + if (holder && !refused) change.diagnostics.push(nameTakenFinding(kind, key, name, holder)) } const planned = settle(resolution, change, (record) => baseOf(named, record)) if ('settled' in planned) return planned.settled switch (planned.action) { case 'create': { const holder = nameHolder(stored, name) - const renamed = holder && keyRenamedChange(change, holder, desired, ctx, file) + const renamed = holder && keyRenamedChange(change, holder, desired, ctx) if (renamed) return renamed holderOf() return { diff --git a/apps/sim/lib/workspace-source/application/kinds/secrets/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/secrets/adapter.ts index 42000383da0..4b61d4e9c98 100644 --- a/apps/sim/lib/workspace-source/application/kinds/secrets/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/secrets/adapter.ts @@ -9,15 +9,19 @@ * entry (a directory read from another workspace, say), a declared description is applied and an * undeclared one is left as the server holds it. * - A declared name the workspace holds no secret under is `W_SECRET_MISSING` on `secrets.ts`, and - * every change the apply writes that reads it is held back (`E_SECRET_MISSING`). + * every change the apply writes that reads it is held back (`E_SECRET_MISSING`, at the line that + * reads it). A workflow's plan reads every declared name as known, so no `W_ENV_UNKNOWN` + * repeats the hold. * - A secret the directory does not declare is left alone, with no finding: nothing is deleted. + * - A get prints only the secrets the workspace holds, so a declared name with no value stays only + * in the directory. * * Only workspace secrets: another user's personal secret is never listed, and a name only the * caller's personal secret holds counts as missing, since not every run of the workspace sees it. * Listing secrets refuses a workspace API key, so a directory with `secrets.ts` is refused one. */ import { compareStrings } from '@sim/utils/string' -import { KIND_DIRS, type ResourceFingerprint, resourceAddress } from '@sim/workspace-code' +import { type ResourceFingerprint, resourceAddress } from '@sim/workspace-code' import { fileKindGroupKey } from '@sim/workspace-code/kinds/entries' import { isDeclarableSecret, @@ -113,7 +117,7 @@ function planSecret( name, 'W_SECRET_MISSING', `${where('secret', name)} is declared, but this workspace has no secret ${name}.`, - { hint: setHint(name), file: KIND_DIRS.secret } + { hint: setHint(name) } ) ) change.unavailable = { @@ -174,6 +178,8 @@ export const secretAdapter: KindAdapter<'secret', StoredSecret> = { async plan(desired, stored, ctx) { const declared = desired.get(fileKindGroupKey('secret')) ?? {} + // Planned before any workflow, so each workflow's plan reads the declared names as known. + ctx.loads.declaredEnvNames = Object.keys(declared) return Object.keys(declared) .sort(compareStrings) .map((name) => planSecret(name, declared[name], stored, ctx)) diff --git a/apps/sim/lib/workspace-source/application/kinds/skills/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/skills/adapter.ts index 947519c453e..12080cb564f 100644 --- a/apps/sim/lib/workspace-source/application/kinds/skills/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/skills/adapter.ts @@ -6,7 +6,7 @@ * source. */ import { requirePrincipalSubjectUserId } from '@sim/auth/principal' -import { type SkillDecl, skillCodec, skillPath } from '@sim/workspace-code/kinds/skills' +import { type SkillDecl, skillCodec } from '@sim/workspace-code/kinds/skills' import { createSkillUseCase, deleteSkillUseCase, @@ -62,9 +62,7 @@ const FIELDS: ReadonlyArray = ['name', 'description', 'content' function checkFields(change: SkillChange, decl: SkillDecl): void { const written = writtenFields(change) const finding = (code: 'E_DECL_SHAPE' | 'E_NAME_TAKEN', message: string) => - change.diagnostics.push( - kindFinding('skill', change.key, code, message, { file: skillPath(change.key) }) - ) + change.diagnostics.push(kindFinding('skill', change.key, code, message)) for (const field of FIELDS) { if (!written.includes(field)) continue const problem = skillFieldProblem({ [field]: decl[field] }) @@ -92,7 +90,7 @@ export const skillAdapter: KindAdapter<'skill', SkillDecl> = { const claimed = new Map() const changes: SkillChange[] = [] for (const [key, decl] of desired) { - const change = planNamed(skills, key, decl, stored, desired, ctx, skillPath(key), claimed) + const change = planNamed(skills, key, decl, stored, desired, ctx, claimed) checkFields(change, decl) changes.push(change) } diff --git a/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts index 7d5d60d6e89..9befb372e67 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts @@ -26,15 +26,14 @@ import { resourceAddress, } from '@sim/workspace-code' import { + coercedTableRows, columnName, - declaredRowKeyText, refusedTableRows, type TableDecl, } from '@sim/workspace-code/kinds/table' import { - hasRowKey, - rowKeyText, type TableRowsDecl, + tableRowChanges, tableRowsFingerprint, tableRowsPath, } from '@sim/workspace-code/kinds/table-rows' @@ -281,7 +280,10 @@ function unkeyedFinding( key, 'I_TABLE_ROWS_UNKEYED', `${count} row(s) of "${name}" have no "${rowKey}" value, so ${tableRowsPath(key)} leaves them out and an apply keeps them as they are.`, - { hint: `Fill their "${rowKey}" cells in the table to manage them as source.` } + { + hint: `Fill their "${rowKey}" cells in the table to manage them as source.`, + file: tableRowsPath(key), + } ) } @@ -389,14 +391,18 @@ async function planRows( 'table', key, 'I_TABLE_SEED_SKIPPED', - `Table "${state.table.name}" holds ${state.table.rowCount} row(s), so its seed rows are not written.` + `Table "${state.table.name}" holds ${state.table.rowCount} row(s), so its seed rows are not written.`, + { file: tableRowsPath(key) } ) ) } } return outcome } - const local = tableRowsFingerprint(rows) + // Compared as the write stores them, so a cell spelled otherwise than its column stores it (a + // timestamp as JavaScript prints it) is no change. + const declared: TableRowsDecl = { ...rows, data: coercedTableRows(decl, rows.data) } + const local = tableRowsFingerprint(declared) const based = entry?.id === state.table.id ? entry.rows : undefined const marked = storedKey === rows.key if (based && based.fingerprint === local && marked) { @@ -409,7 +415,7 @@ async function planRows( key, 'W_SERVER_CHANGED', `The rows of table "${state.table.name}" were written on the server since this directory was read; the apply keeps the server's rows (not reverted to ${tableRowsPath(key)}).`, - { hint: DRIFT_HINT } + { hint: DRIFT_HINT, file: tableRowsPath(key) } ) ) } @@ -424,7 +430,7 @@ async function planRows( const server = tableRowsFingerprint({ ...rows, data: stored.data }) if (server === local) { if (!marked) outcome.plan = { mark: markOf(decl), version: stored.version } - else outcome.base = baseRows(rows, stored.version) + else outcome.base = baseRows(declared, stored.version) return outcome } // The base recorded the rows under the key the server still marks, which this apply may change. @@ -439,15 +445,16 @@ async function planRows( key, 'E_APPLY_STALE', `The rows of table "${state.table.name}" changed on the server since this directory was read.`, - { hint: 'Run `sim workspaces source get` to read them, then apply your edits again.' } + { + hint: 'Run `sim workspaces source get` to read them, then apply your edits again.', + file: tableRowsPath(key), + } ) ) return outcome } - const declared = new Set(rows.data.map((row) => declaredRowKeyText(decl, row))) - outcome.removed = stored.data.filter( - (row) => hasRowKey(row, rowKey) && !declared.has(rowKeyText(row[rowKey])) - ).length + const { added, patched, removed } = tableRowChanges(stored.data, declared.data, rowKey) + outcome.removed = removed if (outcome.removed > 0 && !ctx.allowDelete) { outcome.diagnostics.push( kindFinding( @@ -455,7 +462,10 @@ async function planRows( key, 'E_APPLY_DELETE_NOT_ALLOWED', `This removes ${outcome.removed} row(s) of "${state.table.name}" that ${tableRowsPath(key)} no longer lists.`, - { hint: 'Pass --allow-delete to apply it, or keep the rows listed.' } + { + hint: 'Pass --allow-delete to apply it, or keep the rows listed.', + file: tableRowsPath(key), + } ) ) } @@ -466,7 +476,7 @@ async function planRows( version: stored.version, } outcome.kept = kept - outcome.fields.push(`rows (${rows.data.length})`) + outcome.fields.push(`rows (+${added} ~${patched} -${removed})`) outcome.diagnostics.push(...writeFindings(key, decl, write)) return outcome } diff --git a/apps/sim/lib/workspace-source/application/kinds/tools/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/tools/adapter.ts index 73d5ab11812..a1e96a78a42 100644 --- a/apps/sim/lib/workspace-source/application/kinds/tools/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/tools/adapter.ts @@ -20,7 +20,6 @@ import { isStoredToolCode, type ToolCode, toolCodec, - toolDeclarationPath, toolLiteralSecret, } from '@sim/workspace-code/kinds/tools' import type { CursorKey } from '@/lib/api/list-query' @@ -155,24 +154,13 @@ export const toolAdapter: KindAdapter<'custom-tool', StoredTool> = { }) continue } - const change = planNamed( - tools, - key, - decl, - stored, - desired, - ctx, - toolDeclarationPath(key), - claimed - ) + const change = planNamed(tools, key, decl, stored, desired, ctx, claimed) try { if (writtenFields(change).includes('schema')) assertValidCustomToolDeclaration(decl.schema) } catch (error) { if (!(error instanceof OrchestrationError)) throw error change.diagnostics.push( - kindFinding('custom-tool', key, 'E_TOOL_SCHEMA', getErrorMessage(error), { - file: toolDeclarationPath(key), - }) + kindFinding('custom-tool', key, 'E_TOOL_SCHEMA', getErrorMessage(error)) ) } // A renamed key or a taken title already says which tool the declaration meant. @@ -187,7 +175,6 @@ export const toolAdapter: KindAdapter<'custom-tool', StoredTool> = { 'E_TOOL_STORED_MISSING', 'The code is stored(), which keeps the code of the stored tool, but no tool is stored under this key or title.', { - file: toolDeclarationPath(key), hint: `Write the code in tools/${key}.js, or get the directory from the workspace that holds the tool.`, } ) @@ -274,10 +261,7 @@ export const toolAdapter: KindAdapter<'custom-tool', StoredTool> = { return { ...read, diagnostics: [ - kindFinding('custom-tool', stored.key, 'W_TOOL_LITERAL_SECRET', message, { - file: toolDeclarationPath(stored.key), - hint, - }), + kindFinding('custom-tool', stored.key, 'W_TOOL_LITERAL_SECRET', message, { hint }), ], } }, diff --git a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts index d4511b3e614..d68dd758ab7 100644 --- a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts @@ -29,7 +29,7 @@ import { stableStringify, type WorkflowLockV1, } from '@sim/workflow-code' -import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' +import { SOURCE_BASE_FILE, SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import { type BaseResource, @@ -205,7 +205,7 @@ type WorkflowChange = PlannedChange<'workflow'> * for a kind whose source key is its resource key, once per member it names (an MCP server's * tools); by the id `planned` resolves for one keyed otherwise (a workspace file, whose source * key is its path), which the plan matches to that kind's change; and each secret it reads by name - * (`env.NAME`). + * (`env.NAME`), where it first reads it. */ function sourceRefs(summary: SourcePlanSummary): NonNullable { const refs = new Map[number]>() @@ -223,10 +223,12 @@ function sourceRefs(summary: SourcePlanSummary): NonNullable = { const evaluated = evaluatedCreates.get(step.change.key) if (!evaluated) continue if (evaluated.name !== undefined) { - const file = `${workflowFolder(evaluated.change.key)}/${SOURCE_ENTRY_FILE}` refuseDeclaredTwice( names, evaluated.change, folderName(null, evaluated.name), - evaluated.name, - file + evaluated.name ) } planned.set(step.change.key, evaluated.change) diff --git a/apps/sim/lib/workspace-source/application/knowledge.integration.ts b/apps/sim/lib/workspace-source/application/knowledge.integration.ts index 09eddb6d484..7218af16b16 100644 --- a/apps/sim/lib/workspace-source/application/knowledge.integration.ts +++ b/apps/sim/lib/workspace-source/application/knowledge.integration.ts @@ -1341,6 +1341,10 @@ describe('knowledge bases as workspace source', () => { const missing = await refusal(apply(workspaceId, inFolder, { carry: 'none' })) expect(codes(missing.diagnostics)).toEqual(['E_KB_FOLDER']) + expect(missing.diagnostics[0]).toMatchObject({ + file: POLICIES_FILE, + hint: expect.stringContaining('`sim knowledge folders create "support"`'), + }) expect(await knowledgeBases(workspaceId)).toEqual([]) await createKnowledgeFolder.execute({ diff --git a/apps/sim/lib/workspace-source/application/plan.ts b/apps/sim/lib/workspace-source/application/plan.ts index 9a65e58c071..f284bd0bedb 100644 --- a/apps/sim/lib/workspace-source/application/plan.ts +++ b/apps/sim/lib/workspace-source/application/plan.ts @@ -169,7 +169,9 @@ function resolveRefsById(changes: PlannedChange[]): void { change.refs = change.refs.flatMap((ref) => { if (ref.id === undefined) return [ref] const key = byId.get(`${ref.kind}:${ref.id}`) - return key === undefined ? [] : [{ kind: ref.kind, key }] + return key === undefined + ? [] + : [{ kind: ref.kind, key, ...(ref.span ? { span: ref.span } : {}) }] }) } } @@ -484,7 +486,7 @@ function holdUnavailable(changes: PlannedChange[]): void { for (const ref of change.refs ?? []) { const reference = unavailable.get(resourceAddress(ref.kind, ref.key)) if (!reference) continue - change.diagnostics.push(refUnavailableFinding(change, reference)) + change.diagnostics.push(refUnavailableFinding(change, reference, ref.span)) change.held = true const placeholder = ref.kind === 'credential' ? placeholders.get(ref.key) : undefined if (placeholder !== undefined) { diff --git a/apps/sim/lib/workspace-source/application/references.integration.ts b/apps/sim/lib/workspace-source/application/references.integration.ts index 253ce48862b..fde0fe86149 100644 --- a/apps/sim/lib/workspace-source/application/references.integration.ts +++ b/apps/sim/lib/workspace-source/application/references.integration.ts @@ -323,6 +323,8 @@ describe('workspace source: secrets and credentials', () => { ) const missing = dryRun.diagnostics.find((finding) => finding.code === 'E_SECRET_MISSING') expect(missing?.hint).toContain('sim secrets set OPENAI_API_KEY --scope workspace') + expect(missing).toMatchObject({ file: 'workflows/ask/workflow.ts', line: 8 }) + expect(codes(dryRun.diagnostics, 'warning')).not.toContain('W_ENV_UNKNOWN') expect(held(dryRun.plan)).toEqual(['workflow:ask']) expect(dryRun.refuses).toBe(false) @@ -341,6 +343,30 @@ describe('workspace source: secrets and credentials', () => { } ) + check( + 'a workflow that runs a held-back workflow is held too, at the line that runs it', + async () => { + const workspaceId = await newWorkspace() + const files = { + 'secrets.ts': SECRETS(), + 'workflows/child/workflow.ts': ASK, + 'workflows/parent/workflow.ts': RUNS_CHILD, + } + + const dryRun = await apply(workspaceId, files, { dryRun: true }) + + expect(held(dryRun.plan)).toEqual(['workflow:child', 'workflow:parent']) + const lines = RUNS_CHILD.split('\n') + expect(dryRun.diagnostics).toContainEqual( + expect.objectContaining({ + code: 'E_PLAN_REF_HELD', + file: 'workflows/parent/workflow.ts', + line: lines.findIndex((line) => line.includes("runWorkflow('Run'")) + 1, + }) + ) + } + ) + check( 'refuses deleting a workflow a held-back edit stops running, since the stored one still runs it', async () => { diff --git a/apps/sim/lib/workspace-source/application/rows.integration.ts b/apps/sim/lib/workspace-source/application/rows.integration.ts index 85f6e449e87..1944f367c46 100644 --- a/apps/sim/lib/workspace-source/application/rows.integration.ts +++ b/apps/sim/lib/workspace-source/application/rows.integration.ts @@ -268,7 +268,7 @@ describe('table rows as workspace source', () => { expect(planned.diagnostics.filter((finding) => finding.severity === 'error')).toEqual([]) const result = await apply(workspaceId, edited, { base: read.base }) expect(result.applied).toMatchObject([ - { kind: 'table', key: 'plans', action: 'update', fields: ['rows (3)'] }, + { kind: 'table', key: 'plans', action: 'update', fields: ['rows (+1 ~1 -0)'] }, ]) expect(await storedRows(workspaceId)).toEqual([ { code: 'duo', seats: 2 }, @@ -479,6 +479,42 @@ export default defineTable({ } ) + check( + 'managed rows that spell a timestamp as JavaScript prints it plan as no change once stored', + async () => { + const workspaceId = await newWorkspace() + const timed = `// @sim-sdk 1 +import { column, defineTable } from '@sim/workflow-sdk/workspace' + +export default defineTable({ + name: 'timed', + columns: { + sku: column.string({ required: true, unique: true }), + shipped: column.date(), + expires: column.ttl(), + }, + rows: { mode: 'managed', key: 'sku' }, +}) +` + const directory = { + 'tables/timed.ts': timed, + 'tables/timed.rows.jsonl': `${JSON.stringify({ + sku: 'A-1', + shipped: new Date('2026-11-30T04:32:05Z').toISOString(), + expires: new Date('2099-01-01T00:00:00Z').toISOString(), + })}\n`, + } + const created = await apply(workspaceId, directory) + expect(created.failed).toBeUndefined() + const read = await runner.get(workspaceId) + expect(read.files['tables/timed.rows.jsonl']).not.toContain('.000Z') + + const resent = await apply(workspaceId, directory, { base: read.base, dryRun: true }) + + expect(resent.plan.filter((change) => change.action !== 'noop')).toEqual([]) + } + ) + check('a key rename is a delete and an insert, gated by allow-delete', async () => { const workspaceId = await newWorkspace() const read = await managedPlans(workspaceId) diff --git a/apps/sim/lib/workspace-source/application/types.ts b/apps/sim/lib/workspace-source/application/types.ts index 84e189e1f88..d8f8b016304 100644 --- a/apps/sim/lib/workspace-source/application/types.ts +++ b/apps/sim/lib/workspace-source/application/types.ts @@ -151,7 +151,7 @@ interface ChangeFields { key: string /** The part of the resource the reference names: an MCP server's tool. */ member?: string - /** Where the declaration's entry file writes the reference, when the pipeline located it. */ + /** Where the declaration writes the reference, relative to its folder, when located. */ span?: SourceSpan /** * The resource's id, for a kind keyed otherwise than a workflow names it (a workspace file, diff --git a/packages/workflow-code/src/compile/context.ts b/packages/workflow-code/src/compile/context.ts index 4673e4a7893..6abf10872fd 100644 --- a/packages/workflow-code/src/compile/context.ts +++ b/packages/workflow-code/src/compile/context.ts @@ -172,8 +172,11 @@ export interface CompileContext { envNames: ReadonlySet | undefined /** `CompileInput.envDeclaredIn`: the file the env names are declared in, when there is one. */ envDeclaredIn: string | undefined - /** Every env name the source reads, whether or not `envNames` holds it. */ - envReferences: Set + /** + * Every env name the source reads, whether or not `envNames` holds it, with where it is first + * read. + */ + envReferences: Map /** * JSON code fields written as literals. Their text depends on the output types of the blocks * they reference (`json-fields.ts`), so it is written once every block is compiled. diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index f5484c60e1e..8dca68204f4 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -164,10 +164,10 @@ export interface CompileResult { /** The header's major, or `null` when the header is missing. */ sdkMajor: number | null /** - * Every env name the source reads (`env.NAME`, and `$env.NAME` in code files), sorted: what a - * workspace apply checks against the secrets its directory declares. + * Every env name the source reads (`env.NAME`, and `$env.NAME` in code files), sorted by name: + * what a workspace apply checks against the secrets its directory declares. */ - envReferences: string[] + envReferences: EnvReference[] /** * Every edge the wiring denotes that passed validation, by block key, whether or not the * compile failed elsewhere: what an offline check records of a get's printed source as @@ -186,6 +186,12 @@ export interface CompileResult { untypedJsonFields: UntypedJsonField[] } +/** An env name the source reads, and where it is first read. */ +export interface EnvReference { + name: string + span: SourceSpan +} + /** A JSON field holding bare references nothing types: the text it stores and those references. */ export interface UntypedJsonField { block: BlockKey @@ -694,7 +700,7 @@ function compileEntry( ), envNames: input.envNames, envDeclaredIn: input.envDeclaredIn, - envReferences: new Set(), + envReferences: new Map(), jsonFields: [], dynamicOutputRefs: [], unresolvedTags: [], @@ -940,7 +946,9 @@ function compileEntry( metaSpans: ctx.metaSpans, hints, sdkMajor: parsed.sdkMajor, - envReferences: [...ctx.envReferences].sort(compareStrings), + envReferences: [...ctx.envReferences] + .map(([name, span]) => ({ name, span })) + .sort((a, b) => compareStrings(a.name, b.name)), edges: sortedEdges.map((edge) => ({ from: edge.from, port: portKey(edge.port), to: edge.to })), edgeSpans: written.map(({ node }) => reporter.span(rangeOf(ctx, node))), untypedJsonFields, diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index 201a43c9e7a..fa6594bb451 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -776,7 +776,7 @@ function segmentsOf( * only what that file lists, not what the workspace holds, so the finding says that instead. */ function checkEnvName(ctx: CompileContext, name: string, at: Range, blockKey: BlockKey): void { - ctx.envReferences.add(name) + if (!ctx.envReferences.has(name)) ctx.envReferences.set(name, ctx.reporter.span(at)) const envNames = ctx.envNames if (!envNames || envNames.has(name)) return ctx.reporter.report( diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 18434935835..c7176b17135 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -55,6 +55,7 @@ export { type CompileInput, type CompileResult, compileWorkflow, + type EnvReference, type StoredEdgeRef, type UntypedJsonField, } from './compile' diff --git a/packages/workspace-code/src/diagnostics/codes.ts b/packages/workspace-code/src/diagnostics/codes.ts index b0bc94ad38a..c3f734e6c2c 100644 --- a/packages/workspace-code/src/diagnostics/codes.ts +++ b/packages/workspace-code/src/diagnostics/codes.ts @@ -77,7 +77,10 @@ const BASE_CODES = [ const SECRET_CODES = [ /** A declared name outside the secret name format. */ 'E_SECRET_NAME', - /** A workflow uses a declared secret the workspace holds no value for: it is held back. */ + /** + * A workflow reads a declared secret the workspace holds no value for: it is held back. The + * finding points at the first line that reads it, and replaces `W_ENV_UNKNOWN` for that name. + */ 'E_SECRET_MISSING', /** A declared secret the workspace holds no value for. */ 'W_SECRET_MISSING', @@ -107,7 +110,7 @@ const TABLE_CODES = [ 'E_TABLE_OPTIONS', /** A type change the stored cells cannot convert to. */ 'E_TABLE_TYPE_CONVERSION', - /** A table folder that does not exist in the workspace. */ + /** A table folder that does not exist in the workspace. The hint creates each missing folder, parent first. */ 'E_TABLE_FOLDER', /** * The declaration's `rows` or its `tables/.rows.jsonl`: a bad mode or key column, a line @@ -191,7 +194,10 @@ const KNOWLEDGE_CODES = [ 'E_KB_DOC_EMPTY', /** Chunking settings outside what a knowledge base accepts. */ 'E_KB_CHUNKING', - /** A knowledge base folder that does not exist in the workspace. */ + /** + * A knowledge base folder that does not exist in the workspace. The hint creates each missing + * folder, parent first. + */ 'E_KB_FOLDER', /** A stored document whose bytes this request had no budget left to download and compare. */ 'W_KB_DOC_UNCHECKED', @@ -258,7 +264,10 @@ const PLAN_CODES = [ 'E_APPLY_FAILED', /** The apply would make more changes or touch more workflows than one request may. */ 'E_PLAN_TOO_LARGE', - /** A declared resource references one this apply deletes. */ + /** + * A declared resource references one this apply deletes. For an edited workflow, the finding + * points at the line that uses it. + */ 'E_PLAN_REF_DELETED', /** A declared resource references one this apply holds back, so it is held back too. */ 'E_PLAN_REF_HELD', diff --git a/packages/workspace-code/src/kind.ts b/packages/workspace-code/src/kind.ts index cd6bdcdadae..e63aebf5fb6 100644 --- a/packages/workspace-code/src/kind.ts +++ b/packages/workspace-code/src/kind.ts @@ -107,6 +107,8 @@ export interface PrintedDeclaration { export interface KindLayout { /** Groups the kind's paths by resource key; a path no resource owns is `E_DECL_UNKNOWN_FILE`. */ group(paths: readonly string[]): GroupedPaths + /** The file that declares resource `key`: where a finding about the resource points. */ + declarationPath(key: string): string /** * The name a resource's base entry records one of its blobs under; a kind without it records * each blob under its workspace path. diff --git a/packages/workspace-code/src/kinds/deployment.ts b/packages/workspace-code/src/kinds/deployment.ts index 8ef1647ea76..d3722ba4a13 100644 --- a/packages/workspace-code/src/kinds/deployment.ts +++ b/packages/workspace-code/src/kinds/deployment.ts @@ -330,6 +330,7 @@ function parseDeployment( /** Reads and prints `deployments/.ts`. */ export const deploymentCodec: KindCodec = { group: (paths) => groupByFile(KIND_DIRS.deployment, DECLARATION_EXTENSION, paths), + declarationPath: deploymentDeclarationPath, parse: (key, text) => parseDeployment(key, text), print: (key, decl) => ({ text: { diff --git a/packages/workspace-code/src/kinds/entries.ts b/packages/workspace-code/src/kinds/entries.ts index 8df8319ec6c..effe7c26e07 100644 --- a/packages/workspace-code/src/kinds/entries.ts +++ b/packages/workspace-code/src/kinds/entries.ts @@ -70,6 +70,7 @@ export function entryCodec(spec: EntryKind): KindCodec> const file = KIND_DIRS[spec.kind] return { group: (paths) => groupRootFile(spec.kind, paths), + declarationPath: () => file, parse(key, text) { const resource = resourceOf(spec.kind, key) const source = text[file] ?? '' diff --git a/packages/workspace-code/src/kinds/files.ts b/packages/workspace-code/src/kinds/files.ts index 71c6601c49d..0ff470123ac 100644 --- a/packages/workspace-code/src/kinds/files.ts +++ b/packages/workspace-code/src/kinds/files.ts @@ -252,6 +252,7 @@ export function fileFingerprint(sha256: string): ResourceFingerprint { export const fileCodec: KindCodec = { isBlob: () => true, group: groupFiles, + declarationPath: fileBlobPath, parse: parseFile, print: (key, decl) => ({ text: {}, diff --git a/packages/workspace-code/src/kinds/knowledge.ts b/packages/workspace-code/src/kinds/knowledge.ts index 96717afe5e2..988a76b143f 100644 --- a/packages/workspace-code/src/kinds/knowledge.ts +++ b/packages/workspace-code/src/kinds/knowledge.ts @@ -420,6 +420,7 @@ const DOCUMENT_PATH = new RegExp(`^${KIND_DIRS['knowledge-base']}/[^/]+/${DOCS_F export const knowledgeCodec: KindCodec = { isBlob: (path) => DOCUMENT_PATH.test(path), group: groupKnowledge, + declarationPath: knowledgeDeclarationPath, baseBlobName: (key, path) => path.slice(knowledgeDocPath(key, '').length), baseBlobPath: knowledgeDocPath, parse: parseKnowledgeBase, diff --git a/packages/workspace-code/src/kinds/mcp.ts b/packages/workspace-code/src/kinds/mcp.ts index 817f213e20b..c1971094709 100644 --- a/packages/workspace-code/src/kinds/mcp.ts +++ b/packages/workspace-code/src/kinds/mcp.ts @@ -124,7 +124,7 @@ function wholeEnvName(value: string): string | null { } /** `mcp/.ts`. */ -export function mcpDeclarationPath(key: string): string { +function mcpDeclarationPath(key: string): string { return `${KIND_DIRS['mcp-server']}/${key}${DECLARATION_EXTENSION}` } @@ -364,6 +364,7 @@ function parseMcpServer( /** Reads and prints `mcp/.ts`. */ export const mcpCodec: KindCodec = { group: (paths) => groupByFile(KIND_DIRS['mcp-server'], DECLARATION_EXTENSION, paths), + declarationPath: mcpDeclarationPath, parse: (key, text) => parseMcpServer(key, text), print: (key, decl) => ({ text: { [mcpDeclarationPath(key)]: printDeclaration(CALLEE, printFields(MCP_FIELDS, decl)) }, diff --git a/packages/workspace-code/src/kinds/skills.ts b/packages/workspace-code/src/kinds/skills.ts index adb7c291bf8..5d26fa6bc05 100644 --- a/packages/workspace-code/src/kinds/skills.ts +++ b/packages/workspace-code/src/kinds/skills.ts @@ -46,7 +46,7 @@ const CONTENT_FIELD = 'content' satisfies keyof SkillDecl type Frontmatter = Omit /** `skills/.md`. */ -export function skillPath(key: string): string { +function skillPath(key: string): string { return `${KIND_DIRS.skill}/${key}${EXTENSION}` } @@ -231,6 +231,7 @@ function readQuoted(raw: string): string | null { /** Reads and prints `skills/.md`. */ export const skillCodec: KindCodec = { group: (paths) => groupByFile(KIND_DIRS.skill, EXTENSION, paths), + declarationPath: skillPath, parse: (key, text) => parseSkill(key, text), print: (key, decl) => ({ text: { diff --git a/packages/workspace-code/src/kinds/table-rows.ts b/packages/workspace-code/src/kinds/table-rows.ts index cd62f5a3342..1cf2172a37a 100644 --- a/packages/workspace-code/src/kinds/table-rows.ts +++ b/packages/workspace-code/src/kinds/table-rows.ts @@ -216,3 +216,34 @@ export function tableRowsFingerprint(rows: TableRowsDecl | undefined): ResourceF if (rows?.mode !== 'managed' || rows.key === undefined) return null return fingerprintOf({ key: rows.key, rows: sortedRows(rows.data, rows.key) }) } + +/** How many managed rows a write adds, changes and removes. */ +export interface TableRowChanges { + added: number + patched: number + removed: number +} + +/** + * How managed rows `next` differ from `current`, each matched by its `rowKey` cell as a keyed + * write matches it: a row only `next` holds is added, one only `current` holds is removed, and one + * whose filled cells differ is patched. A row without a key is in neither count. + */ +export function tableRowChanges( + current: readonly TableRowCells[], + next: readonly TableRowCells[], + rowKey: string +): TableRowChanges { + const byKey = (data: readonly TableRowCells[]) => + new Map(sortedRows(data, rowKey).map((row) => [rowKeyText(row[rowKey]), fingerprintOf(row)])) + const before = byKey(current) + const after = byKey(next) + const changes: TableRowChanges = { added: 0, patched: 0, removed: 0 } + for (const [key, row] of after) { + const was = before.get(key) + if (was === undefined) changes.added++ + else if (was !== row) changes.patched++ + } + for (const key of before.keys()) if (!after.has(key)) changes.removed++ + return changes +} diff --git a/packages/workspace-code/src/kinds/table.ts b/packages/workspace-code/src/kinds/table.ts index d08cdfe3203..ae064285b6d 100644 --- a/packages/workspace-code/src/kinds/table.ts +++ b/packages/workspace-code/src/kinds/table.ts @@ -54,7 +54,6 @@ import { groupByFile } from './group' import { parseTableRows, printTableRows, - rowKeyText, TABLE_ROWS_EXTENSION, TABLE_ROWS_MODES, type TableRowCells, @@ -205,17 +204,17 @@ export function refusedTableRows( } /** - * The text a declared managed row of `decl` is matched by ({@link rowKeyText}): its key cell - * coerced to the key column's type first, as a keyed write stores it, so `"007"` in a number key - * column matches the stored `7`. A value the column cannot hold is matched as written. + * `rows` as a write stores them: each cell coerced to its column's type, so `"007"` in a number + * column is `7` and a timestamp takes the spelling its column stores. A value the column cannot + * hold is kept as written, for {@link refusedTableRows} to refuse. */ -export function declaredRowKeyText(decl: TableDecl, row: TableRowCells): string | undefined { - const key = decl.rows?.key - const column = key !== undefined ? decl.columns[key] : undefined - if (key === undefined || !column || !Object.hasOwn(row, key)) return undefined - const cell: CellRow = { [key]: row[key] } - coerceRowCells(cell, [cellColumn(key, column)], () => 'reject') - return rowKeyText(cell[key]) +export function coercedTableRows(decl: TableDecl, rows: readonly TableRowCells[]): TableRowCells[] { + const columns = Object.entries(decl.columns).map(([key, column]) => cellColumn(key, column)) + return rows.map((row) => { + const cells = { ...row } + coerceRowCells(cells, columns, () => 'reject') + return cells + }) } /** Reads one owned option of a column into `column`, reporting a value the server would refuse. */ @@ -561,6 +560,7 @@ export const tableLayout: KindLayout = { extension: TABLE_ROWS_EXTENSION, holds: 'its rows', }), + declarationPath: tablePath, budgetOf: (path) => (path.endsWith(TABLE_ROWS_EXTENSION) ? 'rows' : 'declaration'), } diff --git a/packages/workspace-code/src/kinds/tools.ts b/packages/workspace-code/src/kinds/tools.ts index 2f491d66a53..a5cfd5a31ef 100644 --- a/packages/workspace-code/src/kinds/tools.ts +++ b/packages/workspace-code/src/kinds/tools.ts @@ -300,6 +300,7 @@ export const toolCodec: KindCodec = { extension: CODE_EXTENSION, holds: 'its code', }), + declarationPath: toolDeclarationPath, parse: (key, text) => parseTool(key, text), print(key, decl) { const code = decl.code diff --git a/packages/workspace-code/src/kinds/workflow.ts b/packages/workspace-code/src/kinds/workflow.ts index 725128518bc..8677c8a3116 100644 --- a/packages/workspace-code/src/kinds/workflow.ts +++ b/packages/workspace-code/src/kinds/workflow.ts @@ -63,6 +63,7 @@ export const workflowCodec: KindCodec = { budget: 'workflow', isUnchanged: (decl) => Object.keys(decl.files).length === 0, group: (paths) => groupByFolder(KIND_DIRS.workflow, paths), + declarationPath: (key) => `${workflowFolder(key)}/${SOURCE_ENTRY_FILE}`, parse(key, text) { const folder = `${workflowFolder(key)}/` const decl: WorkflowDecl = { files: {} } diff --git a/packages/workspace-code/src/specs.ts b/packages/workspace-code/src/specs.ts index c2f0d9f3763..5df16cd27c7 100644 --- a/packages/workspace-code/src/specs.ts +++ b/packages/workspace-code/src/specs.ts @@ -55,7 +55,7 @@ export const WORKSPACE_KIND_SPECS: { readonly [K in WorkspaceKind]: WorkspaceKin resourceKind: null, typeChecked: [KIND_DIRS.secret], manifestKey: 'secretDeclarations', - guide: `\`${KIND_DIRS.secret}\`: \`export default defineSecrets({ NAME: { description? } })\`, the workspace secrets workflows read, by name and description only (never a value: set one with \`sim secrets set NAME --scope workspace\`). A workflow: \`env.NAME\`; one using a declared secret the workspace has no value for is held back, and the rest apply.`, + guide: `\`${KIND_DIRS.secret}\`: \`export default defineSecrets({ NAME: { description? } })\`, the workspace secrets workflows read, by name and description only (never a value: set one with \`sim secrets set NAME --scope workspace\`). A workflow: \`env.NAME\`; one using a declared secret the workspace has no value for is held back, and the rest apply. A get prints only the secrets the workspace has a value for, so a declared secret without one stays only in your directory.`, }, credential: { noun: 'credential',