From 018e936ad4556420460bc6d088aafb189aeda3da Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 02:53:23 -0800 Subject: [PATCH 01/85] fix(sim-cli): SOURCE_DIR_BUSY help names the workflows source commands that share the lock --- apps/docs/content/docs/cli/reference.mdx | 8 ++++---- apps/docs/content/docs/cli/workspaces.mdx | 8 ++++---- .../src/commands/protocol/source-dir/command-lock.ts | 5 +++-- .../sim-cli/src/commands/protocol/source-exit-codes.ts | 2 +- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index b91e32700b9..37704a23d86 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -9960,7 +9960,7 @@ sim workspaces source get [options] A directory that already holds a .sim/base.json is refreshed from the workspace it was read from, whatever the profile's default workspace. -Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 7 the workspace has more resources of a kind than one directory holds; 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source command is using this directory (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 7 the workspace has more resources of a kind than one directory holds; 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [downloadFile](/api-reference/files/downloadFile), [downloadKnowledgeDocument](/api-reference/knowledge-bases/downloadKnowledgeDocument). @@ -10020,7 +10020,7 @@ Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its fra These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. -Exit 10 (busy, retry): another sim workspaces source command is using this directory (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. API request and response schemas: [getSourceCatalog](/api-reference/catalog/getSourceCatalog). @@ -10047,7 +10047,7 @@ sim workspaces source status [options] Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). -Exit 10 (busy, retry): another sim workspaces source command is using this directory (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource), [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). @@ -10083,6 +10083,6 @@ sim workspaces source diff [paths...] [options] Without --server, each file created, edited or deleted since the directory was read is shown against the text it was read at. The CLI records only each file's digest, so that text is the server's current text where it still matches the digest; a file the server changed since is named instead (compare it with --server). A binary file is shown by its sizes. Paths filter by file or folder (and in a workspace directory by kind:key, such as table:leads). Exit codes: 0 the differences were shown, whether or not there were any; 7 the source is too large for the server to read; 1 the command failed. -Exit 10 (busy, retry): another sim workspaces source command is using this directory (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource). diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 64e39c047d7..85ecad976b1 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -708,7 +708,7 @@ sim workspaces source get [options] A directory that already holds a .sim/base.json is refreshed from the workspace it was read from, whatever the profile's default workspace. -Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 7 the workspace has more resources of a kind than one directory holds; 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source command is using this directory (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 7 the workspace has more resources of a kind than one directory holds; 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [downloadFile](/api-reference/files/downloadFile), [downloadKnowledgeDocument](/api-reference/knowledge-bases/downloadKnowledgeDocument). @@ -733,7 +733,7 @@ sim workspaces source status [options] Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). -Exit 10 (busy, retry): another sim workspaces source command is using this directory (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource), [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). @@ -789,7 +789,7 @@ Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its fra These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. -Exit 10 (busy, retry): another sim workspaces source command is using this directory (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. API request and response schemas: [getSourceCatalog](/api-reference/catalog/getSourceCatalog). @@ -823,7 +823,7 @@ sim workspaces source diff [paths...] [options] Without --server, each file created, edited or deleted since the directory was read is shown against the text it was read at. The CLI records only each file's digest, so that text is the server's current text where it still matches the digest; a file the server changed since is named instead (compare it with --server). A binary file is shown by its sizes. Paths filter by file or folder (and in a workspace directory by kind:key, such as table:leads). Exit codes: 0 the differences were shown, whether or not there were any; 7 the source is too large for the server to read; 1 the command failed. -Exit 10 (busy, retry): another sim workspaces source command is using this directory (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource). diff --git a/packages/sim-cli/src/commands/protocol/source-dir/command-lock.ts b/packages/sim-cli/src/commands/protocol/source-dir/command-lock.ts index 5a05366adc9..13661563470 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/command-lock.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/command-lock.ts @@ -25,8 +25,9 @@ export const SOURCE_DIR_LOCK = '.sim/command.lock' /** The help line every command that holds {@link SOURCE_DIR_LOCK} adds to its exit codes. */ export const SOURCE_DIR_BUSY_HELP = ` -Exit ${SOURCE_BUSY_EXIT_CODE} (busy, retry): another sim workspaces source command is using this directory -(SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished.` +Exit ${SOURCE_BUSY_EXIT_CODE} (busy, retry): another sim workspaces source or workflows source command is using +this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one +again once it finished.` /** The file-system codes of a directory the user may not write: its lock cannot be taken. */ const UNWRITABLE_CODES: ReadonlySet = new Set(['EACCES', 'EPERM', 'EROFS']) diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index 24d9d4a8bd8..41613912bbc 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -161,7 +161,7 @@ function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRow[] { 'workspaces source apply': 'another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished', 'workspaces source get': - '(busy, retry) another sim workspaces source command is using this directory (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished', + '(busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished', }, }, { From 4bb3f762e8b03100d3b3fe919a9c1cd1554d8f25 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 02:55:39 -0800 Subject: [PATCH 02/85] improvement(sim-cli): show the edit loop and its key flags in the source group help --- .../sim-cli/src/commands/protocol/index.ts | 3 + .../src/commands/protocol/source-loop-help.ts | 58 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 packages/sim-cli/src/commands/protocol/source-loop-help.ts diff --git a/packages/sim-cli/src/commands/protocol/index.ts b/packages/sim-cli/src/commands/protocol/index.ts index d9b37e51f24..d5330c7057e 100644 --- a/packages/sim-cli/src/commands/protocol/index.ts +++ b/packages/sim-cli/src/commands/protocol/index.ts @@ -14,6 +14,7 @@ import { attachKnowledgeExport } from './knowledge-export' import { attachKnowledgeImport } from './knowledge-import' import { attachLogsFollow } from './logs-follow' import { attachResourceDirectoryCommands } from './resource-directory' +import { WORKFLOW_SOURCE_LOOP_HELP, WORKSPACE_SOURCE_LOOP_HELP } from './source-loop-help' import { attachTableImport } from './tables-import' import { attachWorkflowRunFollow } from './workflow-run-follow' import { attachWorkflowRunGet } from './workflow-run-get' @@ -93,6 +94,7 @@ export function attachProtocolCommands(program: Command): void { const source = group(workflows, 'source').description( 'Read and apply a workflow as TypeScript source (preview)' ) + source.addHelpText('after', WORKFLOW_SOURCE_LOOP_HELP) attachWorkflowSourceGet(source) attachWorkflowSourceApply(source) attachWorkflowSourceCreate(source) @@ -106,6 +108,7 @@ export function attachProtocolCommands(program: Command): void { const workspaceSource = group(workspaces, 'source').description( 'Read and apply a workspace as a code directory (preview)' ) + workspaceSource.addHelpText('after', WORKSPACE_SOURCE_LOOP_HELP) attachWorkspaceSourceGet(workspaceSource) attachWorkspaceSourceApply(workspaceSource) attachWorkspaceSourceCheck(workspaceSource) diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts new file mode 100644 index 00000000000..1c9aaa87c51 --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -0,0 +1,58 @@ +/** + * The group help of `sim workflows source` and `sim workspaces source`: the edit loop and the + * flags it needs, so a reader of the group needs no command's own `--help` to start. + */ +import { typecheckCommand } from '@sim/workflow-sdk/codegen' +import { SOURCE_DRIFT_EXIT_CODE, SOURCE_LOCAL_CHANGES_EXIT_CODE } from '../../exit-codes' +import { SOURCE_AGENTS_FILE } from './source-dir' + +/** The loop's steps as aligned `command what it does` rows. */ +function loopRows(rows: ReadonlyArray): string { + const width = Math.max(...rows.map(([command]) => command.length)) + 3 + return rows.map(([command, what]) => ` ${command.padEnd(width)}${what}`.trimEnd()).join('\n') +} + +/** The status line both groups end with, for a directory at `dir`. */ +function statusLine(group: string, dir: string): string { + return `\`${group} status --dir ${dir}\` shows what applying would do and +whether the server changed since the get (exit 0 clean, ${SOURCE_LOCAL_CHANGES_EXIT_CODE} your edits only, ${SOURCE_DRIFT_EXIT_CODE} the server changed). +Every exit code, and the rules for editing: ${SOURCE_AGENTS_FILE} in the directory.` +} + +/** `sim workflows source --help`, after the command list. */ +export const WORKFLOW_SOURCE_LOOP_HELP = ` +The loop: +${loopRows([ + ['sim workflows source get --dir ./wf', 'write workflow.ts, functions/* and .sim/'], + ['edit ./wf/workflow.ts', ''], + ['sim workflows source check --dir ./wf', 'offline: each error as file:line:column'], + [typecheckCommand('./wf'), 'type-check the edit'], + ['sim workflows source apply --dir ./wf --dry-run', 'the plan; nothing is written'], + ['sim workflows source apply --dir ./wf --yes', 'save the draft'], +])} +A new workflow: \`sim workflows source create --dir ./new\` writes a starter; edit and check it, +then \`create --dir ./new --yes\` creates the workflow, and the loop above goes on from there. + +Flags the loop needs: --allow-delete (apply: an edit that removes a block or variable is refused +without it), --deploy (apply, create: also deploy the saved draft), --force (get: replace another +workflow's source, or edits no apply has saved). +${statusLine('sim workflows source', './wf')}` + +/** `sim workspaces source --help`, after the command list. */ +export const WORKSPACE_SOURCE_LOOP_HELP = ` +The loop: +${loopRows([ + ['sim workspaces source get --dir ./ws', 'write tables/, workflows//, … and .sim/'], + ['edit the files', 'a new workflow: workflows//workflow.ts'], + ['sim workspaces source check --dir ./ws', 'offline: each error as file:line:column'], + [typecheckCommand('./ws'), 'type-check the edit'], + ['sim workspaces source apply --dir ./ws --dry-run', 'the plan; nothing is written'], + ['sim workspaces source apply --dir ./ws --yes', 'write it to the workspace'], +])} +Promote dev to prod: \`sim workspaces source apply --dir ./ws --to --dry-run\`, then +--yes. + +Flags the loop needs: --allow-delete (apply: a removed file, column, block or variable is refused +without it), --force (get: replace edits no apply has saved). A workflow deploys on apply when +deployments/.ts declares it. +${statusLine('sim workspaces source', './ws')}` From f99bc389057a9a04a3a73bf0da1b85a36c54e569 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 02:57:19 -0800 Subject: [PATCH 03/85] fix(workflow-persistence): load blocks and subflows in insertion order, as edges already do A full replace wrote every block with one created_at, so the id tie-break shuffled their order against the unordered index scan before it. Ties now break on ctid, and a save stamps the rows it inserts together a microsecond apart in the state's order, so a later diff save that rewrites a row in place cannot move it either. --- .../normalized-save.integration.ts | 55 +++++++++++++++++++ packages/workflow-persistence/src/load.ts | 27 ++++----- packages/workflow-persistence/src/save.ts | 36 ++++++++---- packages/workflow-persistence/src/types.ts | 5 +- 4 files changed, 97 insertions(+), 26 deletions(-) diff --git a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts index 10f31572999..e0184d8b3eb 100644 --- a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts +++ b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts @@ -368,6 +368,61 @@ describe('saveWorkflowToNormalizedTables', () => { expect(loaded?.edges.map((edge) => edge.id)).toEqual([`${workflowId}-z`, `${workflowId}-a`]) }) + it('loads blocks and subflows saved together in the order the state listed them, whatever a later save rewrote', async () => { + const workflowId = await insertWorkflow() + const blocks = [ + containerBlock(`${workflowId}-z-loop`, 'loop', 'Z loop'), + containerBlock(`${workflowId}-a-loop`, 'loop', 'A loop'), + functionBlock(`${workflowId}-y`, 'Y', 0), + functionBlock(`${workflowId}-b`, 'B', 100), + ] + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf(blocks, []))).toEqual({ + success: true, + }) + + const edited = structuredClone(blocks) + edited[0].name = 'Renamed' + edited[2].position = { x: 50, y: 50 } + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf(edited, []))).toEqual({ + success: true, + }) + const loaded = await loadWorkflowFromNormalizedTablesRaw(workflowId) + + expect(Object.keys(loaded?.blocks ?? {})).toEqual(blocks.map((block) => block.id)) + expect(Object.keys(loaded?.loops ?? {})).toEqual([blocks[0].id, blocks[1].id]) + }) + + it('loads blocks and subflows an older save wrote with one timestamp in the order they were inserted', async () => { + const workflowId = await insertWorkflow() + const createdAt = new Date() + const [zLoop, aLoop] = [`${workflowId}-z-loop`, `${workflowId}-a-loop`] + await db.insert(workflowBlocks).values( + [zLoop, aLoop].map((id) => ({ + id, + workflowId, + type: 'loop', + name: id, + positionX: '0', + positionY: '0', + createdAt, + })) + ) + await db.insert(workflowSubflows).values( + [zLoop, aLoop].map((id) => ({ + id, + workflowId, + type: 'loop', + config: { id, nodes: [], iterations: 1, loopType: 'for' }, + createdAt, + })) + ) + + const loaded = await loadWorkflowFromNormalizedTablesRaw(workflowId) + + expect(Object.keys(loaded?.blocks ?? {})).toEqual([zLoop, aLoop]) + expect(Object.keys(loaded?.loops ?? {})).toEqual([zLoop, aLoop]) + }) + it('saves and reloads a workflow at the 10,000-edge source limit, in order', async () => { const workflowId = await insertWorkflow() const blocks = ['b1', 'b2'].map((id, index) => diff --git a/packages/workflow-persistence/src/load.ts b/packages/workflow-persistence/src/load.ts index 31bfb779193..57afef0d7d6 100644 --- a/packages/workflow-persistence/src/load.ts +++ b/packages/workflow-persistence/src/load.ts @@ -11,7 +11,7 @@ import { import type { Edge } from '@xyflow/react' import { and, asc, eq, getTableColumns, inArray, isNull, type SQLWrapper, sql } from 'drizzle-orm' import { clampParallelBatchSize } from './subflow-helpers' -import type { DbOrTx, NormalizedWorkflowData } from './types' +import type { DbOrTx, GraphTable, NormalizedWorkflowData } from './types' const logger = createLogger('WorkflowPersistenceLoad') @@ -180,20 +180,21 @@ export async function loadWorkflowsFromNormalizedTablesRaw( } /** - * The order a workflow's edge rows load in, which the executor reads for a condition or router - * edge with no handle: creation order. A save writes its edges together, each a microsecond after - * the one before, so this is the order the state listed them in; rows written in one statement - * with one timestamp (older saves, a duplicate) keep the order they were inserted in. + * The order a workflow's block, edge or subflow rows load in: creation order. A save stamps the + * rows it inserts together a microsecond apart, in the order the state listed them, so this is + * that order; rows written in one statement with one timestamp (older saves, a duplicate, a + * paste) keep the order they were inserted in, as the unordered index scan before this returned + * them. The executor reads it for a condition or router edge with no handle, and the editor for + * its node order. */ -export function edgeLoadOrder() { - return [asc(workflowEdges.createdAt), sql`ctid`] as const +export function creationOrder(table: GraphTable) { + return [asc(table.createdAt), sql`ctid`] as const } /** * The block, edge and subflow rows of `workflowIds`: a list, or a query of ids that each graph - * query embeds as a subquery. Blocks and subflows come in creation order, ties by id, and edges - * in {@link edgeLoadOrder}, so the assembled graph's order is a fact of the stored rows, not of - * where an update left them in the heap. + * query embeds as a subquery, each in {@link creationOrder}, so the assembled graph's order is a + * fact of the stored rows, not of the query plan. */ async function selectGraphRows(tx: DbOrTx, workflowIds: string[] | (() => SQLWrapper)) { const ids = () => (typeof workflowIds === 'function' ? workflowIds() : workflowIds) @@ -205,17 +206,17 @@ async function selectGraphRows(tx: DbOrTx, workflowIds: string[] | (() => SQLWra }) .from(workflowBlocks) .where(inArray(workflowBlocks.workflowId, ids())) - .orderBy(asc(workflowBlocks.createdAt), asc(workflowBlocks.id)), + .orderBy(...creationOrder(workflowBlocks)), tx .select() .from(workflowEdges) .where(inArray(workflowEdges.workflowId, ids())) - .orderBy(...edgeLoadOrder()), + .orderBy(...creationOrder(workflowEdges)), tx .select() .from(workflowSubflows) .where(inArray(workflowSubflows.workflowId, ids())) - .orderBy(asc(workflowSubflows.createdAt), asc(workflowSubflows.id)), + .orderBy(...creationOrder(workflowSubflows)), ]) return { blocks, edges, subflows } } diff --git a/packages/workflow-persistence/src/save.ts b/packages/workflow-persistence/src/save.ts index b10a9959685..dccd63f97ab 100644 --- a/packages/workflow-persistence/src/save.ts +++ b/packages/workflow-persistence/src/save.ts @@ -11,14 +11,13 @@ import { import type { InferInsertModel, SQL } from 'drizzle-orm' import { and, eq, inArray, sql } from 'drizzle-orm' import type { PgInsertValue } from 'drizzle-orm/pg-core' -import { edgeLoadOrder } from './load' +import { creationOrder } from './load' import { pruneWorkflowSourceMeta } from './source-meta' import { generateLoopBlocks, generateParallelBlocks } from './subflow-helpers' -import type { DbOrTx } from './types' +import type { DbOrTx, GraphTable } from './types' const logger = createLogger('WorkflowPersistenceSave') -type GraphTable = typeof workflowBlocks | typeof workflowEdges | typeof workflowSubflows type BlockRow = InferInsertModel type EdgeRow = InferInsertModel type SubflowRow = InferInsertModel @@ -194,6 +193,19 @@ async function deleteRows( await tx.delete(table).where(and(eq(table.workflowId, workflowId), inArray(table.id, ids))) } +/** + * `rows` stamped a microsecond apart in their order, so a save's inserts load back in the order + * the state listed them (`creationOrder`) rather than by where the heap put them. + */ +function inCreationOrder( + rows: T[] +): Array & { createdAt: SQL }> { + return rows.map((row, index) => ({ + ...row, + createdAt: sql`now() + ${index} * interval '1 microsecond'`, + })) +} + /** * Makes the workflow's normalized block, edge and subflow rows match `state`, leaving the rows a * delete-all and re-insert would leave; a state with an edge to a block it does not hold is @@ -202,7 +214,7 @@ async function deleteRows( * untouched (keeping their timestamps), changed rows are rewritten, and missing or extra rows are * inserted or deleted, so an edit costs its size rather than the graph's. Edges, which nothing * references, are left alone when unchanged and in order, and otherwise rewritten whole in the - * state's order (see `edgeLoadOrder`). + * state's order. Rows inserted together are stamped in the state's order (see `creationOrder`). * * The stored rows are read `FOR UPDATE`, the rows a delete-all would lock. Writes run in * foreign-key order: an edge is retargeted before the block it left is deleted, so that block's @@ -248,7 +260,7 @@ export async function saveWorkflowToNormalizedTables( .select() .from(workflowEdges) .where(eq(workflowEdges.workflowId, workflowId)) - .orderBy(...edgeLoadOrder()) + .orderBy(...creationOrder(workflowEdges)) .for('update'), tx .select() @@ -270,22 +282,22 @@ export async function saveWorkflowToNormalizedTables( } await deleteRows(tx, workflowSubflows, workflowId, subflows.deleteIds) - if (blocks.inserts.length > 0) await tx.insert(workflowBlocks).values(blocks.inserts) + if (blocks.inserts.length > 0) { + await tx.insert(workflowBlocks).values(inCreationOrder(blocks.inserts)) + } await updateRows(tx, workflowBlocks, workflowId, blocks.updates, BLOCK_UPDATE_SET) if (rewriteEdges) { - const timed = desiredEdges.map((edge, index) => ({ - ...edge, - createdAt: sql`now() + ${index} * interval '1 microsecond'`, - })) - for (const batch of chunkArray(timed, EDGE_INSERT_BATCH)) { + for (const batch of chunkArray(inCreationOrder(desiredEdges), EDGE_INSERT_BATCH)) { await tx.insert(workflowEdges).values(batch) } } await deleteRows(tx, workflowBlocks, workflowId, blocks.deleteIds) - if (subflows.inserts.length > 0) await tx.insert(workflowSubflows).values(subflows.inserts) + if (subflows.inserts.length > 0) { + await tx.insert(workflowSubflows).values(inCreationOrder(subflows.inserts)) + } await updateRows(tx, workflowSubflows, workflowId, subflows.updates, SUBFLOW_UPDATE_SET) const savedBlockIds = new Set(Object.keys(state.blocks)) diff --git a/packages/workflow-persistence/src/types.ts b/packages/workflow-persistence/src/types.ts index ae640bd90ed..ea4caea1f94 100644 --- a/packages/workflow-persistence/src/types.ts +++ b/packages/workflow-persistence/src/types.ts @@ -1,4 +1,4 @@ -import type { db } from '@sim/db' +import type { db, workflowBlocks, workflowEdges, workflowSubflows } from '@sim/db' import type * as schema from '@sim/db/schema' import type { BlockState, Loop, Parallel } from '@sim/workflow-types/workflow' import type { Edge } from '@xyflow/react' @@ -14,6 +14,9 @@ export type DbOrTx = ExtractTablesWithRelations > +/** A table of a workflow's normalized graph. */ +export type GraphTable = typeof workflowBlocks | typeof workflowEdges | typeof workflowSubflows + export interface NormalizedWorkflowData { blocks: Record edges: Edge[] From 8d6605fefd3973609de08196b2e99b026005bc3d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 02:57:56 -0800 Subject: [PATCH 04/85] docs(self-hosting): realtime does not wait for migrations, so run them before new realtime pods --- apps/docs/content/docs/platform/self-hosting/upgrades.mdx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx index 8a7e09e33ba..2602b27aa69 100644 --- a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx +++ b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx @@ -286,6 +286,10 @@ Migrations are Drizzle SQL files plus registered script (data) migrations, appli - **Kubernetes** — an **init container on the app Deployment**. Every app pod waits for migrations to complete before it starts, so a failed migration blocks the rollout instead of starting an app against a mismatched schema. - **Docker Compose** — a one-shot `migrations` service with `restart: no` that runs before the app. + + Only the app waits for migrations. The realtime service starts without them: on Helm its pods have no migrations init container, and on Compose `realtime` does not depend on the `migrations` service. A realtime pod of the new release that starts before its migrations finish fails the editor writes that read a new table or column, such as deleting a block or a variable, until they do. Run the migrations before new realtime pods start: run the migration image yourself before `helm upgrade` (see [Migration environment](#migration-environment)), or stop `realtime` until the `migrations` service has exited successfully. + + Migrations are **forward-only**. Take the backup described in the upgrade procedure before applying them; there are no down-migrations. From 2698eabe8f39d4b1f102787c24bba3fb57f2724b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 02:58:00 -0800 Subject: [PATCH 05/85] improvement(sim-cli): teach renames, failures, retries and draft test runs in the source primer --- apps/docs/content/docs/workflows/code.mdx | 2 +- .../src/commands/protocol/source-primer.ts | 23 +++++++++++++------ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx index 03a2d5dfae4..17d8ba098b3 100644 --- a/apps/docs/content/docs/workflows/code.mdx +++ b/apps/docs/content/docs/workflows/code.mdx @@ -13,7 +13,7 @@ Workflows as code is in preview. When it is [enabled on your Sim deployment](/pl ## For coding agents [#for-coding-agents] -Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. `get` prints a short primer (the edit loop, how block identity and references work, deletes, deploy, exit codes, and the params of each builder the workflow already uses; in JSON output, its `primer` field), and the same primer opens `.sim/AGENTS.md`, the full guide. The loop: +Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. `get` prints a short primer (the edit loop, how block identity, references and renames work, failures and retries, test runs, deletes, deploy, exit codes, and the params of each builder the workflow already uses; in JSON output, its `primer` field), and the same primer opens `.sim/AGENTS.md`, the full guide. The loop: 1. `sim workflows source get --dir ` writes the workflow and the guide. 2. Edit `workflow.ts`. diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 89664fbeaef..fa3635a0837 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -24,8 +24,11 @@ import { SOURCE_AGENTS_FILE } from './source-dir' /** Which directory a primer is for. */ export type PrimerKind = 'workflow' | 'workspace' -/** The primer without its builder snippets stays within this many bytes. */ -export const PRIMER_MAX_BYTES = 3072 +/** + * The primer without its builder snippets stays within this many bytes: about one screen, room for + * the rules agents otherwise spend a lookup on (renames, failures, test runs). + */ +export const PRIMER_MAX_BYTES = 4096 /** At most this many snippets, and this many bytes of them; the rest are named for `params`. */ const MAX_SNIPPETS = 12 @@ -35,12 +38,14 @@ const MAX_SNIPPET_BYTES = 4096 const PARAMS_COMMAND = 'sim workflows source params' /** The rules every source directory shares, after the kind's own edit loop. */ -function sharedRules(group: string): string { - return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, which binds it by its const name or its display name. Change the display name (first argument) freely. Renaming the const too keeps it when settings, neighbours or references still tie it to the old block; otherwise the apply refuses a delete (\`E_APPLY_BLOCK_DELETE\`). Safest: keep the const. -- **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function code file (\`codeFile('./functions/x.js')\`) read an output as \`$ref..\`, the key being the display name lowercased, whitespace and dots removed ("Triage Agent" → \`$ref.triageagent.content\`); in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\`, in a parallel \`$ref.parallel.currentItem\` / \`$ref.parallel.index\`; env as \`$env.NAME\`. In \`.py\`/\`.sh\` files write \`\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A rename rewrites \`$ref.\` to the new key. A \`$ref\` naming no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). +function sharedRules(group: string, extraRenames = ''): string { + return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, which binds it by its const name or its display name. Change the display name (first argument) freely: references through the const follow it, and the apply rewrites every \`$ref.\` and \`\` to the new key and reprints the files (don't hand-edit them). Renaming the const too keeps it when settings, neighbours or references still tie it to the old block; otherwise the apply refuses a delete (\`E_APPLY_BLOCK_DELETE\`). Safest: keep the const. +- **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function code file (\`codeFile('./functions/x.js')\`) read an output as \`$ref..\`, the key being the display name lowercased, whitespace and dots removed ("Triage Agent" → \`$ref.triageagent.content\`); in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\`, in a parallel \`$ref.parallel.currentItem\` / \`$ref.parallel.index\`; env as \`$env.NAME\`. In \`.py\`/\`.sh\` files write \`\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A \`$ref\` naming no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). +- **Renames**: one variable per apply (two at once read as a delete and an add).${extraRenames} - **Look up a builder**: \`${PARAMS_COMMAND} \` (\`agent\`, \`trigger.schedule\`; a namespace like \`gmail\` lists its builders), offline. - **Credentials**: \`sim credentials connect --name ""\`, give the owner its link, then \`credential('')\` (\`sim workflows source resources\`). -- **Run and debug**: \`sim workflows run --input '{…}'\` runs the deployed version (\`apply --deploy\` first); a failed run: \`sim logs get --trace --no-include-workflow-state\` (spans hold resolved inputs). +- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, reading the message as \`x.error\`. A retry is block meta, the third argument: \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\`. Branches that each reply: a \`response\` per branch. +- **Run and debug**: \`sim workflows run --manual --input '{…}'\` runs the saved draft, no deploy needed (without \`--manual\` it runs the deployed version). Runs write real data (rows, emails): test on test resources. A failed run: \`sim logs get --trace --no-include-workflow-state\` (spans hold resolved inputs). - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (\`${group} get --dir \`, redo the edit there), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed. Every code: \`${SOURCE_AGENTS_FILE}\`.` } @@ -55,6 +60,10 @@ const WORKFLOW_PRIMER = `# Sim workflow source: primer ${sharedRules('sim workflows source')} ` +/** What a rename in a workspace directory rewrites beyond a workflow's own blocks. */ +const WORKSPACE_RENAMES = + " A column: change its \`name\`, keep its key (cells stay); Table blocks using the old name are not rewritten (\`W_TABLE_COLUMN_RENAMED_IN_USE\`). A file's key never changes (\`E_KEY_RENAMED\`): rename by \`name\`." + const WORKSPACE_PRIMER = `# Sim workspace source: primer This directory is a Sim workspace as files (\`tables/\`, \`workflows//workflow.ts\`, …); read statically; nothing runs. Commands read the workspace id from \`${SOURCE_BASE_FILE}\`; run them from this directory. @@ -64,7 +73,7 @@ This directory is a Sim workspace as files (\`tables/\`, \`workflows//workf - **Deletes**: a removed file (a resource this directory managed), table column, workflow block or workflow variable is deleted only with \`apply --allow-delete\` (else refused), and cannot be undone. A kind is managed only when its folder exists. - **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply; without one, apply never deploys. - **Promote** (dev → prod): \`sim workspaces source apply --dir . --to --dry-run\`, then \`--yes\`. -${sharedRules('sim workspaces source')} +${sharedRules('sim workspaces source', WORKSPACE_RENAMES)} ` /** The primer for a `kind` directory, without builder snippets. */ From dec7d71f4ad76edd2b63697d8b9c0cd3fd7e78fe Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 02:59:43 -0800 Subject: [PATCH 06/85] docs(workflows): the code example acknowledges its webhook instead of replying with a Response the caller never sees --- apps/docs/content/docs/workflows/code.mdx | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx index 17d8ba098b3..16b5cd48091 100644 --- a/apps/docs/content/docs/workflows/code.mdx +++ b/apps/docs/content/docs/workflows/code.mdx @@ -98,7 +98,7 @@ Keep the `.sim/` folder the commands write. `.sim/lock.json` ties each block in ## Example: support triage -A webhook receives a ticket, an agent classifies it, billing tickets are logged to a table, and the team hears about them in Slack. This is the file `sim workflows source get` prints for it: +A webhook receives a ticket, an agent classifies it, billing tickets are logged to a table, and the team hears about every ticket in Slack. This is the file `sim workflows source get` prints for it: ```ts title="workflow.ts" // @sim-sdk 1 @@ -108,7 +108,6 @@ import { credential, env, js, - response, slack, t, table, @@ -124,6 +123,9 @@ export default workflow( requireAuth: true, token: env.TICKETS_WEBHOOK_TOKEN, inputFormat: { subject: 'string', body: 'string', contacts: 'array' }, + responseMode: 'custom', + responseStatusCode: 202, + responseBody: { ok: true }, }) const classify = agent('Classify', { messages: [ @@ -152,7 +154,6 @@ ${ticketIn.body}`, }) const byCategory = condition('By category', { billing: js`${classify.category} === 'billing'`, - urgent: js`${classify.urgent} === true`, else: true, }) const logTicket = table.insertRow('Log ticket', { @@ -162,21 +163,15 @@ ${ticketIn.body}`, const notify = slack.sendMessage('Notify', { credential: credential('support-slack'), channel: 'C0SUPPORT', - text: t`New ${classify.category} ticket: ${ticketIn.subject}`, - }) - const reply = response('Reply', { - body: { ok: true, category: classify.category, urgent: classify.urgent }, - status: 202, + text: t`New ${classify.category} ticket (urgent: ${classify.urgent}): ${ticketIn.subject}`, }) ticketIn.to(classify) classify.to(byCategory) byCategory.billing.to(logTicket) - byCategory.urgent.to(notify) - byCategory.else.to(reply) + byCategory.else.to(notify) logTicket.to(notify) logTicket.onError(notify) - notify.to(reply) } ) ``` @@ -187,7 +182,8 @@ How to read it: - `classify.category` is a typed reference to another block's output, the same as `` in the builder. `t` writes text with references in it; `js` writes code. - `table('tickets')` and `credential('support-slack')` name workspace resources by a stable key. Renaming the table in Sim keeps the key. - `env.TICKETS_WEBHOOK_TOKEN` reads an environment variable. Secret values are never printed: a key pasted into a password field prints as `stored()`, which keeps the saved value. -- `.to()` connects blocks, `byCategory.billing` is one branch of the condition, and `.onError()` follows the error path. +- `.to()` connects blocks, `byCategory.billing` is one branch of the condition, and `.onError()` follows the error path. `notify` has three incoming edges and runs once, after the branch that was taken. +- A webhook answers its caller as soon as the request is accepted and runs the workflow in the background, so the caller never sees a `response` block's output. `responseMode: 'custom'` sets that fixed answer (here `202` with `{ "ok": true }`; without it, `200` with `{ "message": "Webhook processed" }`). To answer with values the run computes, start the workflow with `trigger.start` and call it through the API; a `response` block then sets what the caller receives. ## Function code From eb4c5e5c8c182c6ac4dcd76c6e2452a282335795 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:00:54 -0800 Subject: [PATCH 07/85] fix(workflow-code): dry runs draw on the plan budget and take a plan slot, on every source write route A workflow dry run spent the source-write budget, and every dry run took an apply slot, so a dry-run loop could 429 real applies. A create from source is charged and admitted the same way, and its route now takes a slot too. --- .../docs/api-reference/getting-started.mdx | 2 +- .../[workflowId]/source/route.test.ts | 41 +++++++++++++++++-- .../v2/workflows/[workflowId]/source/route.ts | 13 +++--- .../[workspaceId]/source/route.test.ts | 29 +++++++++++++ .../workspaces/[workspaceId]/source/route.ts | 8 ++-- .../[workspaceId]/workflows/source/route.ts | 16 +++++--- .../api/server/routes/v2-json-route.test.ts | 2 +- .../lib/api/server/routes/v2-json-route.ts | 33 ++++----------- apps/sim/lib/workflows/api/index.ts | 2 +- apps/sim/lib/workflows/api/source-slots.ts | 17 ++++++-- .../protocol/workflow-source-status.ts | 2 +- 11 files changed, 115 insertions(+), 50 deletions(-) diff --git a/apps/docs/content/docs/api-reference/getting-started.mdx b/apps/docs/content/docs/api-reference/getting-started.mdx index 7fcecfc8b80..ae2cfc220da 100644 --- a/apps/docs/content/docs/api-reference/getting-started.mdx +++ b/apps/docs/content/docs/api-reference/getting-started.mdx @@ -239,7 +239,7 @@ Some endpoints return an unpaginated bounded inventory or a provider-specific pa ## Rate limits -V2 request limits apply to the credential and its user or workspace. Workflow execution also applies separate synchronous/asynchronous execution buckets, quota, and concurrency policy. Writing workflow source (applying it, a dry run, or creating a workflow from it) draws on one tighter budget of its own, 20 requests a minute with bursts of up to 40, on every plan. Plan and deployment configuration determine the other limits. +V2 request limits apply to the credential and its user or workspace. Workflow execution also applies separate synchronous/asynchronous execution buckets, quota, and concurrency policy. Writing workflow source (applying it, or creating a workflow from it) draws on one tighter budget of its own, 20 requests a minute with bursts of up to 40, on every plan. A dry run, which writes nothing, draws on the source plan budget the plan routes use instead, 30 requests a minute with bursts of up to 60. Plan and deployment configuration determine the other limits. A rate-limited request returns `429`; `Retry-After` gives seconds to wait. Inspect [Billing status](/api-reference/billing/getBillingStatus) for a workspace's current credits and storage. Async mode does not bypass admission or usage limits. diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts index 071f4a301e4..b71b4976b08 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts @@ -466,10 +466,40 @@ describe('source write rate limit', () => { expect((await GET(request(), context)).status).toBe(200) }) - it('answers 429 with Retry-After to a dry run past the applies this server runs at once', async () => { + it('charges a dry run, which writes nothing, to the plan bucket, and a real apply and create to the write bucket', async () => { + const charges = () => + v2RouteMocks.operationRate.mock.calls + .filter(([key]) => String(key).endsWith(':api-key:key-1')) + .map(([key]) => String(key).split(':')[1]) + const create = (query: string) => + CREATE( + new NextRequest( + `http://localhost:3000/api/v2/workspaces/${WORKSPACE_ID}/workflows/source${query}`, + { + method: 'POST', + headers: { 'x-api-key': 'key', 'content-type': 'application/json' }, + body: JSON.stringify({ files: source.files }), + } + ), + { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) } + ) + + expect((await POST(applyRequest(applyBody, '?dryRun=true'), context)).status).toBe(200) + expect((await create('?dryRun=true')).status).toBe(200) + expect(charges()).toEqual(['source.plan', 'source.plan']) + + v2RouteMocks.operationRate.mockClear() + expect((await POST(applyRequest(applyBody), context)).status).toBe(200) + expect((await create('')).status).toBe(200) + expect(charges()).toEqual(['workflows.source.write', 'workflows.source.write']) + }) + + it('runs dry runs in plan slots, never in an apply’s: past the plans this server runs at once a dry run answers 429 and a real apply still runs', async () => { const finish: Array<() => void> = [] - mocks.apply.mockImplementation( - () => new Promise((resolve) => finish.push(() => resolve({ ...applied, dryRun: true }))) + mocks.apply.mockImplementation(({ input }: { input: { dryRun?: boolean } }) => + input.dryRun + ? new Promise((resolve) => finish.push(() => resolve({ ...applied, dryRun: true }))) + : Promise.resolve(applied) ) const dryRun = () => POST(applyRequest(applyBody, '?dryRun=true'), context) const running = Array.from({ length: 4 }, () => dryRun()) @@ -478,6 +508,7 @@ describe('source write rate limit', () => { const refused = await dryRun() expect(refused.status).toBe(429) expect(refused.headers.get('Retry-After')).toBe('5') + expect((await POST(applyRequest(applyBody), context)).status).toBe(200) for (const done of finish) done() expect((await Promise.all(running)).map((response) => response.status)).toEqual([ @@ -551,11 +582,13 @@ describe('source plan budget', () => { }) it('answers 429 to plans well inside the generic budget, and never spends the write budget', async () => { + mocks.apply.mockResolvedValue(applied) const limitedAt = await writesUntilLimited(plan) expect(limitedAt).not.toBeNull() expect(limitedAt).toBeLessThan(GENERIC_BUDGET) - expect((await POST(applyRequest(applyBody, '?dryRun=true'), context)).status).toBe(200) + expect((await POST(applyRequest(applyBody, '?dryRun=true'), context)).status).toBe(429) + expect((await POST(applyRequest(applyBody), context)).status).toBe(200) }) it('answers 429 with Retry-After to a plan past the plans this server runs at once', async () => { diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts index b5b249a9a42..c393b80afc0 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts @@ -5,6 +5,7 @@ import { } from '@/lib/api/contracts/v2/workflow-source' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' import { + applyOrDryRunLane, presentSourceOutcome, v2WorkflowErrorPolicies, withBoundSourceFindings, @@ -46,15 +47,17 @@ export const GET = defineV2JsonRoute({ * all-or-nothing write. Error diagnostics (and a `base` read from another workflow) answer 400, a * stale fingerprint 409, a locked workflow 423; a dry run answers 200 with its diagnostics in the * body. Answers 403 while the `workflow-code` flag is off. Analytics are recorded by the use case. - * Applies and dry runs draw on the source-write budget (`v2RateLimits.sourceWrite`), not the - * generic one: each compiles and diffs a body of up to `SOURCE_REQUEST_MAX_BYTES`, so a server - * already running as many source applies as it allows answers 429 with `Retry-After`. + * Each compiles and diffs a body of up to `SOURCE_REQUEST_MAX_BYTES`, so neither draws on the + * generic budget: a real apply spends the source-write budget and takes an apply slot, and a dry + * run, which writes nothing, the source-plan budget and a plan slot, as the plan route does + * (`v2RateLimits.sourceApply`). A server already running as many as it allows answers 429 with + * `Retry-After`. */ export const POST = defineV2JsonRoute({ contract: v2ApplyWorkflowSourceContract, auth: v2ApiKeyAuth, operation: workflowOperations.applySource, - rateLimit: v2RateLimits.sourceWrite, + rateLimit: v2RateLimits.sourceApply, errorPolicy: v2WorkflowErrorPolicies.concealWorkflowGraphAuthorization, parseOptions: { maxBodyBytes: SOURCE_REQUEST_MAX_BYTES }, mapInput: ({ params, query, body }) => ({ @@ -66,6 +69,6 @@ export const POST = defineV2JsonRoute({ ...(query.dryRun !== undefined ? { dryRun: query.dryRun } : {}), ...(query.allowDelete !== undefined ? { allowDelete: query.allowDelete } : {}), }), - useCase: withSourceSlot(applyWorkflowSource, 'apply'), + useCase: withSourceSlot(applyWorkflowSource, applyOrDryRunLane), present: (result) => ({ data: presentSourceOutcome(result) }), }) diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts index c9710866aa6..570bbd210e3 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts @@ -106,6 +106,35 @@ describe('POST /api/v2/workspaces/{workspaceId}/source', () => { expect(charges()).toEqual(['workflows.source.write 1', 'workflows.source.write 39']) }) + it('runs dry runs in plan slots, never in an apply’s: past the plans this server runs at once a dry run answers 429 and a real apply still runs', async () => { + const result = { + workspaceId: WORKSPACE_ID, + dryRun: true, + plan: [], + applied: [], + needBlobs: [], + files: {}, + base: { version: 1, workspaceId: WORKSPACE_ID, resources: {} }, + diagnostics: [], + } + const finish: Array<() => void> = [] + mocks.apply.mockImplementation(({ input }: { input: { dryRun?: boolean } }) => + input.dryRun + ? new Promise((resolve) => finish.push(() => resolve(result))) + : Promise.resolve({ ...result, dryRun: false }) + ) + const running = Array.from({ length: 4 }, () => apply('?dryRun=true')) + await vi.waitFor(() => expect(finish).toHaveLength(4)) + + expect((await apply('?dryRun=true')).status).toBe(429) + expect((await apply('')).status).toBe(200) + + for (const done of finish) done() + expect((await Promise.all(running)).map((response) => response.status)).toEqual([ + 200, 200, 200, 200, + ]) + }) + it('answers a plan refused before any write with at most 1000 findings, and one that counts the rest', async () => { mocks.apply.mockRejectedValue(new WorkspaceSourceRejectedError(folderErrors(1_500))) diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts index dd95b4209ea..663f614a491 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts @@ -4,7 +4,7 @@ import { v2GetWorkspaceSourceContract, } from '@/lib/api/contracts/v2/workspace-source' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' -import { withSourceSlot } from '@/lib/workflows/api' +import { applyOrDryRunLane, withSourceSlot } from '@/lib/workflows/api' import { v2WorkspaceSourceErrorPolicy, withBoundWorkspaceFindings, @@ -45,8 +45,8 @@ export const GET = defineV2JsonRoute({ * 200 with its findings. A write that fails mid-apply answers 200 with `failed` and what was * written before it. A real apply draws on the source-write budget and a dry run, which writes * nothing, on the source-plan budget the status plan route uses (`v2RateLimits.sourceApply`), each - * charged per workflow folder sent with its files (`workspaceApplyRateCost`); a server already - * running as many applies as it allows answers 429. + * charged per workflow folder sent with its files (`workspaceApplyRateCost`), and runs in an apply + * or a plan slot to match; a server already running as many as it allows answers 429. */ export const POST = defineV2JsonRoute({ contract: v2ApplyWorkspaceSourceContract, @@ -67,6 +67,6 @@ export const POST = defineV2JsonRoute({ ...(query.dryRun !== undefined ? { dryRun: query.dryRun } : {}), }), rateLimitCost: (input) => workspaceApplyRateCost(input.files, input.blobs), - useCase: withSourceSlot(applyWorkspaceSource, 'apply'), + useCase: withSourceSlot(applyWorkspaceSource, applyOrDryRunLane), present: (result) => ({ data: withBoundWorkspaceFindings(result) }), }) diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.ts index f5ad727483c..04eb401563d 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.ts @@ -1,7 +1,12 @@ import { SOURCE_REQUEST_MAX_BYTES } from '@sim/workflow-code/limits' import { v2CreateWorkflowFromSourceContract } from '@/lib/api/contracts/v2/workflow-source' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' -import { presentSourceOutcome, v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { + applyOrDryRunLane, + presentSourceOutcome, + v2WorkflowErrorPolicies, + withSourceSlot, +} from '@/lib/workflows/api' import { createWorkflowFromSource } from '@/lib/workflows/application/apply-workflow-source' import { workflowOperations } from '@/lib/workflows/application/operations' @@ -12,14 +17,15 @@ export const revalidate = 0 * POST /api/v2/workspaces/[workspaceId]/workflows/source — creates a workflow from TypeScript * source through the same pipeline and checks as an apply, in one all-or-nothing write. Error * diagnostics answer 400 and nothing is created; a dry run answers 200 with its diagnostics and - * creates nothing. Answers 403 while the `workflow-code` flag is off. Shares the source-write budget - * with apply (`v2RateLimits.sourceWrite`). + * creates nothing. Answers 403 while the `workflow-code` flag is off. Charged and admitted as an + * apply is (`v2RateLimits.sourceApply`): a real create shares the source-write budget and the + * apply slots, and a dry run the source-plan budget and the plan slots. */ export const POST = defineV2JsonRoute({ contract: v2CreateWorkflowFromSourceContract, auth: v2ApiKeyAuth, operation: workflowOperations.createFromSource, - rateLimit: v2RateLimits.sourceWrite, + rateLimit: v2RateLimits.sourceApply, errorPolicy: v2WorkflowErrorPolicies.concealWorkspaceSourceCreate, parseOptions: { maxBodyBytes: SOURCE_REQUEST_MAX_BYTES }, mapInput: ({ params, query, body }) => ({ @@ -31,6 +37,6 @@ export const POST = defineV2JsonRoute({ ...(body.provenance ? { provenance: body.provenance } : {}), ...(query.dryRun !== undefined ? { dryRun: query.dryRun } : {}), }), - useCase: createWorkflowFromSource, + useCase: withSourceSlot(createWorkflowFromSource, applyOrDryRunLane), present: (result) => ({ data: presentSourceOutcome(result) }), }) diff --git a/apps/sim/lib/api/server/routes/v2-json-route.test.ts b/apps/sim/lib/api/server/routes/v2-json-route.test.ts index 7b8a28dc381..0b36a255be9 100644 --- a/apps/sim/lib/api/server/routes/v2-json-route.test.ts +++ b/apps/sim/lib/api/server/routes/v2-json-route.test.ts @@ -342,7 +342,7 @@ describe('defineV2JsonRoute', () => { contract, auth: v2ApiKeyAuth, operation, - rateLimit: v2RateLimits.sourceWrite, + rateLimit: v2RateLimits.sourceApply, errorPolicy: v2OrchestrationErrorPolicy, mapInput: ({ body }) => body, rateLimitCost: (input) => input.value.length, diff --git a/apps/sim/lib/api/server/routes/v2-json-route.ts b/apps/sim/lib/api/server/routes/v2-json-route.ts index 502c86a20ca..caadb578e3c 100644 --- a/apps/sim/lib/api/server/routes/v2-json-route.ts +++ b/apps/sim/lib/api/server/routes/v2-json-route.ts @@ -162,11 +162,10 @@ async function enforceV2Buckets( const VALIDATED_BODY_CACHE_MAX = 4 /** - * The budget for writing workflow source (apply, dry run, and create from source), per subject - * and on every plan. Each request parses, compiles, canonicalizes and diffs a body of up to + * The budget for writing workflow source (an apply or a create from source), per subject and on + * every plan. Each request parses, compiles, canonicalizes and diffs a body of up to * `SOURCE_REQUEST_MAX_BYTES`, so it costs far more than the row reads the generic budget is sized - * for; a dry run costs nearly as much as an apply, so it is charged the same amount (a workspace - * dry run on the plan bucket instead, see `sourceApply`). + * for. A dry run, which writes nothing, draws on the plan bucket instead (see `sourceApply`). */ const V2_SOURCE_WRITE_RATE_LIMIT: TokenBucketConfig = { maxTokens: 40, @@ -224,22 +223,6 @@ export const v2RateLimits = { return enforceV2Buckets(request, auth, operation.id, getRateLimit(plan, 'api-endpoint'), cost) }, } satisfies V2RateLimitPolicy, - /** - * {@link V2_SOURCE_WRITE_RATE_LIMIT}, one bucket shared by every source write, so alternating - * an apply and a create from source cannot double it. - */ - sourceWrite: { - maxCost: V2_SOURCE_WRITE_RATE_LIMIT.maxTokens, - async enforce(request, auth, _operation, cost = 1) { - return enforceV2Buckets( - request, - auth, - 'workflows.source.write', - V2_SOURCE_WRITE_RATE_LIMIT, - cost - ) - }, - } satisfies V2RateLimitPolicy, /** {@link V2_SOURCE_READ_RATE_LIMIT}, for reading a workspace as source. */ sourceRead: { async enforce(request, auth) { @@ -254,10 +237,12 @@ export const v2RateLimits = { }, } satisfies V2RateLimitPolicy, /** - * A source apply route that also serves dry runs (`?dryRun=true`): a dry run writes nothing and - * runs what a plan runs, so it draws on the {@link V2_SOURCE_PLAN_RATE_LIMIT} bucket as the plan - * routes do, and only a real apply spends the {@link V2_SOURCE_WRITE_RATE_LIMIT} bucket applies - * need. Capped at the smaller bucket, so the largest request fits either. + * A source write route (an apply or a create from source) that also serves dry runs + * (`?dryRun=true`): a dry run writes nothing and runs what a plan runs, so it draws on the + * {@link V2_SOURCE_PLAN_RATE_LIMIT} bucket as the plan routes do, and only a real write spends + * the {@link V2_SOURCE_WRITE_RATE_LIMIT} bucket, one shared by every source write so alternating + * an apply and a create cannot double it. Capped at the smaller bucket, so the largest request + * fits either. */ sourceApply: { maxCost: Math.min(V2_SOURCE_WRITE_RATE_LIMIT.maxTokens, V2_SOURCE_PLAN_RATE_LIMIT.maxTokens), diff --git a/apps/sim/lib/workflows/api/index.ts b/apps/sim/lib/workflows/api/index.ts index 37b1a68c40f..45bf083bdb5 100644 --- a/apps/sim/lib/workflows/api/index.ts +++ b/apps/sim/lib/workflows/api/index.ts @@ -9,7 +9,7 @@ export { } from '@/lib/workflows/api/route-policies' export { withBoundSourceFindings } from '@/lib/workflows/api/source-findings' export { presentSourceOutcome } from '@/lib/workflows/api/source-presenters' -export { withSourceSlot } from '@/lib/workflows/api/source-slots' +export { applyOrDryRunLane, withSourceSlot } from '@/lib/workflows/api/source-slots' export { presentV2WorkflowTrigger, presentV2WorkspaceSchedule, diff --git a/apps/sim/lib/workflows/api/source-slots.ts b/apps/sim/lib/workflows/api/source-slots.ts index 96d64e605b9..f7b8e562fe7 100644 --- a/apps/sim/lib/workflows/api/source-slots.ts +++ b/apps/sim/lib/workflows/api/source-slots.ts @@ -28,18 +28,19 @@ class SourceSlotBusyError extends Error { } /** - * `useCase`, run in one of its lane's slots: a get, plan or apply (each holds a workflow's or a - * directory's worth of text, stored state and canonical forms in memory) waits for nothing, and - * is refused with a `429` (see {@link renderSourceSlotBusy}) when the process already runs + * `useCase`, run in one of its lane's slots (`laneOf`, or the lane it picks for the input): a get, + * plan or apply (each holds a workflow's or a directory's worth of text, stored state and + * canonical forms in memory) waits for nothing, and is refused with a `429` (see {@link renderSourceSlotBusy}) when the process already runs * {@link MAX_CONCURRENT_SOURCE_REQUESTS} of them, so a burst cannot run the process out of memory. */ export function withSourceSlot( useCase: AuthorizingUseCase, - lane: SourceLane + laneOf: SourceLane | ((input: I) => SourceLane) ): AuthorizingUseCase { return { ...useCase, async execute(args) { + const lane = typeof laneOf === 'function' ? laneOf(args.input) : laneOf if (runningSourceRequests[lane] >= MAX_CONCURRENT_SOURCE_REQUESTS[lane]) { throw new SourceSlotBusyError(lane) } @@ -53,6 +54,14 @@ export function withSourceSlot( } } +/** + * The lane of a source apply route that also serves dry runs: a dry run writes nothing and runs + * what a plan runs, so it takes a plan slot and never one a real apply needs. + */ +export function applyOrDryRunLane(input: { dryRun?: boolean }): SourceLane { + return input.dryRun ? 'plan' : 'apply' +} + /** A request {@link withSourceSlot} refused, as `429` with `Retry-After`; `null` for any other error. */ export function renderSourceSlotBusy(error: unknown): NextResponse | null { if (!(error instanceof SourceSlotBusyError)) return null diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts index a64e84ad222..10c35bde107 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts @@ -3,7 +3,7 @@ * source directory since it was read, on either side, without applying anything. Local changes * come from the file digests `.sim/written.json` records (for a `workflows/` folder, the * workspace directory's record: `readFolderWritten`); the server's from the plan read - * (`planWorkflowSource`: a dry run on the read budget, never the source-write one), whose + * (`planWorkflowSource`: a dry run on the source-plan budget, never the source-write one), whose * `E_APPLY_STALE` says the workflow changed since the base. */ import { compareStrings } from '@sim/utils/string' From e46874b2ed9f67d0d7fab8bb2c9a0390e0ceffa8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:01:20 -0800 Subject: [PATCH 08/85] feat(workflows): a manual run's --stop-after and --from-block take a block's name or key, and an unknown one lists the blocks --- apps/docs/content/docs/cli/reference.mdx | 4 +- apps/docs/content/docs/cli/workflows.mdx | 4 +- apps/docs/openapi-v2-workflows.json | 4 +- apps/sim/lib/api/contracts/v2/workflows.ts | 6 +- .../execute-manual-workflow.test.ts | 71 +++++++++++++++++ .../application/execute-manual-workflow.ts | 79 ++++++++++++++----- .../protocol/workflow-run-follow.test.ts | 2 +- .../commands/protocol/workflow-run-follow.ts | 13 +-- 8 files changed, 148 insertions(+), 35 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index b91e32700b9..cd8fb68a6f1 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8441,9 +8441,9 @@ sim workflows run [options] | `--manual` | No | Run the current saved workflow state instead of the active deployment. | | `--trigger ` | No | Enter the run through this runnable trigger; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | -| `--from-block ` | No | Run manually from this saved workflow block. | +| `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | -| `--stop-after ` | No | Stop the run after this saved block, failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | +| `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | | `--follow` | No | Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns. | | `--include-thinking` | No | Show model reasoning while following (requires --follow). | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 7e76fc8249d..d3b15455d5a 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -771,9 +771,9 @@ sim workflows run [options] | `--manual` | No | Run the current saved workflow state instead of the active deployment. | | `--trigger ` | No | Enter the run through this runnable trigger; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | -| `--from-block ` | No | Run manually from this saved workflow block. | +| `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | -| `--stop-after ` | No | Stop the run after this saved block, failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | +| `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | | `--follow` | No | Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns. | | `--include-thinking` | No | Show model reasoning while following (requires --follow). | diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 785097e19cd..b1c49b2d6fb 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17453,7 +17453,7 @@ "blockId": { "type": "string", "minLength": 1, - "description": "Saved workflow block at which manual execution should resume." + "description": "Saved workflow block at which manual execution should resume: its id, display name or reference key (the name lowercased, whitespace and dots removed)." }, "sourceRunId": { "type": "string", @@ -17467,7 +17467,7 @@ ] }, "stopAfterBlockId": { - "description": "Saved workflow block after which the run stops; downstream blocks do not execute. Must not be inside a loop or parallel. If a router, condition, or untaken error path routes the run away from the block, the run fails as soon as that is decided; no further block starts, though blocks already running finish. With a block entry naming the same block, re-runs only that block against the source run.", + "description": "Saved workflow block after which the run stops (its id, display name or reference key); downstream blocks do not execute. Must not be inside a loop or parallel. If a router, condition, or untaken error path routes the run away from the block, the run fails as soon as that is decided; no further block starts, though blocks already running finish. With a block entry naming the same block, re-runs only that block against the source run.", "type": "string", "minLength": 1 } diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 01689947160..fcff30dd9d9 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1654,7 +1654,9 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ blockId: z .string() .min(1, 'run.entry.blockId cannot be empty') - .describe('Saved workflow block at which manual execution should resume.'), + .describe( + 'Saved workflow block at which manual execution should resume: its id, display name or reference key (the name lowercased, whitespace and dots removed).' + ), sourceRunId: z .string() .min(1, 'run.entry.sourceRunId cannot be empty') @@ -1673,7 +1675,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .min(1, 'run.stopAfterBlockId cannot be empty') .optional() .describe( - 'Saved workflow block after which the run stops; downstream blocks do not execute. Must not be inside a loop or parallel. If a router, condition, or untaken error path routes the run away from the block, the run fails as soon as that is decided; no further block starts, though blocks already running finish. With a block entry naming the same block, re-runs only that block against the source run.' + 'Saved workflow block after which the run stops (its id, display name or reference key); downstream blocks do not execute. Must not be inside a loop or parallel. If a router, condition, or untaken error path routes the run away from the block, the run fails as soon as that is decided; no further block starts, though blocks already running finish. With a block entry naming the same block, re-runs only that block against the source run.' ), }) .strict(), diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts index 200241c8656..3efe284975e 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts @@ -408,6 +408,77 @@ describe('manual workflow execution application operations', () => { expect(mocks.executeService).not.toHaveBeenCalled() }) + it('resolves a stop or entry block named by its display name or reference key', async () => { + mockLoadManualState.mockResolvedValue({ + blocks: { + 'trigger-1': { name: 'Lead in' }, + 'agent-1': { name: 'Score lead' }, + 'agent-2': { name: 'Reply' }, + }, + edges: [ + { source: 'trigger-1', target: 'agent-1' }, + { source: 'agent-1', target: 'agent-2' }, + ], + }) + mocks.loadSourceState.mockResolvedValue({ blockStates: {} }) + + await executeManualWorkflowOperation.execute({ + principal, + input: { ...baseInput, useMockPayload: false, stopAfterBlockId: 'Score lead' }, + }) + expect(mocks.executeService).toHaveBeenLastCalledWith( + expect.objectContaining({ stopAfterBlockId: 'agent-1' }) + ) + + await executeManualWorkflowFromBlockOperation.execute({ + principal, + input: { + ...baseInput, + blockId: 'scorelead', + sourceRunId: 'source-run-1', + stopAfterBlockId: 'reply', + }, + }) + expect(mocks.executeService).toHaveBeenLastCalledWith( + expect.objectContaining({ + stopAfterBlockId: 'agent-2', + runFromBlock: expect.objectContaining({ startBlockId: 'agent-1' }), + }) + ) + }) + + it('refuses a block selector naming no block or several, listing the candidates', async () => { + mockLoadManualState.mockResolvedValue({ + blocks: { + 'trigger-1': { name: 'Start' }, + 'agent-1': { name: 'Score lead' }, + 'agent-2': { name: 'Score Lead' }, + }, + edges: [{ source: 'trigger-1', target: 'agent-1' }], + }) + + await expect( + executeManualWorkflowOperation.execute({ + principal, + input: { ...baseInput, useMockPayload: false, stopAfterBlockId: 'scorer' }, + }) + ).rejects.toMatchObject({ + code: 'validation', + message: expect.stringContaining('"Score lead" (agent-1)'), + }) + await expect( + executeManualWorkflowFromBlockOperation.execute({ + principal, + input: { ...baseInput, blockId: 'scorelead', sourceRunId: 'source-run-1' }, + }) + ).rejects.toMatchObject({ + code: 'validation', + message: expect.stringContaining('names 2 blocks'), + }) + expect(mocks.loadSourceState).not.toHaveBeenCalled() + expect(mocks.executeService).not.toHaveBeenCalled() + }) + it('rejects a stop block named by an inherited object key', async () => { await expect( executeManualWorkflowOperation.execute({ diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.ts index f742270bddc..bed58c59f47 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.ts @@ -1,5 +1,6 @@ import { requirePrincipalSubjectUserId, type WorkflowExecutionPrincipal } from '@sim/auth/principal' import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks' +import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import { OrchestrationError } from '@/lib/core/orchestration/types' import { inlinesRunFiles, @@ -56,6 +57,44 @@ async function loadManualState(workflowId: string) { type ManualWorkflowState = Awaited> +/** At most this many block names are listed when a block selector matches none. */ +const MAX_LISTED_BLOCKS = 25 + +/** `name (id)` for each block of `ids`, at most {@link MAX_LISTED_BLOCKS} of them. */ +function listBlocks(state: ManualWorkflowState, ids: readonly string[]): string { + const shown = ids + .slice(0, MAX_LISTED_BLOCKS) + .map((id) => `"${state.blocks[id]?.name ?? id}" (${id})`) + const more = ids.length > MAX_LISTED_BLOCKS ? `, and ${ids.length - MAX_LISTED_BLOCKS} more` : '' + return `${shown.join(', ')}${more}` +} + +/** + * The id of the saved block `selector` names: its id, else the one block whose display name or + * reference key (the name lowercased, whitespace and dots removed: "Score lead" and `scorelead`) + * matches it. A selector matching no block, or several, is refused with the candidates, so a + * caller never has to read block ids out of the stored workflow. `field` names the wire field. + */ +function resolveBlockSelector(state: ManualWorkflowState, selector: string, field: string): string { + if (Object.hasOwn(state.blocks, selector)) return selector + const key = normalizeWorkflowBlockName(selector) + const matches = Object.keys(state.blocks).filter((id) => { + const name = state.blocks[id]?.name + return typeof name === 'string' && normalizeWorkflowBlockName(name) === key + }) + if (matches.length === 1) return matches[0] + if (matches.length > 1) { + throw new OrchestrationError( + 'validation', + `${field} "${selector}" names ${matches.length} blocks: ${listBlocks(state, matches)}. Pass one of their ids.` + ) + } + throw new OrchestrationError( + 'validation', + `${field} "${selector}" is not a block in the current saved workflow. Pass a block's id, name or key: ${listBlocks(state, Object.keys(state.blocks))}.` + ) +} + /** Blocks a run entering at `entryBlockId` can reach; the executor skips disabled blocks. */ function reachableFrom(state: ManualWorkflowState, entryBlockId: string): Set { const targetsBySource = new Map() @@ -77,26 +116,22 @@ function reachableFrom(state: ManualWorkflowState, entryBlockId: string): Set): string { @@ -194,7 +230,11 @@ export const executeManualWorkflowOperation = defineAuthorizedWorkflowUseCase({ ) } - assertStopAfterBlock(state, input.stopAfterBlockId, selected.triggerBlockId) + const stopAfterBlockId = resolveStopAfterBlock( + state, + input.stopAfterBlockId, + selected.triggerBlockId + ) const executionInput = input.useMockPayload ? selected.mockPayload : input.input const validation = validateTriggerInput(selected, executionInput) if (!validation.ok) { @@ -204,6 +244,7 @@ export const executeManualWorkflowOperation = defineAuthorizedWorkflowUseCase({ const result = await executeWorkflowService({ ...executionServiceInput({ principal, context, input, draftState: state }), + stopAfterBlockId, input: executionInput, triggerBlockId: selected.triggerBlockId, }) @@ -216,13 +257,8 @@ export const executeManualWorkflowFromBlockOperation = defineAuthorizedWorkflowU resolveContext: resolveContext, async execute({ principal, context, input }): Promise { const state = await loadManualState(context.workflowId) - if (!Object.hasOwn(state.blocks, input.blockId)) { - throw new OrchestrationError( - 'validation', - `run.entry.blockId "${input.blockId}" is not a block in the current saved workflow.` - ) - } - assertStopAfterBlock(state, input.stopAfterBlockId, input.blockId) + const blockId = resolveBlockSelector(state, input.blockId, 'run.entry.blockId') + const stopAfterBlockId = resolveStopAfterBlock(state, input.stopAfterBlockId, blockId) const sourceSnapshot = await getExecutionStateForWorkflow(input.sourceRunId, context.workflowId) if (!sourceSnapshot) { @@ -234,9 +270,10 @@ export const executeManualWorkflowFromBlockOperation = defineAuthorizedWorkflowU const result = await executeWorkflowService({ ...executionServiceInput({ principal, context, input, draftState: state }), + stopAfterBlockId, input: input.input, runFromBlock: { - startBlockId: input.blockId, + startBlockId: blockId, sourceSnapshot, sourceExecutionId: input.sourceRunId, }, diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index 125f57b5667..efc920960dd 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -372,7 +372,7 @@ describe('sim workflows run --follow', () => { it('refuses an empty --stop-after rather than running the whole draft', async () => { await expect(run(WORKFLOW_ID, '--stop-after', '')).rejects.toThrow( - '--stop-after requires a block ID' + '--stop-after requires a block id, name or key' ) expect(requestRaw).not.toHaveBeenCalled() }) 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 c2eaac496d2..f4bcf07d326 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -78,7 +78,7 @@ export function resolveWorkflowRunSelection( throw new SimApiError('--from-block requires --source-run ', 0) } if (sourceRun && !fromBlock) { - throw new SimApiError('--source-run requires --from-block ', 0) + throw new SimApiError('--source-run requires --from-block ', 0) } if ((manual || fromBlock) && flags.async === true) { throw new SimApiError( @@ -90,7 +90,7 @@ export function resolveWorkflowRunSelection( throw new SimApiError('--mock-payload cannot be combined with --input', 0) } if (stopAfter !== undefined && stopAfter.trim() === '') { - throw new SimApiError('--stop-after requires a block ID', 0) + throw new SimApiError('--stop-after requires a block id, name or key', 0) } const stop = stopAfter !== undefined ? { stopAfterBlockId: stopAfter } : {} @@ -583,14 +583,17 @@ export function attachWorkflowRunFollow(workflows: Command): void { '--mock-payload', "Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual)" ) - .option('--from-block ', 'Run manually from this saved workflow block') + .option( + '--from-block ', + 'Run manually from this saved workflow block: its id, display name or key' + ) .option( '--source-run ', 'Prior run whose persisted state supplies upstream outputs (requires --from-block)' ) .option( - '--stop-after ', - 'Stop the run after this saved block, failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual)' + '--stop-after ', + 'Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual)' ) .option( WAIT_TIMEOUT_FLAG, From 1da2959d8524a3bb57b9ccf462d9322fee0a0afc Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:03:07 -0800 Subject: [PATCH 09/85] fix(logs): a failed, cancelled or timed-out run records the input it ran with --- .../logs/execution/logging-session.test.ts | 20 +++++++++++++++++++ .../sim/lib/logs/execution/logging-session.ts | 6 ++++++ .../workflows/executor/execution-core.test.ts | 5 ++++- .../lib/workflows/executor/execution-core.ts | 11 +++++++++- 4 files changed, 40 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/logs/execution/logging-session.test.ts b/apps/sim/lib/logs/execution/logging-session.test.ts index 69c1211fb30..da6ad0bfbdf 100644 --- a/apps/sim/lib/logs/execution/logging-session.test.ts +++ b/apps/sim/lib/logs/execution/logging-session.test.ts @@ -986,6 +986,26 @@ describe('LoggingSession completion retries', () => { ) }) + it('persists the run input of a failed or cancelled run', async () => { + completeWorkflowExecutionMock.mockResolvedValue({}) + const failed = new LoggingSession('workflow-1', 'execution-7', 'manual', 'req-1') + failed.setResolvedSecretTraceRegistry(createSecretRegistry([])) + await failed.safeCompleteWithError({ + error: { message: 'boom' }, + workflowInput: { company: 'Acme' }, + }) + expect(completeWorkflowExecutionMock).toHaveBeenLastCalledWith( + expect.objectContaining({ executionId: 'execution-7', workflowInput: { company: 'Acme' } }) + ) + + const cancelled = new LoggingSession('workflow-1', 'execution-8', 'manual', 'req-1') + cancelled.setResolvedSecretTraceRegistry(createSecretRegistry([])) + await cancelled.safeCompleteWithCancellation({ workflowInput: { company: 'Acme' } }) + expect(completeWorkflowExecutionMock).toHaveBeenLastCalledWith( + expect.objectContaining({ executionId: 'execution-8', workflowInput: { company: 'Acme' } }) + ) + }) + it('marks paused completions as completed and deduplicates later attempts', async () => { const session = new LoggingSession('workflow-1', 'execution-1', 'api', 'req-1') diff --git a/apps/sim/lib/logs/execution/logging-session.ts b/apps/sim/lib/logs/execution/logging-session.ts index 425b4f80b6e..e461b36d00e 100644 --- a/apps/sim/lib/logs/execution/logging-session.ts +++ b/apps/sim/lib/logs/execution/logging-session.ts @@ -173,6 +173,8 @@ export interface SessionErrorCompleteParams { } traceSpans?: TraceSpan[] skipCost?: boolean + /** The input the run started with, once its input stage finished; absent for a run refused before it. */ + workflowInput?: unknown executionState?: SerializableExecutionState } @@ -180,6 +182,8 @@ export interface SessionCancelledParams { endedAt?: string totalDurationMs?: number traceSpans?: TraceSpan[] + /** The input the run started with. */ + workflowInput?: unknown executionState?: SerializableExecutionState } @@ -1094,6 +1098,7 @@ export class LoggingSession { costSummary, finalOutput: { error: message }, traceSpans: spans, + workflowInput: params.workflowInput, executionState: params.executionState, finalOutputResolvedSecretTraceProvenance: errorDisplayProvenance, level: 'error', @@ -1175,6 +1180,7 @@ export class LoggingSession { costSummary, finalOutput: { cancelled: true }, traceSpans, + workflowInput: params.workflowInput, executionState: params.executionState, finalOutputResolvedSecretTraceProvenance: emptyResolvedSecretTraceProvenance(), finalizationPath: 'cancelled', diff --git a/apps/sim/lib/workflows/executor/execution-core.test.ts b/apps/sim/lib/workflows/executor/execution-core.test.ts index cef607dbd34..fd5a8f4f24a 100644 --- a/apps/sim/lib/workflows/executor/execution-core.test.ts +++ b/apps/sim/lib/workflows/executor/execution-core.test.ts @@ -1511,6 +1511,7 @@ describe('executeWorkflowCore terminal finalization sequencing', () => { expect.objectContaining({ totalDurationMs: 123, traceSpans: [{ id: 'span-1' }], + workflowInput: { hello: 'world' }, executionState, }) ) @@ -1549,6 +1550,7 @@ describe('executeWorkflowCore terminal finalization sequencing', () => { error: { message: 'Execution timed out' }, totalDurationMs: 123, traceSpans: [{ id: 'span-1' }], + workflowInput: { hello: 'world' }, executionState, }) ) @@ -1849,7 +1851,7 @@ describe('executeWorkflowCore terminal finalization sequencing', () => { expect(safeCompleteWithErrorMock).toHaveBeenCalledTimes(1) expect(safeCompleteWithErrorMock).toHaveBeenCalledWith( - expect.objectContaining({ executionState }) + expect.objectContaining({ executionState, workflowInput: { hello: 'world' } }) ) expect(clearExecutionCancellationMock).toHaveBeenCalledWith('execution-1') expect(wasExecutionFinalizedByCore(error, 'execution-1')).toBe(true) @@ -1986,6 +1988,7 @@ describe('executeWorkflowCore terminal finalization sequencing', () => { }) ) expect(safeCompleteWithErrorMock).toHaveBeenCalledTimes(1) + expect(safeCompleteWithErrorMock.mock.calls[0]?.[0]?.workflowInput).toBeUndefined() expect(wasExecutionFinalizedByCore(envError, 'execution-1')).toBe(true) }) diff --git a/apps/sim/lib/workflows/executor/execution-core.ts b/apps/sim/lib/workflows/executor/execution-core.ts index b9331e41705..9aaea8aad30 100644 --- a/apps/sim/lib/workflows/executor/execution-core.ts +++ b/apps/sim/lib/workflows/executor/execution-core.ts @@ -379,6 +379,7 @@ async function finalizeExecutionOutcome(params: { totalDurationMs: totalDuration || 0, error: { message: getTimeoutErrorMessage() }, traceSpans: traceSpans || [], + workflowInput, executionState: result.executionState, }) } else if (result.status === 'cancelled') { @@ -386,6 +387,7 @@ async function finalizeExecutionOutcome(params: { endedAt, totalDurationMs: totalDuration || 0, traceSpans: traceSpans || [], + workflowInput, executionState: result.executionState, }) } else if (result.status === 'paused') { @@ -438,8 +440,10 @@ async function finalizeExecutionError(params: { workflowId: string executionId: string requestId: string + /** The input the executor ran with; absent when the run failed before its input stage finished. */ + workflowInput: unknown }): Promise { - const { error, loggingSession, workflowId, executionId, requestId } = params + const { error, loggingSession, workflowId, executionId, requestId, workflowInput } = params const executionResult = hasExecutionResult(error) ? error.executionResult : undefined const { traceSpans } = executionResult ? buildTraceSpansForLog(executionResult, loggingSession, requestId, executionId) @@ -455,6 +459,7 @@ async function finalizeExecutionError(params: { stackTrace: error instanceof Error ? error.stack : undefined, }, traceSpans, + workflowInput, executionState: executionResult?.executionState, }) @@ -702,6 +707,8 @@ async function executeWorkflowCoreImpl( } let processedInput = input || {} + /** The input the executor ran with, once the input stage (file fields, PII redaction) finished. */ + let executorInput: unknown let deploymentVersionId: string | undefined let loggingStarted = false let resolvedSecretTraceRegistry: ResolvedSecretTraceRegistry | undefined @@ -1357,6 +1364,7 @@ async function executeWorkflowCoreImpl( } } + executorInput = processedInput const executorInstance = new Executor({ workflow: serializedWorkflow, envVarValues: decryptedEnvVars, @@ -1453,6 +1461,7 @@ async function executeWorkflowCoreImpl( workflowId, executionId, requestId, + workflowInput: executorInput, }) : false From ae7a6df28be56448deea31c04448bcc4d478ba69 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:03:47 -0800 Subject: [PATCH 10/85] fix(workflow-code): the Code tab's source read takes a source read slot The internal read ran the same load, canonicalize and print as the v2 get with no slot. It now shares the read lane and answers 429 with Retry-After when the server is full. Its ETag stays after the read: the printed keys are known only once the graph is canonicalized, so no earlier tag is sound. --- .../api/workflows/[id]/source/route.test.ts | 76 +++++++++++++++++++ .../app/api/workflows/[id]/source/route.ts | 17 ++++- apps/sim/lib/workflows/api/route-policies.ts | 24 ++++-- apps/sim/lib/workflows/api/source-slots.ts | 14 ++++ 4 files changed, 123 insertions(+), 8 deletions(-) create mode 100644 apps/sim/app/api/workflows/[id]/source/route.test.ts diff --git a/apps/sim/app/api/workflows/[id]/source/route.test.ts b/apps/sim/app/api/workflows/[id]/source/route.test.ts new file mode 100644 index 00000000000..ac0fd810c6e --- /dev/null +++ b/apps/sim/app/api/workflows/[id]/source/route.test.ts @@ -0,0 +1,76 @@ +import { authMockFns } from '@sim/testing' +import { NextRequest } from 'next/server' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { mockRead } = vi.hoisted(() => ({ mockRead: vi.fn() })) + +vi.mock('@/lib/workflows/application/read-workflow-source', () => ({ + readWorkflowSource: { + operation: { + id: 'workflows.source.read', + minimumRole: 'read', + workspaceApiKey: 'allow', + principalKinds: ['session', 'personal_api_key', 'workspace_api_key'], + }, + authorize: vi.fn(async () => {}), + execute: mockRead, + }, +})) + +import { GET } from '@/app/api/workflows/[id]/source/route' + +const WORKFLOW_ID = 'workflow-123' +const FINGERPRINT = `sf1:${'c'.repeat(64)}` + +const source = { + workflowId: WORKFLOW_ID, + workspaceId: 'workspace-456', + files: { 'workflow.ts': "// @sim-sdk 1\nexport default workflow('W', () => {})\n" }, + lock: { + version: 1 as const, + blocks: { start: { id: 'b-1', parent: null, ident: 'start', order: 0 } }, + variables: {}, + }, + base: { + version: 1 as const, + workflowId: WORKFLOW_ID, + workspaceId: 'workspace-456', + fingerprint: FINGERPRINT, + catalogHash: 'h', + }, + canonicalHash: 'd'.repeat(64), + sdkMajor: 1, + blockTypes: ['start_trigger'], + diagnostics: [], +} + +const read = () => + GET(new NextRequest(`http://localhost:3000/api/workflows/${WORKFLOW_ID}/source`), { + params: Promise.resolve({ id: WORKFLOW_ID }), + }) + +describe('GET /api/workflows/[id]/source', () => { + beforeEach(() => { + authMockFns.mockGetSession.mockResolvedValue({ + user: { id: 'user-123' }, + session: { id: 'session-123' }, + }) + }) + + it('answers 429 with Retry-After to a read past the source gets this server runs at once', async () => { + const finish: Array<() => void> = [] + mockRead.mockImplementation(() => new Promise((resolve) => finish.push(() => resolve(source)))) + const running = Array.from({ length: 4 }, () => read()) + await vi.waitFor(() => expect(finish).toHaveLength(4)) + + const refused = await read() + expect(refused.status).toBe(429) + expect(refused.headers.get('Retry-After')).toBe('5') + expect(mockRead).toHaveBeenCalledTimes(4) + + for (const done of finish) done() + expect((await Promise.all(running)).map((response) => response.status)).toEqual([ + 200, 200, 200, 200, + ]) + }) +}) diff --git a/apps/sim/app/api/workflows/[id]/source/route.ts b/apps/sim/app/api/workflows/[id]/source/route.ts index fe59cbce4fc..27759d3301f 100644 --- a/apps/sim/app/api/workflows/[id]/source/route.ts +++ b/apps/sim/app/api/workflows/[id]/source/route.ts @@ -6,7 +6,11 @@ import { internalSessionAuth, } from '@/lib/api/server/routes' import type { TokenBucketConfig } from '@/lib/core/rate-limiter' -import { internalWorkflowErrorPolicies, withBoundSourceFindings } from '@/lib/workflows/api' +import { + internalWorkflowErrorPolicies, + withBoundSourceFindings, + withSourceSlot, +} from '@/lib/workflows/api' import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' export const dynamic = 'force-dynamic' @@ -32,6 +36,13 @@ const SOURCE_READ_RATE_LIMIT: TokenBucketConfig = { * The bare fingerprint would not do: it ignores what it does not hash (canvas positions, * comments), which the printed files and lock can still carry. * + * The tag is taken after the read, so a `304` still loads, canonicalizes and prints the draft: the + * printed resource keys are known only once the stored graph is canonicalized (a reference the + * graph gained loads its key then), and a workspace apply that rebinds or releases a key changes + * the print without touching this workflow's rows, so no tag taken before that would be sound. Like the v2 + * read, it runs in a source read slot, and a server already running as many answers `429` with + * `Retry-After`. + * * `headSafe: false` because the first read that references a resource with no key allocates one * (`workspace_resource_key`), so a `HEAD` probe must not run it. */ @@ -44,12 +55,12 @@ export const GET = defineInternalJsonRoute({ bucketName: 'workflow-source-read', config: SOURCE_READ_RATE_LIMIT, }), - errorPolicy: internalWorkflowErrorPolicies.concealWorkflowAuthorization, + errorPolicy: internalWorkflowErrorPolicies.concealWorkflowSourceRead, mapInput: ({ params, query }) => ({ workflowId: params.id, ...(query.functionCode ? { functionCode: query.functionCode } : {}), }), - useCase: readWorkflowSource, + useCase: withSourceSlot(readWorkflowSource, 'read'), entityTag: (source) => `${source.base.fingerprint}.${sha256Hex(JSON.stringify(source))}`, present: (source) => ({ data: withBoundSourceFindings(source) }), }) diff --git a/apps/sim/lib/workflows/api/route-policies.ts b/apps/sim/lib/workflows/api/route-policies.ts index a0e08a4fc60..1fd0ca4f39c 100644 --- a/apps/sim/lib/workflows/api/route-policies.ts +++ b/apps/sim/lib/workflows/api/route-policies.ts @@ -10,6 +10,7 @@ import { createInternalResourceConcealmentPolicy, createInternalSessionOrExecutorAuth, createV2ResourceConcealmentPolicy, + extendInternalErrorPolicy, type InternalAuthPolicy, type InternalErrorPolicy, InternalUnauthenticatedError, @@ -24,7 +25,10 @@ import { apiKeyPrincipal } from '@/lib/api-key/principal' import { authenticateApiKeyFromHeader, updateApiKeyLastUsed } from '@/lib/api-key/service' import { asOrchestrationError, statusForOrchestrationError } from '@/lib/core/orchestration/types' import { WorkflowRunAlreadyTerminalError } from '@/lib/execution/workflow-run-already-terminal-error' -import { renderSourceSlotBusy } from '@/lib/workflows/api/source-slots' +import { + projectInternalSourceSlotBusy, + renderSourceSlotBusy, +} from '@/lib/workflows/api/source-slots' import { WORKFLOW_DELEGATION_AUDIENCE } from '@/lib/workflows/application/authorization' import { WorkflowImportError } from '@/lib/workflows/application/import-error' import { WorkflowOperationsNotAppliedError } from '@/lib/workflows/application/operations-error' @@ -233,11 +237,21 @@ export function createInternalWorkflowErrorPolicy(fallback: string): InternalErr * Internal-surface counterparts of {@link v2WorkflowErrorPolicies} for the * workflow routes that project plain orchestration errors. */ +const concealInternalWorkflowAuthorization = createInternalResourceConcealmentPolicy({ + base: internalOrchestrationErrorPolicy, + notFoundMessage: WORKFLOW_NOT_FOUND_MESSAGE, +}) + export const internalWorkflowErrorPolicies = { - concealWorkflowAuthorization: createInternalResourceConcealmentPolicy({ - base: internalOrchestrationErrorPolicy, - notFoundMessage: WORKFLOW_NOT_FOUND_MESSAGE, - }), + concealWorkflowAuthorization: concealInternalWorkflowAuthorization, + /** + * The Code tab's source read: concealed as `concealWorkflowAuthorization` does, and refused for + * want of a slot with `429` and `Retry-After`. + */ + concealWorkflowSourceRead: extendInternalErrorPolicy( + concealInternalWorkflowAuthorization, + projectInternalSourceSlotBusy + ), concealRunAuthorization: createInternalResourceConcealmentPolicy({ base: internalOrchestrationErrorPolicy, notFoundMessage: 'Execution not found', diff --git a/apps/sim/lib/workflows/api/source-slots.ts b/apps/sim/lib/workflows/api/source-slots.ts index f7b8e562fe7..f1a360555db 100644 --- a/apps/sim/lib/workflows/api/source-slots.ts +++ b/apps/sim/lib/workflows/api/source-slots.ts @@ -1,4 +1,6 @@ import type { NextResponse } from 'next/server' +import { internalErrorResponse } from '@/lib/api/server/routes' +import type { JsonErrorResponseDescriptor } from '@/lib/api/server/routes/types' import type { ApplicationOperation, AuthorizingUseCase } from '@/lib/core/application' import { v2Error } from '@/app/api/v2/lib/response' @@ -69,3 +71,15 @@ export function renderSourceSlotBusy(error: unknown): NextResponse | null { headers: { 'Retry-After': String(SOURCE_BUSY_RETRY_AFTER_SECONDS) }, }) } + +/** {@link renderSourceSlotBusy} for an internal route. */ +export function projectInternalSourceSlotBusy(error: unknown): JsonErrorResponseDescriptor | null { + if (!(error instanceof SourceSlotBusyError)) return null + return internalErrorResponse( + 429, + { error: error.message }, + { + 'Retry-After': String(SOURCE_BUSY_RETRY_AFTER_SECONDS), + } + ) +} From 7ad5049059b69ed5674518cbc12e492f01131d9e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:03:51 -0800 Subject: [PATCH 11/85] improvement(sim-cli): hide autolayout infos from source output unless --verbose --- apps/docs/content/docs/cli/reference.mdx | 10 +++++----- apps/docs/content/docs/cli/workflows.mdx | 6 +++--- apps/docs/content/docs/cli/workspaces.mdx | 4 ++-- .../sim-cli/src/commands/protocol/source-ui.ts | 17 ++++++++++++++--- .../protocol/workflow-source-apply.test.ts | 6 +++++- 5 files changed, 29 insertions(+), 14 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index cd8fb68a6f1..73ea06b8dc0 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8575,7 +8575,7 @@ sim workflows source apply [workflowId] [options] | Option | Required | Description | | --- | --- | --- | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | | `--dir ` | No | Source directory: workflow.ts, functions/*, .sim/lock.json and .sim/base.json. Defaults to `.`. | | `--dry-run` | No | Check the source and show the outcome without saving or writing files. | | `-y, --yes` | No | Apply without asking for confirmation. | @@ -8602,7 +8602,7 @@ sim workflows source create [options] | Option | Required | Description | | --- | --- | --- | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | | `--dir ` | Yes | Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter and the types instead (an error with --dry-run or --yes). | | `--dry-run` | No | Check the source and show the outcome without creating anything. | | `--name ` | No | The workflow name (default: the source's). | @@ -8633,7 +8633,7 @@ sim workflows source check [options] | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | @@ -9978,7 +9978,7 @@ sim workspaces source apply [options] | Option | Required | Description | | --- | --- | --- | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--dry-run` | No | Plan and check without writing anything. | | `-y, --yes` | No | Apply without asking for confirmation. | @@ -10010,7 +10010,7 @@ sim workspaces source check [options] | `--dir ` | No | Workspace source directory: the kind folders and .sim/base.json. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index d3b15455d5a..37b25b76f2b 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1355,7 +1355,7 @@ sim workflows source create [options] | Option | Required | Description | | --- | --- | --- | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | | `--dir ` | Yes | Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter and the types instead (an error with --dry-run or --yes). | | `--dry-run` | No | Check the source and show the outcome without creating anything. | | `--name ` | No | The workflow name (default: the source's). | @@ -1391,7 +1391,7 @@ sim workflows source apply [workflowId] [options] | Option | Required | Description | | --- | --- | --- | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | | `--dir ` | No | Source directory: workflow.ts, functions/*, .sim/lock.json and .sim/base.json. Defaults to `.`. | | `--dry-run` | No | Check the source and show the outcome without saving or writing files. | | `-y, --yes` | No | Apply without asking for confirmation. | @@ -1437,7 +1437,7 @@ sim workflows source check [options] | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 64e39c047d7..adfeedd64d3 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -749,7 +749,7 @@ sim workspaces source apply [options] | Option | Required | Description | | --- | --- | --- | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--dry-run` | No | Plan and check without writing anything. | | `-y, --yes` | No | Apply without asking for confirmation. | @@ -779,7 +779,7 @@ sim workspaces source check [options] | `--dir ` | No | Workspace source directory: the kind folders and .sim/base.json. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | -| `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | +| `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index d0b0005bc1e..ba63ac6a31c 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -203,7 +203,14 @@ export interface FindingsOutput { } /** - * The {@link FindingsOutput} of `format`; `verbose` keeps info findings in a machine result. It is + * Info findings a display format prints only with `--verbose`: they report what the server does + * for the person (a new block placed by autolayout), so there is nothing to act on. + */ +const QUIET_INFO_CODES: ReadonlySet = new Set(['I_MAT_NEEDS_LAYOUT']) + +/** + * The {@link FindingsOutput} of `format`; `verbose` keeps info findings in a machine result, and + * the {@link QUIET_INFO_CODES} in a display one. It is * the CLI's output edge, where each finding's message and hint are cut (`boundFindingText`): a * finding an offline check made is as long as its source made it until here. */ @@ -213,7 +220,11 @@ export function findingsOutput(format: OutputFormat, verbose = false): FindingsO return { machine, print(diagnostics) { - const unseen = diagnostics.filter((diagnostic) => fresh(printed, findingKey(diagnostic))) + const unseen = diagnostics.filter( + (diagnostic) => + (verbose || !QUIET_INFO_CODES.has(diagnostic.code)) && + fresh(printed, findingKey(diagnostic)) + ) if (!machine) printDiagnostics(unseen.map((diagnostic) => boundFindingText(diagnostic))) }, result: (diagnostics) => @@ -250,7 +261,7 @@ export function createdText(created: readonly CreatedResource[]): string { export function verboseFlag(command: Command): Command { return command.option( '--verbose', - 'With --output json, also list info findings (such as blocks placed by autolayout)' + 'Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display' ) } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index 8ddfe50f8f8..d59012067f8 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -611,7 +611,7 @@ describe('sim workflows source apply', () => { expect(JSON.stringify(printed.created)).not.toContain('"id"') }) - it('folds info findings into one line per code and keeps frames on warnings', async () => { + it('hides autolayout infos unless --verbose, folds infos into one line per code and keeps frames on warnings', async () => { setTerminal(false) contextMockState.output = 'text' const layout = (key: string, line: number) => ({ @@ -640,6 +640,10 @@ describe('sim workflows source apply', () => { ) await apply(WORKFLOW_ID, '--dir', dir, '--dry-run') + expect(stderrLines().filter((line) => line.includes('I_MAT_NEEDS_LAYOUT'))).toEqual([]) + vi.mocked(console.error).mockClear() + + await apply(WORKFLOW_ID, '--dir', dir, '--dry-run', '--verbose') const lines = stderrLines() const layoutLines = lines.filter((line) => line.includes('I_MAT_NEEDS_LAYOUT')) From 6acf9ca8db2d3ea3c9b013c98bdec2fa8212b14c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:04:46 -0800 Subject: [PATCH 12/85] fix(workflow-code): an offline check says secrets.ts does not declare an env name instead of claiming the workspace lacks it --- .../src/commands/protocol/workflow-source-check.test.ts | 4 +++- packages/workflow-code/src/compile/SYNTAX.md | 2 +- packages/workflow-code/src/compile/values.ts | 7 +++++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index b50392368e5..9badc5a39cb 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts @@ -435,7 +435,7 @@ describe('sim workflows source check', () => { expect(process.exitCode).toBe(1) }) - it('warns on an env name secrets.ts does not declare', async () => { + it('warns on an env name secrets.ts does not declare, without claiming the workspace lacks it', async () => { cacheCatalog() writeWorkspace() const folder = writeWorkflowFolder( @@ -447,6 +447,8 @@ describe('sim workflows source check', () => { expect(result()).toMatchObject({ errors: 0, warnings: 1 }) expect(findingLines()).toContain('W_ENV_UNKNOWN') + expect(findingLines()).toContain('secrets.ts does not declare ANTHROPIC_KEY') + expect(findingLines()).not.toContain('The workspace has no env variable') }) it('lists at most 20 warnings of one code, as a workflow answer does, and counts every one', async () => { diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index e4e68d66e3e..bd7d10e9b38 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -400,7 +400,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `E_DUPLICATE_VARIABLE` | Two variables with one key. | | `E_VARIABLE_NAME_MISMATCH` | A variable's `name` does not normalize to its key. | | `E_INVALID_ENV_NAME` | `env.X` with an invalid name. | -| `W_ENV_UNKNOWN` | `env.X`, or a code file `$env`, naming a variable the workspace does not hold (checked only when the env names are known); the hint has a did-you-mean, and in a workspace directory points at `secrets.ts`. | +| `W_ENV_UNKNOWN` | `env.X`, or a code file `$env`, naming a variable the workspace does not hold (checked only when the env names are known); the hint has a did-you-mean. An offline check in a workspace directory knows only the names `secrets.ts` declares, so there the finding says `secrets.ts` does not declare it, and the hint points there. | | `W_CHILD_INPUT_UNKNOWN` | A child workflow call's `inputMapping` sets an input the child's Start trigger does not declare (`sim workspaces source check`, with the child in the same directory); the hint names the nearest input. | | `W_CHILD_NO_START` | A child workflow call names a workflow of the same directory that has no Start trigger (`sim workspaces source check`). | | `E_UNKNOWN_SUBFLOW_PROPERTY` | `p.` that a loop or parallel does not have. | diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index 86c06ecc451..bc31ce3e750 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -728,7 +728,8 @@ function segmentsOf( /** * Records `name` as read, and reports `W_ENV_UNKNOWN` when the caller's runs resolve a known set of - * env names and `name` is not one. + * env names and `name` is not one. Names a file declares (`envDeclaredIn`, an offline check) say + * 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) @@ -736,7 +737,9 @@ function checkEnvName(ctx: CompileContext, name: string, at: Range, blockKey: Bl const near = didYouMean(name, ctx.envNames) ctx.reporter.report( 'W_ENV_UNKNOWN', - `The workspace has no env variable ${name}, so it resolves to nothing at run time.`, + ctx.envDeclaredIn + ? `${ctx.envDeclaredIn} does not declare ${name}. This check is offline, so it cannot tell whether the workspace holds a value for it; the dry run checks.` + : `The workspace has no env variable ${name}, so it resolves to nothing at run time.`, at, { hint: ctx.envDeclaredIn From db3d21af3e529c99cbe09d6e687c29d0f4ed9fa0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:05:29 -0800 Subject: [PATCH 13/85] perf(workflow-code): a source dry run checks the stored draft's deployment only when it leaves the draft as it is The check started beside every plan and was discarded whenever the dry run would change the draft, which then compares what it would write instead. --- .../apply-workflow-source.integration.ts | 16 ++++++++++++++++ .../application/apply-workflow-source.ts | 14 +++++--------- .../application/source-pipeline/outcome.ts | 10 +++++----- 3 files changed, 26 insertions(+), 14 deletions(-) diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts index 4a3abb65403..61724a6a4ac 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -75,6 +75,18 @@ import { claimResourceKey } from '@/lib/workspaces/resource-keys' vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock) vi.mock('@/lib/realtime/notify', () => realtimeNotifyMock) vi.mock('@/lib/posthog/server', () => posthogServerMock) +/** The real check, counted: a dry run that changes the draft must not load its deployment twice. */ +const draftDeploymentChecks = vi.hoisted(() => ({ count: 0 })) +vi.mock('@/lib/workflows/deployment-status', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + checkNeedsRedeployment: (workflowId: string) => { + draftDeploymentChecks.count += 1 + return actual.checkNeedsRedeployment(workflowId) + }, + } +}) const ownerId = generateId() const workspaceId = generateId() @@ -2412,8 +2424,12 @@ export default workflow('Fresh', {}, () => { const source = await getSource(workflowId) const changed = edit(source.files, 'return 1', 'return 2') + draftDeploymentChecks.count = 0 const unchangedDryRun = await apply(source, source.files, { dryRun: true }) + // Only a dry run that leaves the draft as it is checks the stored draft's deployment. + expect(draftDeploymentChecks.count).toBe(1) const changedDryRun = await apply(source, changed, { dryRun: true }) + expect(draftDeploymentChecks.count).toBe(1) const applied = await apply(source, changed) expect(unchangedDryRun.needsRedeployment).toBe(false) diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.ts b/apps/sim/lib/workflows/application/apply-workflow-source.ts index 14ed886e67d..9bfddc8a8a1 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.ts @@ -68,15 +68,11 @@ export interface CreateWorkflowFromSourceInput { /** * Whether the draft as it is differs from its deployment, for a dry run that leaves it so (a no-op - * or a refusal): it writes nothing, so this is known now and runs beside the plan. A new workflow - * has no deployment. A dry run that would change the draft compares what it would write instead. - * The `catch` only keeps it observed when an error throws first or it goes unused. + * or a refusal). A new workflow has no deployment. A dry run that would change the draft compares + * what it would write instead, so this runs only once the plan says it will not. */ -function draftNeedsRedeployment(target: SourceTarget): Promise { - if (target.kind === 'new') return Promise.resolve(false) - const check = checkNeedsRedeployment(target.context.workflowId) - check.catch(() => {}) - return check +async function draftNeedsRedeployment(target: SourceTarget): Promise { + return target.kind === 'new' ? false : checkNeedsRedeployment(target.context.workflowId) } /** @@ -95,7 +91,7 @@ async function writeSource( if (planned.kind === 'refused') throw refusalError(planned) return commitSource(principal, planned, target) } - const needsRedeployment = draftNeedsRedeployment(target) + const needsRedeployment = () => draftNeedsRedeployment(target) const planned = await planSource(principal, target, submission, { allocate: false }) return planned.kind === 'refused' ? refusedOutcome(planned, target, submission, needsRedeployment) diff --git a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts index c0e3a7879ec..3a757b99dd2 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts @@ -129,12 +129,12 @@ export function printWritten( /** * The dry run of a plan: what a commit would store, re-printed, and whether the draft would then * differ from its deployment. A graph no-op reports the source meta a commit would store, and - * `draftNeedsRedeployment`, the deployment check of the draft as it is, started beside the plan. + * `draftNeedsRedeployment`, the deployment check of the draft as it is, run only for a no-op. */ export async function previewSource( principal: Principal, planned: PlannedSource, - draftNeedsRedeployment: Promise + draftNeedsRedeployment: () => Promise ): Promise { const { plan, loaded, target } = planned const frame = { @@ -151,7 +151,7 @@ export async function previewSource( workflowName: plan.meta.name, diff: plan.diff, diagnostics: plan.diagnostics, - needsRedeployment: await draftNeedsRedeployment, + needsRedeployment: await draftNeedsRedeployment(), }) } const preview = await previewSourceCommit(planned.workflowId, plan) @@ -187,7 +187,7 @@ export async function refusedOutcome( refused: RefusedSource, target: CommitTarget, submission: { files: Record; lock: WorkflowLockV1 }, - draftNeedsRedeployment: Promise + draftNeedsRedeployment: () => Promise ): Promise { return shapeOutcome( { @@ -201,7 +201,7 @@ export async function refusedOutcome( applied: false, diff: emptyDiffSummary(), diagnostics: refused.diagnostics, - needsRedeployment: await draftNeedsRedeployment, + needsRedeployment: await draftNeedsRedeployment(), } ) } From ac27b73e7874c05bcb61a76718278d18ed70c5e7 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:05:36 -0800 Subject: [PATCH 14/85] improvement(workflow-code): an unknown builder written short suggests the builders its method starts --- .../workflow-code/src/compile/checks.test.ts | 2 ++ packages/workflow-code/src/compile/hints.ts | 18 ++++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 8529f4e3e72..4b25f1daa01 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -450,6 +450,8 @@ describe('unknown builders', () => { "const s = slack.fetchEverything('S', {})", 'slack has: slack.sendMessage, slack.listChannels.', ], + ["const s = slack.send('S', {})", 'Did you mean slack.sendMessage?'], + ["const s = slack.list('S', {})", 'Did you mean slack.listChannels?'], ["const h = http.request('H', {})", 'Did you mean api?'], ["const f = javascript.run('F', {})", 'Did you mean fn?'], ])('%s', (body, hint) => { diff --git a/packages/workflow-code/src/compile/hints.ts b/packages/workflow-code/src/compile/hints.ts index f853911e3ca..41195095df6 100644 --- a/packages/workflow-code/src/compile/hints.ts +++ b/packages/workflow-code/src/compile/hints.ts @@ -229,7 +229,8 @@ const LISTED_BUILDERS = 15 /** * The hint for a builder path no catalog builder has, from most to least specific: the builder a * common other name stands for (`http.request` → `api`), a builder of the same namespace whose method differs only by a synonymous verb (`postMessage` → `sendMessage`), - * the closest path by edit distance, the namespace's builders listed, else the closest namespace. + * the closest path by edit distance, the one builder of the namespace whose method starts with the + * written one, the namespace's builders listed (those it starts first), else the closest namespace. */ export function suggestBuilder(written: string, paths: readonly string[]): string | undefined { const alias = BUILDER_ALIASES[(written.split('.')[0] ?? written).toLowerCase()] @@ -254,7 +255,20 @@ export function suggestBuilder(written: string, paths: readonly string[]): strin const near = didYouMean(written, paths) if (near) return near if (siblings.length > 0) { - const shown = siblings.slice(0, LISTED_BUILDERS).join(', ') + // A method written short (`slack.send`) names the builders it starts: one is the answer, and + // several lead the list, which would otherwise start at whatever sorts first. + const start = method.toLowerCase() + const started = start + ? siblings.filter((path) => + path + .slice(namespace.length + 1) + .toLowerCase() + .startsWith(start) + ) + : [] + if (started.length === 1) return `Did you mean ${started[0]}?` + const ranked = [...started, ...siblings.filter((path) => !started.includes(path))] + const shown = ranked.slice(0, LISTED_BUILDERS).join(', ') const more = siblings.length > LISTED_BUILDERS ? `, and ${siblings.length - LISTED_BUILDERS} more` : '' return `${namespace} has: ${shown}${more}.` From 60f2beb0d7745471f6b6415b7cbfba12a5ecd365 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:07:28 -0800 Subject: [PATCH 15/85] feat(catalog): a legacy block hidden from the toolbar reads by its id, naming its replacement first (blocks get starter) --- apps/docs/content/docs/cli/blocks.mdx | 2 +- apps/docs/content/docs/cli/reference.mdx | 2 +- apps/docs/openapi-v2-resources.json | 4 +- apps/sim/lib/api/contracts/v2/catalog.ts | 2 +- apps/sim/lib/catalog/application/get-block.ts | 20 ++++++--- .../sim/lib/catalog/application/reads.test.ts | 43 +++++++++++++++++++ packages/sim-cli/src/generated/v2-api.ts | 2 +- 7 files changed, 64 insertions(+), 11 deletions(-) diff --git a/apps/docs/content/docs/cli/blocks.mdx b/apps/docs/content/docs/cli/blocks.mdx index 776cd4c7134..fb1ffa07f71 100644 --- a/apps/docs/content/docs/cli/blocks.mdx +++ b/apps/docs/content/docs/cli/blocks.mdx @@ -49,7 +49,7 @@ sim blocks get | Argument | Required | Description | | --- | --- | --- | -| `blockId` | Yes | Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID. | +| `blockId` | Yes | Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID. A legacy or deprecated block (such as `starter`) is readable by its exact ID, and its description opens with the block that replaces it. | diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 73ea06b8dc0..67e4f661b7e 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -422,7 +422,7 @@ sim blocks get | Argument | Required | Description | | --- | --- | --- | -| `blockId` | Yes | Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID. | +| `blockId` | Yes | Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID. A legacy or deprecated block (such as `starter`) is readable by its exact ID, and its description opens with the block that replaces it. | diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index 06b645fde37..98b16c49b78 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -6360,12 +6360,12 @@ "name": "blockId", "in": "path", "required": true, - "description": "Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID.", + "description": "Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID. A legacy or deprecated block (such as `starter`) is readable by its exact ID, and its description opens with the block that replaces it.", "schema": { "type": "string", "minLength": 1, "maxLength": 255, - "description": "Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID." + "description": "Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID. A legacy or deprecated block (such as `starter`) is readable by its exact ID, and its description opens with the block that replaces it." } }, { diff --git a/apps/sim/lib/api/contracts/v2/catalog.ts b/apps/sim/lib/api/contracts/v2/catalog.ts index 67942cb26d6..9d35456d248 100644 --- a/apps/sim/lib/api/contracts/v2/catalog.ts +++ b/apps/sim/lib/api/contracts/v2/catalog.ts @@ -886,7 +886,7 @@ export type V2ListToolsQuery = z.output export const v2GetBlockParamsSchema = z.object({ blockId: catalogIdSchema.describe( - 'Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID.' + 'Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID. A legacy or deprecated block (such as `starter`) is readable by its exact ID, and its description opens with the block that replaces it.' ), }) export type V2GetBlockParams = z.output diff --git a/apps/sim/lib/catalog/application/get-block.ts b/apps/sim/lib/catalog/application/get-block.ts index 1d186ac3231..9d34c774f78 100644 --- a/apps/sim/lib/catalog/application/get-block.ts +++ b/apps/sim/lib/catalog/application/get-block.ts @@ -11,7 +11,8 @@ import { getContainerBlockDetail } from '@/lib/catalog/projection/container-bloc import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' import { isHosted } from '@/lib/core/config/env-flags' import { OrchestrationError } from '@/lib/core/orchestration/types' -import { getLatestBlockForViewer } from '@/blocks/registry' +import { getBlock, getLatestBlockForViewer } from '@/blocks/registry' +import type { BlockConfig } from '@/blocks/types' export interface GetCatalogBlockInput { workspaceId: string @@ -34,7 +35,10 @@ export interface GetCatalogBlockResult { * block hidden from the toolbar, an unrevealed preview block, a kill-switched * one, a type this deployment does not ship, and one the workspace's permission * groups exclude all answer identically. Anything softer would let a caller - * enumerate unrevealed blocks one id at a time. + * enumerate unrevealed blocks one id at a time. The one exception is a sunset + * (legacy or deprecated) block hidden only for its lifecycle: placed instances + * keep running, so it reads by its exact id (`starter`), its description leading + * with the block that replaces it (`start_trigger`). */ export const getCatalogBlock = defineAuthorizedWorkspaceUseCase({ operation: catalogOperations.readBlock, @@ -49,9 +53,15 @@ export const getCatalogBlock = defineAuthorizedWorkspaceUseCase({ // the catalog answers for the same vocabulary add_block accepts. const container = getContainerBlockDetail(input.blockId) if (container) return container - const block = getLatestBlockForViewer(input.blockId) - if (!block || !isBlockVisibleToCaller(block, gate)) return null - return projectBlockDetail(block, { deployment: { hostedKeys: isHosted } }) + const project = (block: BlockConfig) => + projectBlockDetail(block, { deployment: { hostedKeys: isHosted } }) + const latest = getLatestBlockForViewer(input.blockId) + if (latest) return isBlockVisibleToCaller(latest, gate) ? project(latest) : null + const sunset = getBlock(input.blockId) + if (!sunset?.sunset || !isBlockVisibleToCaller(sunset, gate, { includeSunset: true })) { + return null + } + return project(sunset) }) if (!detail) throw new OrchestrationError('not_found', 'Block not found') diff --git a/apps/sim/lib/catalog/application/reads.test.ts b/apps/sim/lib/catalog/application/reads.test.ts index 4b1cbdf39a1..66b5a3b7903 100644 --- a/apps/sim/lib/catalog/application/reads.test.ts +++ b/apps/sim/lib/catalog/application/reads.test.ts @@ -351,6 +351,49 @@ describe('catalog block and tool reads', () => { expect(included.entries.map((entry) => entry.id)).toEqual(['loop', 'parallel', 'slack']) }) + it('reads a sunset block hidden from the toolbar by its id, naming its replacement first', async () => { + const starter = block({ + type: 'starter', + description: 'Start the workflow.', + hideFromToolbar: true, + sunset: { status: 'legacy', replacedBy: 'start_trigger' }, + }) + mocks.getAllBlocks.mockReturnValue([slackBlock, starter]) + mocks.getBlock.mockImplementation((type: string) => + [slackBlock, starter, confluenceV1].find((entry) => entry.type === type) + ) + + const { block: detail } = await getCatalogBlock.execute({ + principal: session, + input: { workspaceId: WORKSPACE_ID, blockId: 'starter' }, + }) + expect(detail.id).toBe('starter') + expect(detail.description).toBe('Legacy — replaced by start_trigger. Start the workflow.') + + // A superseded version hidden from the toolbar with no sunset stays as unknown as before. + await expect( + getCatalogBlock.execute({ + principal: session, + input: { workspaceId: WORKSPACE_ID, blockId: 'confluence' }, + }) + ).resolves.toMatchObject({ block: { id: 'confluence_v2' } }) + mocks.getLatestBlockForViewer.mockReturnValue(undefined) + await expect( + getCatalogBlock.execute({ + principal: session, + input: { workspaceId: WORKSPACE_ID, blockId: 'confluence' }, + }) + ).rejects.toMatchObject({ code: 'not_found', message: 'Block not found' }) + + setVisibility({ ...NOTHING_GATED, disabled: new Set(['starter']) }) + await expect( + getCatalogBlock.execute({ + principal: session, + input: { workspaceId: WORKSPACE_ID, blockId: 'starter' }, + }) + ).rejects.toMatchObject({ code: 'not_found', message: 'Block not found' }) + }) + it('drops a kill-switched block from the list and 404s its detail', async () => { setVisibility({ revealed: new Set(), diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 47f56e72e70..55c4fe4438e 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -23453,7 +23453,7 @@ export const V2_OPERATIONS = { pathParams: ['blockId'] as const, pathParamDocs: { blockId: - 'Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID.', + 'Block type identifier. An unversioned base type resolves to the newest visible version. The response echoes the resolved ID. A legacy or deprecated block (such as `starter`) is readable by its exact ID, and its description opens with the block that replaces it.', }, responseMode: 'json', summary: 'Get block', From ade7bdd595246559d07557e319a624ed395c8340 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:07:58 -0800 Subject: [PATCH 16/85] fix(workspace-source): a file delete is guarded by the revision its plan saw, under the row lock The apply compared the revision and then deleted with no precondition, so a Files tab edit landing in between was deleted with the file. The delete use case now takes expectedRevision, as content updates do, and refuses with a conflict when the content moved. --- .../contexts/workspace/file-manager.ts | 41 ++++++++++++++----- .../application/delete-workspace-file.ts | 24 ++++++++++- .../application/files.integration.ts | 33 +++++++++++++++ .../application/kinds/files/adapter.ts | 18 +++++--- 4 files changed, 98 insertions(+), 18 deletions(-) diff --git a/apps/sim/lib/uploads/contexts/workspace/file-manager.ts b/apps/sim/lib/uploads/contexts/workspace/file-manager.ts index 9c5d33e32f0..13ccdb132d7 100644 --- a/apps/sim/lib/uploads/contexts/workspace/file-manager.ts +++ b/apps/sim/lib/uploads/contexts/workspace/file-manager.ts @@ -3378,9 +3378,15 @@ export async function renameFileInTx( } /** - * Soft delete a workspace file. + * Soft delete a workspace file. With `expectedContentUpdatedAt`, refuses with + * {@link ContentVersionConflictError} when its content was written since, checked under the row lock + * the delete takes, so an edit that lands after the caller's read is never deleted with it. */ -export async function deleteWorkspaceFile(workspaceId: string, fileId: string): Promise { +export async function deleteWorkspaceFile( + workspaceId: string, + fileId: string, + options: { expectedContentUpdatedAt?: Date } = {} +): Promise { logger.info(`Deleting workspace file: ${fileId}`) try { @@ -3390,26 +3396,39 @@ export async function deleteWorkspaceFile(workspaceId: string, fileId: string): } if (fileRecord.deletedAt) return + const live = and( + eq(workspaceFiles.id, fileId), + eq(workspaceFiles.workspaceId, workspaceId), + eq(workspaceFiles.context, 'workspace'), + isNull(workspaceFiles.deletedAt) + ) const [archived] = await db.transaction(async (tx) => { await lockWorkspaceProject(tx, workspaceId) + const expected = options.expectedContentUpdatedAt + if (expected) { + const [current] = await tx + .select({ contentUpdatedAt: workspaceFiles.contentUpdatedAt }) + .from(workspaceFiles) + .where(live) + .for('update') + .limit(1) + if (current && current.contentUpdatedAt.getTime() !== expected.getTime()) { + throw new ContentVersionConflictError(fileId) + } + } return tx .update(workspaceFiles) .set({ deletedAt: new Date(), updatedAt: new Date() }) - .where( - and( - eq(workspaceFiles.id, fileId), - eq(workspaceFiles.workspaceId, workspaceId), - eq(workspaceFiles.context, 'workspace'), - isNull(workspaceFiles.deletedAt) - ) - ) + .where(live) .returning() }) if (!archived) return logger.info(`Successfully archived workspace file: ${archived.originalName}`) } catch (error) { - logger.error(`Failed to delete workspace file ${fileId}:`, error) + if (!(error instanceof ContentVersionConflictError)) { + logger.error(`Failed to delete workspace file ${fileId}:`, error) + } throw error } } diff --git a/apps/sim/lib/workspace-files/application/delete-workspace-file.ts b/apps/sim/lib/workspace-files/application/delete-workspace-file.ts index 561c9f00401..5d052e3be8b 100644 --- a/apps/sim/lib/workspace-files/application/delete-workspace-file.ts +++ b/apps/sim/lib/workspace-files/application/delete-workspace-file.ts @@ -1,9 +1,11 @@ import { AuditAction, AuditResourceType } from '@sim/audit' import { createLogger } from '@sim/logger' import type { AuthorizedWorkspaceUseCaseContext } from '@/lib/core/application' +import { OrchestrationError } from '@/lib/core/orchestration/types' import { notifyWorkspaceFilesChanged } from '@/lib/realtime/notify' import { type ActiveWorkspaceFileContext, + ContentVersionConflictError, deleteWorkspaceFile, } from '@/lib/uploads/contexts/workspace/file-manager' import { defineAuthorizedWorkspaceFileUseCase } from '@/lib/workspace-files/application/authorized-workspace-file-use-case' @@ -11,11 +13,18 @@ import { resolveActiveWorkspaceFileContext, type WorkspaceFileTargetInput, } from '@/lib/workspace-files/application/file-context' +import { parseWorkspaceFileRevision } from '@/lib/workspace-files/application/file-revision' import { fileOperations } from '@/lib/workspace-files/application/operations' const logger = createLogger('DeleteWorkspaceFile') -export type DeleteWorkspaceFileInput = WorkspaceFileTargetInput +export interface DeleteWorkspaceFileInput extends WorkspaceFileTargetInput { + /** + * Refuse the delete (`conflict`) unless the file still holds exactly this content, as reported + * by the `revision` an earlier read or write returned. + */ + expectedRevision?: string +} export interface DeleteWorkspaceFileResult { id: string @@ -24,13 +33,24 @@ export interface DeleteWorkspaceFileResult { } async function executeDeleteWorkspaceFile({ + input, context, }: AuthorizedWorkspaceUseCaseContext< typeof fileOperations.delete, DeleteWorkspaceFileInput, ActiveWorkspaceFileContext >): Promise { - await deleteWorkspaceFile(context.workspaceId, context.fileId) + const expectedContentUpdatedAt = input.expectedRevision + ? parseWorkspaceFileRevision(input.expectedRevision, context.fileId) + : undefined + try { + await deleteWorkspaceFile(context.workspaceId, context.fileId, { expectedContentUpdatedAt }) + } catch (error) { + if (error instanceof ContentVersionConflictError) { + throw new OrchestrationError('conflict', error.message) + } + throw error + } return { id: context.fileId, workspaceId: context.workspaceId, deleted: true } } diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index 2568dbcb76f..90f98d7d107 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -50,6 +50,7 @@ import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope. import { ensureWorkspaceFileFolderPath } from '@/lib/uploads/contexts/workspace/file-folder-manager' import { uploadWorkspaceFile } from '@/lib/uploads/contexts/workspace/file-manager' import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils' +import * as deleteUseCases from '@/lib/workspace-files/application/delete-workspace-file' import { moveWorkspaceFileItemsOperation } from '@/lib/workspace-files/application/move-workspace-file-items' import { readWorkspaceFileContent } from '@/lib/workspace-files/application/read-workspace-file-content' import { renameWorkspaceFile } from '@/lib/workspace-files/application/rename-workspace-file' @@ -632,6 +633,38 @@ describe('workspace source files', () => { } ) + check( + 'a UI edit between the plan and a delete fails that delete and keeps the file with the UI bytes', + async () => { + const workspaceId = await newWorkspace() + const read = await setUp(workspaceId) + const id = fileId(read.base, 'docs/plan.md') + const remove = deleteUseCases.deleteWorkspaceFileOperation.execute + const spy = vi + .spyOn(deleteUseCases.deleteWorkspaceFileOperation, 'execute') + .mockImplementationOnce(async (args) => { + await editInUi(workspaceId, id, '# Plan, racing UI edit\n') + return remove(args) + }) + try { + const result = await apply( + workspaceId, + { 'files/notes.txt': STARTER['files/notes.txt'] }, + { base: read.base, allowDelete: true } + ) + expect(result.failed).toMatchObject({ key: 'docs/plan.md', code: 'E_APPLY_STALE' }) + } finally { + spy.mockRestore() + } + const [row] = await db + .select({ deletedAt: workspaceFiles.deletedAt }) + .from(workspaceFiles) + .where(eq(workspaceFiles.id, id)) + expect(row?.deletedAt).toBeNull() + expect(await bytesOf(workspaceId, id)).toBe('# Plan, racing UI edit\n') + } + ) + check('a dropped file edited in the UI since the get is not deleted', async () => { const workspaceId = await newWorkspace() const read = await setUp(workspaceId) diff --git a/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts index 11a59e7deb9..dc92c5ea6d0 100644 --- a/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts @@ -3,7 +3,8 @@ * and name, synced by SHA-256 through staged blobs. Creates go through * `createWorkspaceFileBufferByPath` (which creates missing folders), content changes through * `updateWorkspaceFileContentFromBuffer` guarded by the revision the plan saw (each one records a - * new version), deletes through `deleteWorkspaceFileOperation` (Recently Deleted keeps the file). + * new version), deletes through `deleteWorkspaceFileOperation` guarded the same way (Recently + * Deleted keeps the file). * Only `context = 'workspace'` files are read; a file over the blob cap, or one whose path no * directory can hold, is left out of a get and never touched by an apply (a declaration of one is * refused, unless it is unchanged since a get that read the file). A path is the key, so a @@ -580,10 +581,17 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { if ((await stateOf(ctx, fileId)).rev !== rev) { throw new ResourceChangedError(change) } - await deleteWorkspaceFileOperation.execute({ - principal, - input: { fileId, assertedWorkspaceId: workspaceId }, - }) + try { + await deleteWorkspaceFileOperation.execute({ + principal, + input: { fileId, assertedWorkspaceId: workspaceId, expectedRevision: rev }, + }) + } catch (error) { + if (error instanceof OrchestrationError && error.code === 'conflict') { + throw new ResourceChangedError(change) + } + throw error + } return { id: fileId, text: {} } } const { content, sha256 } = await contentOf(change, ctx) From 53ed6fcc5dd398618dccf35d838685984db43581 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:09:38 -0800 Subject: [PATCH 17/85] improvement(sim-cli): operations apply help documents edges, handles, edge removal and rename rewrites, and its example wires source --- apps/docs/content/docs/cli/reference.mdx | 4 +++- apps/docs/content/docs/cli/workflows.mdx | 4 +++- packages/sim-cli/src/contract/commands.ts | 23 ++++++++++++++++++++++- packages/sim-cli/src/contract/types.ts | 2 ++ packages/sim-cli/src/runtime/build.ts | 1 + 5 files changed, 31 insertions(+), 3 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 67e4f661b7e..5898f545ee7 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -7746,7 +7746,7 @@ sim workflows operations apply [options] | --- | --- | --- | | `--dry-run` | No | Validate and lint without writing, auditing, or notifying collaborators. Returns the same validation, preparation warnings, lint findings, and ID-ownership conflicts (`409`) as a committed write. `needsRedeployment` describes the pre-write state. For semantic operations, `mintedBlockIds` is empty; `previewBlockIds` contains provisional IDs with a warning, since committing mints new IDs. | | `--no-dry-run` | No | Send --dry-run as false. | -| `--operations ` | Yes | Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"<uuid>","params":{"name":"Renamed","connections":{"success":"my-fn"}}},{"operation_type":"delete","block_id":"<uuid>"}]. Also extract_from_subflow, whose params carry {"subflowId":"<loop-id>"}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId. To move an existing block into a loop or parallel (keeping its id), edit it with params {"parentId":"<loop-id>"}; {"parentId":null} moves it out (JSON, or @path / @- to read a file or stdin). | +| `--operations ` | Yes | Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"<uuid>","params":{"name":"Renamed","connections":{"source":"my-fn"}}},{"operation_type":"delete","block_id":"<uuid>"}]. Also extract_from_subflow, whose params carry {"subflowId":"<loop-id>"}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId. To move an existing block into a loop or parallel (keeping its id), edit it with params {"parentId":"<loop-id>"}; {"parentId":null} moves it out (JSON, or @path / @- to read a file or stdin). | | `--atomic` | No | Fail the whole batch when any operation is declined or any block input would be dropped. The default applies what it can and reports the rest in `skipped` and `inputValidationErrors`; `true` writes nothing and answers `409` instead. | | `--no-atomic` | No | Send --atomic as false. | | `--layout ` | No | Whether to reposition blocks the batch touched. `targeted` (default) nudges only the affected subgraph; `none` leaves every position exactly as supplied. Accepted values: `targeted`, `none`. | @@ -7755,6 +7755,8 @@ sim workflows operations apply [options] +Edges: connections maps a source handle to its targets: {"source":"<id>"}, {"source":["<a>","<b>"]}, or {"source":{"block":"<id>","handle":"<target handle>"}}; "success" is an alias of "source". An add's connections create the new block's edges. An edit's connections REPLACE every outgoing edge of that block, on every handle: list again each edge to keep. To remove one edge, edit its source block with {"removeEdges":[{"targetBlockId":"<id>","sourceHandle":"source"}]} (sourceHandle defaults to "source"). Source handles: source the normal path error a failure (a block that has an error output) if, else-if-0, else a condition's branches, in order (else-if-1, … for more) route-0, route-1, … a router's routes, in order loop-start-source a loop into its body; loop-end-source after the loop parallel-start-source, parallel-end-source the same for a parallel Renames: An edit's {"name":"New name"} also rewrites every <old key.field> reference to the block, in other blocks' inputs and in a loop's or parallel's collection and condition. + API request and response schemas: [applyWorkflowOperations](/api-reference/workflows/applyWorkflowOperations). ### sim workflows variables update diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 37b25b76f2b..3f62b7861ef 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -326,7 +326,7 @@ sim workflows operations apply [options] | --- | --- | --- | | `--dry-run` | No | Validate and lint without writing, auditing, or notifying collaborators. Returns the same validation, preparation warnings, lint findings, and ID-ownership conflicts (`409`) as a committed write. `needsRedeployment` describes the pre-write state. For semantic operations, `mintedBlockIds` is empty; `previewBlockIds` contains provisional IDs with a warning, since committing mints new IDs. | | `--no-dry-run` | No | Send --dry-run as false. | -| `--operations ` | Yes | Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"<uuid>","params":{"name":"Renamed","connections":{"success":"my-fn"}}},{"operation_type":"delete","block_id":"<uuid>"}]. Also extract_from_subflow, whose params carry {"subflowId":"<loop-id>"}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId. To move an existing block into a loop or parallel (keeping its id), edit it with params {"parentId":"<loop-id>"}; {"parentId":null} moves it out (JSON, or @path / @- to read a file or stdin). | +| `--operations ` | Yes | Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"<uuid>","params":{"name":"Renamed","connections":{"source":"my-fn"}}},{"operation_type":"delete","block_id":"<uuid>"}]. Also extract_from_subflow, whose params carry {"subflowId":"<loop-id>"}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId. To move an existing block into a loop or parallel (keeping its id), edit it with params {"parentId":"<loop-id>"}; {"parentId":null} moves it out (JSON, or @path / @- to read a file or stdin). | | `--atomic` | No | Fail the whole batch when any operation is declined or any block input would be dropped. The default applies what it can and reports the rest in `skipped` and `inputValidationErrors`; `true` writes nothing and answers `409` instead. | | `--no-atomic` | No | Send --atomic as false. | | `--layout ` | No | Whether to reposition blocks the batch touched. `targeted` (default) nudges only the affected subgraph; `none` leaves every position exactly as supplied. Accepted values: `targeted`, `none`. | @@ -335,6 +335,8 @@ sim workflows operations apply [options] +Edges: connections maps a source handle to its targets: {"source":"<id>"}, {"source":["<a>","<b>"]}, or {"source":{"block":"<id>","handle":"<target handle>"}}; "success" is an alias of "source". An add's connections create the new block's edges. An edit's connections REPLACE every outgoing edge of that block, on every handle: list again each edge to keep. To remove one edge, edit its source block with {"removeEdges":[{"targetBlockId":"<id>","sourceHandle":"source"}]} (sourceHandle defaults to "source"). Source handles: source the normal path error a failure (a block that has an error output) if, else-if-0, else a condition's branches, in order (else-if-1, … for more) route-0, route-1, … a router's routes, in order loop-start-source a loop into its body; loop-end-source after the loop parallel-start-source, parallel-end-source the same for a parallel Renames: An edit's {"name":"New name"} also rewrites every <old key.field> reference to the block, in other blocks' inputs and in a loop's or parallel's collection and condition. + API request and response schemas: [applyWorkflowOperations](/api-reference/workflows/applyWorkflowOperations). ### Update workflow variables diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 5ab9ccd4322..ce47bbb4433 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -62,7 +62,27 @@ const FILE_EDIT_HELP = * shape guessable, the same way `TABLE_FILTER_HELP` does for the predicate. */ const WORKFLOW_OPERATIONS_HELP = - 'Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"","params":{"name":"Renamed","connections":{"success":"my-fn"}}},{"operation_type":"delete","block_id":""}]. Also extract_from_subflow, whose params carry {"subflowId":""}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId. To move an existing block into a loop or parallel (keeping its id), edit it with params {"parentId":""}; {"parentId":null} moves it out' + 'Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"","params":{"name":"Renamed","connections":{"source":"my-fn"}}},{"operation_type":"delete","block_id":""}]. Also extract_from_subflow, whose params carry {"subflowId":""}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId. To move an existing block into a loop or parallel (keeping its id), edit it with params {"parentId":""}; {"parentId":null} moves it out' +/** How `--operations` wires and unwires edges, and what a rename rewrites. */ +const WORKFLOW_OPERATIONS_GUIDE = ` +Edges: + connections maps a source handle to its targets: {"source":""}, {"source":["",""]}, + or {"source":{"block":"","handle":""}}; "success" is an alias of "source". + An add's connections create the new block's edges. An edit's connections REPLACE every + outgoing edge of that block, on every handle: list again each edge to keep. + To remove one edge, edit its source block with + {"removeEdges":[{"targetBlockId":"","sourceHandle":"source"}]} (sourceHandle defaults to + "source"). +Source handles: + source the normal path + error a failure (a block that has an error output) + if, else-if-0, else a condition's branches, in order (else-if-1, … for more) + route-0, route-1, … a router's routes, in order + loop-start-source a loop into its body; loop-end-source after the loop + parallel-start-source, parallel-end-source the same for a parallel +Renames: + An edit's {"name":"New name"} also rewrites every reference to the block, in + other blocks' inputs and in a loop's or parallel's collection and condition.` const WORKFLOW_SET_BLOCK_ENABLED_HELP = 'Blocks to enable or disable, applied after --operations: [{"block_id":"","enabled":false}]. Disabling a loop or parallel cascades to its unlocked descendants; enabling a block whose container is disabled is declined' const WORKFLOW_VARIABLE_OPERATIONS_HELP = @@ -680,6 +700,7 @@ export const CLI_CONTRACT: CliContract = { applyWorkflowOperations: { command: 'workflows operations apply', describe: 'Edit a workflow’s blocks, connections and settings with a batch of operations', + helpText: WORKFLOW_OPERATIONS_GUIDE, confirm: 'This edits the draft graph: the batch adds, edits, or deletes blocks and their edges as written.', flags: { diff --git a/packages/sim-cli/src/contract/types.ts b/packages/sim-cli/src/contract/types.ts index d04c8572557..b2c2bcd2a46 100644 --- a/packages/sim-cli/src/contract/types.ts +++ b/packages/sim-cli/src/contract/types.ts @@ -300,6 +300,8 @@ export interface CommandSpec { variants?: readonly CommandVariantSpec[] /** One-line help. Falls back to the OpenAPI summary for the operation. */ describe?: string + /** Prose `--help` prints after the options: how the fields combine, where one flag cannot say. */ + helpText?: string /** Per-field flag overrides, keyed by the contract's field name. */ flags?: Record /** Friendly mutually-exclusive flags for an otherwise opaque union body. */ diff --git a/packages/sim-cli/src/runtime/build.ts b/packages/sim-cli/src/runtime/build.ts index 46ecc97a16e..b6105187043 100644 --- a/packages/sim-cli/src/runtime/build.ts +++ b/packages/sim-cli/src/runtime/build.ts @@ -462,6 +462,7 @@ function configureOperation( spec.describe ?? operationSpec.summary ?? `${operationSpec.method} ${operationSpec.path}` ) ) + if (spec.helpText) command.addHelpText('after', spec.helpText) addOperationOptions(command, operation, spec, operationSpec) assertNoReservedFlags(command, operation) // The last frame that still knows which operation ran, and so the only one From a51494c17d9cb1385312fe059552119e2c95f4c9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:11:30 -0800 Subject: [PATCH 18/85] fix(sim-cli): workspace status counts and lints only what an apply sends, and says a conflict refuses the apply --- .../protocol/workspace-source-status.test.ts | 80 ++++++++++++++++++- .../protocol/workspace-source-status.ts | 78 +++++++++++++----- 2 files changed, 135 insertions(+), 23 deletions(-) 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 c68d63d979a..89761c88d09 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 @@ -128,7 +128,16 @@ describe('workspaces source status', () => { local: [], drift: [], conflicts: [], - plan: { create: 0, update: 0, delete: 0, unchanged: 0, held: 0, errors: 0, warnings: 0 }, + plan: { + create: 0, + update: 0, + delete: 0, + unchanged: 0, + held: 0, + conflicts: 0, + errors: 0, + warnings: 0, + }, next: null, }) expect(process.exitCode ?? 0).toBe(0) @@ -145,6 +154,7 @@ describe('workspaces source status', () => { kind: 'workflow', key: 'ingest', } + write('workflows/ingest/workflow.ts', INGEST.replace("'Ingest'", "'Ingest v2'")) mockRequest.mockResolvedValue(dryRun([], [warning])) await run('status') @@ -543,6 +553,51 @@ describe('workspaces source status', () => { expect(printed().plan).toMatchObject({ update: 0, unchanged: 1 }) }) + it('leaves out lint findings on a workflow an apply sends by its base, as its dry run does', async () => { + mockRequest.mockResolvedValue( + dryRun( + [{ kind: 'workflow', key: 'ingest', action: 'noop' }], + [ + { + code: 'W_APPLY_LINT', + severity: 'warning', + message: 'Start must be connected', + kind: 'workflow', + key: 'ingest', + }, + ] + ) + ) + + await run('status') + + const report = printed() + expect(report.plan).toMatchObject({ errors: 0, warnings: 0 }) + expect(report.diagnostics ?? []).toEqual([]) + }) + + it('keeps lint findings on a workflow edited here, which an apply sends whole', async () => { + write('workflows/ingest/workflow.ts', INGEST.replace("'Ingest'", "'Ingest v2'")) + mockRequest.mockResolvedValue( + dryRun( + [{ kind: 'workflow', key: 'ingest', action: 'update' }], + [ + { + code: 'W_APPLY_LINT', + severity: 'warning', + message: 'Start must be connected', + kind: 'workflow', + key: 'ingest', + }, + ] + ) + ) + + await run('status') + + expect(printed().plan).toMatchObject({ warnings: 1 }) + }) + it('counts an edited workflow as the update its dry run plans', async () => { write('workflows/ingest/workflow.ts', INGEST.replace("'Ingest'", "'Ingest v2'")) mockRequest.mockResolvedValue(dryRun([{ kind: 'workflow', key: 'ingest', action: 'update' }])) @@ -586,9 +641,32 @@ describe('workspaces source status', () => { expect(report.next).toMatchObject({ command: 'sim workspaces source get --dir ', }) + expect(report.plan).toMatchObject({ conflicts: 1, errors: 0 }) expect(process.exitCode).toBe(12) }) + it('says a conflict refuses the apply, never "0 error(s)" alone, for a person', async () => { + write('tables/leads.ts', `${LEADS}// edited\n`) + mockRequest.mockResolvedValue( + dryRun( + [{ kind: 'table', key: 'leads', action: 'noop' }], + [{ code: 'E_APPLY_STALE', severity: 'error', message: 'm', kind: 'table', key: 'leads' }] + ) + ) + mockProfileFrom.mockReturnValue({ + ...mockedProfile(), + workspaceId: WORKSPACE_ID, + output: 'text', + }) + + await run('status') + + const screen = String(vi.mocked(console.log).mock.calls.at(-1)?.[0]) + expect(screen).toContain( + 'Applying would be refused as stale (exit 5): 1 conflict(s) above. Without them it would:' + ) + }) + it('degrades to the local view when the server cannot be reached, and says so', async () => { write('tables/leads.ts', `${LEADS}// edited\n`) mockRequest.mockRejectedValue( 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 99e91ec8614..de6900d548b 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -26,6 +26,7 @@ import { import type { Command } from 'commander' import { profileFrom } from '../../context' import { setSoftExitCode } from '../../embed-context' +import { SOURCE_STALE_EXIT_CODE } from '../../exit-codes' import type { GetWorkspaceSourceResponse, PlanWorkspaceSourceBody, @@ -194,6 +195,8 @@ interface WorkspacePlanSummary { delete: number unchanged: number held: number + /** Resources changed on both sides: while any stands, an apply is refused as stale. */ + conflicts: number /** Errors other than the server changes the status lists. */ errors: number warnings: number @@ -202,15 +205,10 @@ interface WorkspacePlanSummary { type PlannedChange = PlanData['plan'][number] /** - * The dry run's plan as an apply to `target` would make it. The status sends every workflow folder - * whole, so the server plans an update for one changed only on the server, but an apply sends a - * folder without local edits by its base alone, which the server leaves unchanged. + * The workflow folders an apply to `target` sends by their base alone: those without local edits. + * The status sends every folder whole, to compare each with the stored workflow. */ -function planAsApplied( - plan: readonly PlannedChange[], - local: LocalWorkspace, - target: string -): PlannedChange[] { +function workflowsSentByBase(local: LocalWorkspace, target: string): Set { const sent = withUnchangedWorkflowsPruned(local.submission, local.written, target).files const workflowPaths = Object.keys(local.submission.files).filter( (path) => kindOfPath(path) === 'workflow' @@ -219,37 +217,70 @@ function planAsApplied( for (const [key, paths] of KIND_LAYOUTS.workflow.group(workflowPaths).groups) { if (paths.some((path) => !Object.hasOwn(sent, path))) byBase.add(key) } + return byBase +} + +/** Whether `change` or `finding` is about a workflow folder an apply sends by its base alone. */ +function aboutWorkflowSentByBase( + { kind, key }: { kind?: string; key?: string }, + byBase: ReadonlySet +): boolean { + return kind === 'workflow' && key !== undefined && byBase.has(key) +} + +/** + * The dry run's plan as an apply would make it: the server plans an update for a folder changed + * only on the server, but leaves a folder sent by its base unchanged. + */ +function planAsApplied( + plan: readonly PlannedChange[], + byBase: ReadonlySet +): PlannedChange[] { return plan.map((change) => - change.kind === 'workflow' && byBase.has(change.key) && change.action !== 'noop' + aboutWorkflowSentByBase(change, byBase) && change.action !== 'noop' ? { kind: change.kind, key: change.key, action: 'noop' } : change ) } -/** The dry run's findings the plan counts: all but the server changes the status lists. */ -function workspacePlanFindings(data: PlanData): Diagnostic[] { - return planFindings(data.diagnostics, isServerChangeFinding) +/** + * The dry run's findings the plan counts, as an apply's dry run would report them: all but the + * server changes the status lists, and none about a workflow folder an apply sends by its base + * (the server compiles and lints only a folder sent whole). + */ +function workspacePlanFindings(data: PlanData, byBase: ReadonlySet): Diagnostic[] { + return planFindings(data.diagnostics, isServerChangeFinding).filter( + (finding) => !aboutWorkflowSentByBase(finding, byBase) + ) } -function planSummary(data: PlanData, plan: readonly PlannedChange[]): WorkspacePlanSummary { +function planSummary( + findings: readonly Diagnostic[], + plan: readonly PlannedChange[], + conflicts: number +): WorkspacePlanSummary { const count = (...actions: string[]) => plan.filter((change) => actions.includes(change.action)).length - const planned = workspacePlanFindings(data) - const findings = (severity: string) => - planned.filter((finding) => finding.severity === severity).length + const severity = (level: string) => + findings.filter((finding) => finding.severity === level).length return { create: count('create'), update: count('update', 'adopt'), delete: count('delete'), unchanged: count('noop'), held: plan.filter((change) => change.held).length, - errors: findings('error'), - warnings: findings('warning'), + conflicts, + errors: severity('error'), + warnings: severity('warning'), } } +/** The plan line: what applying would write, or that it is refused while a conflict stands. */ function planLine(plan: WorkspacePlanSummary): string { - return `Applying would: ${plan.create} create, ${plan.update} update, ${plan.delete} delete (${plan.unchanged} unchanged); ${plan.errors} error(s), ${plan.warnings} warning(s).` + const counts = `${plan.create} create, ${plan.update} update, ${plan.delete} delete (${plan.unchanged} unchanged); ${plan.errors} error(s), ${plan.warnings} warning(s)` + return plan.conflicts > 0 + ? `Applying would be refused as stale (exit ${SOURCE_STALE_EXIT_CODE}): ${plan.conflicts} conflict(s) above. Without them it would: ${counts}.` + : `Applying would: ${counts}.` } /** @@ -330,6 +361,7 @@ export function attachWorkspaceSourceStatus(source: Command): void { let note: string | undefined = options.offline ? 'Skipped with --offline.' : undefined let data: PlanData | null = null let applyPlan: PlannedChange[] = [] + let byBase: ReadonlySet = new Set() let workspaceId = local.readFrom // The scope every recommended command carries, so it acts on what this status showed. const onlyScope = only ? ` --only ${only.map((kind) => KIND_DIRS[kind]).join(',')}` : '' @@ -373,7 +405,8 @@ export function attachWorkspaceSourceStatus(source: Command): void { }) ) data = response.data - applyPlan = planAsApplied(data.plan, local, target) + byBase = workflowsSentByBase(local, target) + applyPlan = planAsApplied(data.plan, byBase) } catch (error) { const reason = unreachableReason(error) if (reason === null) throw withSourceExitCode(error) @@ -392,7 +425,8 @@ export function attachWorkspaceSourceStatus(source: Command): void { ) : [] ) - const plan = data ? planSummary(data, applyPlan) : null + const planned = data ? workspacePlanFindings(data, byBase) : [] + const plan = data ? planSummary(planned, applyPlan, status.conflicts.length) : null const report: StatusReport & { workspaceId: string | null } = { workspaceId, dir: options.dir, @@ -421,7 +455,7 @@ export function attachWorkspaceSourceStatus(source: Command): void { `Workspace ${workspaceId ?? '(no base)'} in ${options.dir}`, report, planLine, - data ? workspacePlanFindings(data) : [] + planned ) setSoftExitCode(statusExitCode(status.state, login)) }, From b4d64a0b06a693320aa4bf091b355de46c725253 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:12:03 -0800 Subject: [PATCH 19/85] fix(table): a managed rows write counts the keyless rows it keeps against the row limit The reshape checked capacity as if the declared rows replaced every stored row, but a keyed write keeps stored rows with no key value, so a table could end over its plan limit. The keyed write now checks the rows it leaves under the lock, once it has read them. --- apps/sim/lib/table/application/reshape.ts | 4 +- apps/sim/lib/table/rows/keyed-write.ts | 12 ++++- apps/sim/lib/table/rows/writes.integration.ts | 1 + .../application/rows.integration.ts | 49 +++++++++++++++++++ 4 files changed, 64 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/table/application/reshape.ts b/apps/sim/lib/table/application/reshape.ts index 2d19b0ac2e9..272a093303a 100644 --- a/apps/sim/lib/table/application/reshape.ts +++ b/apps/sim/lib/table/application/reshape.ts @@ -272,7 +272,8 @@ export const reshapeTableUseCase = defineAuthorizedTableUseCase({ }) const requestId = generateRequestId() // Checked before the transaction opens (it reads the billing pool), for the rows the table - // holds once they are written. + // holds once they are written; a managed write, which keeps stored rows with no key value, + // checks again under the lock once it has read them. const rowLimit = input.rows ? await assertRowCapacity({ workspaceId, @@ -331,6 +332,7 @@ export const reshapeTableUseCase = defineAuthorizedTableUseCase({ columnIds: rows.columns.flatMap((name) => idByName.get(name) ?? []), rows: stored, allowDelete: rows.allowDelete, + rowLimit: rowLimit ?? -1, }, actor, requestId diff --git a/apps/sim/lib/table/rows/keyed-write.ts b/apps/sim/lib/table/rows/keyed-write.ts index caf5deb4899..039cf68c35a 100644 --- a/apps/sim/lib/table/rows/keyed-write.ts +++ b/apps/sim/lib/table/rows/keyed-write.ts @@ -4,7 +4,8 @@ * row service's transaction-bound writers: stored rows whose key no declared row has are deleted, * rows whose declared cells changed are patched (cells of other columns, a workflow group's * outputs say, are left alone), and new keys are inserted. A stored row with no key value (the - * grid's "add row" makes one) is no declared row's, so it is kept. An unchanged row is not touched, so + * grid's "add row" makes one) is no declared row's, so it is kept, and counts toward the table's row + * limit with the rest. An unchanged row is not touched, so * its id, `updated_at`, run state and provenance stay, and no trigger fires for it. */ @@ -13,6 +14,7 @@ import { userTableRows } from '@sim/db/schema' import { rowKeyText } from '@sim/workspace-code/kinds/table-rows' import { and, eq } from 'drizzle-orm' import { OrchestrationError } from '@/lib/core/orchestration/types' +import { TableRowLimitError, wouldExceedRowLimit } from '@/lib/table/billing' import type { DbTransaction } from '@/lib/table/planner' import { createExactEmptyTableRowSecretProvenance } from '@/lib/table/rows/secret-provenance' import { @@ -34,6 +36,11 @@ export interface KeyedRows { rows: RowData[] /** Whether stored rows no declared row matches are deleted; otherwise they refuse the write. */ allowDelete: boolean + /** + * The plan's row limit for the table (negative: unlimited). The write is refused when the rows + * it leaves, the stored rows with no key value it keeps included, would cross it. + */ + rowLimit: number } /** What a keyed write changed, and the triggers to fire once the transaction commits. */ @@ -131,6 +138,9 @@ export async function writeKeyedRowsWithTx( `${removed.length} stored row(s) of "${table.name}" match no declared row; deleting them needs allow-delete.` ) } + if (wouldExceedRowLimit(declared.rowLimit, stored.length - removed.length, inserts.length)) { + throw new TableRowLimitError(declared.rowLimit) + } const deletion = removed.length > 0 ? await deleteRowsByIdsWithTx(trx, table, removed, requestId) : undefined diff --git a/apps/sim/lib/table/rows/writes.integration.ts b/apps/sim/lib/table/rows/writes.integration.ts index 78f7cd93811..3c79f78d18d 100644 --- a/apps/sim/lib/table/rows/writes.integration.ts +++ b/apps/sim/lib/table/rows/writes.integration.ts @@ -360,6 +360,7 @@ describe('table row writes against real PostgreSQL', () => { columnIds: ['key', 'note'], rows: [{ key: 'kept', note: 'new' }], allowDelete: true, + rowLimit: -1, }, { userId, capabilityGovernedUserId: null }, 'keyed-timeout' diff --git a/apps/sim/lib/workspace-source/application/rows.integration.ts b/apps/sim/lib/workspace-source/application/rows.integration.ts index 00b465709fc..cc71403370d 100644 --- a/apps/sim/lib/workspace-source/application/rows.integration.ts +++ b/apps/sim/lib/workspace-source/application/rows.integration.ts @@ -40,6 +40,20 @@ vi.mock('@/lib/realtime/notify', () => realtimeNotifyMock) vi.mock('@/lib/posthog/server', () => posthogServerMock) // The trigger module is mocked so each check sees exactly which row events an apply fires. vi.mock('@/lib/table/trigger', () => tableTriggerMock) +/** A row limit a check sets for the table plan (billing is off here, so it is otherwise unlimited). */ +const planRowLimit = vi.hoisted(() => ({ value: undefined as number | undefined })) +vi.mock('@/lib/table/constants', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getBillingDisabledTableLimits: () => { + const limits = actual.getBillingDisabledTableLimits() + return planRowLimit.value === undefined + ? limits + : { ...limits, maxRowsPerTable: planRowLimit.value } + }, + } +}) const ownerId = generateId() const readerId = generateId() @@ -1056,6 +1070,41 @@ export default defineTable({ } ) + check( + 'refuses a managed write whose rows, with the rows the UI added without a key that it keeps, would cross the row limit', + async () => { + const workspaceId = await newWorkspace() + const optionalKey = MANAGED.replace( + 'column.string({ required: true, unique: true })', + 'column.string({ unique: true })' + ) + const created = await apply(workspaceId, { + 'tables/plans.ts': optionalKey, + 'tables/plans.rows.jsonl': ROWS, + }) + expect(created.failed).toBeUndefined() + await addUiRow(workspaceId, {}) + await addUiRow(workspaceId, {}) + const read = await runner.get(workspaceId) + const rowsBefore = await storedRows(workspaceId) + planRowLimit.value = 4 + try { + const written = await apply( + workspaceId, + { + ...read.files, + 'tables/plans.rows.jsonl': `${ROWS}{"code":"ent","seats":50,"tier":"pro"}\n`, + }, + { base: read.base } + ) + expect(written.failed?.message).toContain('row limit (4 rows)') + } finally { + planRowLimit.value = undefined + } + expect(await storedRows(workspaceId)).toEqual(rowsBefore) + } + ) + check( 'refuses at plan time a column made required that a row the UI added leaves empty, though the rows file is unchanged', async () => { From f12f65508f2bd46742f761a902eb9bfe8afe3362 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:13:06 -0800 Subject: [PATCH 20/85] fix(sim-cli): read a status finding's resource without assuming the workflow finding shape --- .../src/commands/protocol/workspace-source-status.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) 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 de6900d548b..d96d7323ddb 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -221,11 +221,9 @@ function workflowsSentByBase(local: LocalWorkspace, target: string): Set } /** Whether `change` or `finding` is about a workflow folder an apply sends by its base alone. */ -function aboutWorkflowSentByBase( - { kind, key }: { kind?: string; key?: string }, - byBase: ReadonlySet -): boolean { - return kind === 'workflow' && key !== undefined && byBase.has(key) +function aboutWorkflowSentByBase(item: object, byBase: ReadonlySet): boolean { + const { kind, key } = toRecord(item) + return kind === 'workflow' && typeof key === 'string' && byBase.has(key) } /** From cf137256e9bd7a07e93984ae73662c92fd4a0978 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:13:09 -0800 Subject: [PATCH 21/85] feat(sim-cli): a workspace apply or promotion that wrote part of its plan and held the rest back exits 15, apart from nothing written --- apps/docs/content/docs/cli/reference.mdx | 2 +- apps/docs/content/docs/cli/scripting.mdx | 3 ++- apps/docs/content/docs/cli/workspaces.mdx | 2 +- .../commands/protocol/source-exit-codes.ts | 13 +++++++++- .../protocol/workspace-source-apply.test.ts | 26 +++++++++++++++++-- .../protocol/workspace-source-apply.ts | 5 ++-- .../commands/protocol/workspace-source-dir.ts | 3 ++- packages/sim-cli/src/exit-codes.ts | 9 +++++++ packages/workflow-sdk/README.md | 1 + 9 files changed, 55 insertions(+), 9 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 5898f545ee7..99a701c1bc3 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -9991,7 +9991,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or changes were held back because they use a declared secret the workspace has no value for or a declared credential key nothing binds to (the rest was applied: set the secret or connect the credential, then apply again), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run that would hold changes back exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog). diff --git a/apps/docs/content/docs/cli/scripting.mdx b/apps/docs/content/docs/cli/scripting.mdx index 90617965b3e..b8f0973f026 100644 --- a/apps/docs/content/docs/cli/scripting.mdx +++ b/apps/docs/content/docs/cli/scripting.mdx @@ -207,7 +207,7 @@ The CLI resends a request the API answers `429` only when sending it twice is sa | Code | `sim workspaces source apply` | | --- | --- | | `0` | Applied, or a dry run with no errors | -| `1` | The source has errors, changes were held back for a secret or credential the workspace cannot satisfy, or command/request failure | +| `1` | The source has errors, every change it would write was held back for a secret or credential the workspace cannot satisfy (nothing was written), or command/request failure | | `5` | A resource changed since the directory was read (`409 SOURCE_STALE`): get it again into a fresh directory, reapply the edit, and retry | | `6` | A resource (a workflow or its folder, a table) is locked (`423`); a locked block exits `1` (`E_APPLY_LOCKED_BLOCK`) | | `7` | The directory is over the size limits (`413`) | @@ -215,6 +215,7 @@ The CLI resends a request the API answers `429` only when sending it twice is sa | `9` | Still rate limited (`429`) after the CLI's retries; nothing was written | | `10` | Busy, retry: another apply is writing the workspace (`409 SOURCE_BUSY`), or another `sim workspaces source` command is using the same directory (`SOURCE_DIR_BUSY`); nothing was written: run the command again once the other finished | | `13` | `AUTH_REQUIRED`: not logged in, or the server refused the credential; nothing was sent | +| `15` | Written in part: changes that use a declared secret with no value, or a credential key nothing binds to, were held back and the rest was applied and saved; set the secret or connect the credential, then apply again (a promotion with `--to` too) | | `130` | Interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check | Both waits default to 3600 seconds; `--wait-timeout 0` waits indefinitely. `SIM_TIMEOUT_SECONDS` independently bounds one API request. A timeout does not cancel the underlying run or operation. diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index adfeedd64d3..6e950abe5a9 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -760,7 +760,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or changes were held back because they use a declared secret the workspace has no value for or a declared credential key nothing binds to (the rest was applied: set the secret or connect the credential, then apply again), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run that would hold changes back exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog). diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index 24d9d4a8bd8..775a4c1ef8d 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -4,6 +4,7 @@ import { RATE_LIMITED_EXIT_CODE, SOURCE_BUSY_EXIT_CODE, SOURCE_DRIFT_EXIT_CODE, + SOURCE_HELD_EXIT_CODE, SOURCE_LOCAL_CHANGES_EXIT_CODE, SOURCE_LOCKED_EXIT_CODE, SOURCE_PARTIAL_EXIT_CODE, @@ -79,7 +80,7 @@ function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRow[] { 'workflows source get': "the command failed, the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force)", 'workspaces source apply': - 'the source has errors (each printed as file:line:column with its frame and hint), or changes were held back because they use a declared secret the workspace has no value for or a declared credential key nothing binds to (the rest was applied: set the secret or connect the credential, then apply again), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed', + 'the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run that would hold changes back exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed', 'workspaces source get': 'the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written)', }, @@ -200,6 +201,16 @@ function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRow[] { 'without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it)', }, }, + { + code: SOURCE_HELD_EXIT_CODE, + meaning: + '`sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to', + next: 'Set the secret (`sim secrets set`) or connect the credential, then apply again', + help: { + 'workspaces source apply': + 'written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again)', + }, + }, { code: INTERRUPTED_EXIT_CODE, meaning: `Interrupted (Ctrl-C). An apply or create already sent is finished and saved into the directory first, waiting up to ${DEFERRED_SECONDS}s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written`, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index a054f034f21..b4cd34db966 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1597,7 +1597,7 @@ describe('workspaces source apply', () => { expect(Object.keys(body.files)).not.toContain('notes.ts') }) - it('saves what an apply wrote around the changes it held back, and exits 1', async () => { + it('saves what an apply wrote around the changes it held back, and exits 15 (written in part)', async () => { request.mockResolvedValue( answer({ plan: [ @@ -1622,7 +1622,7 @@ describe('workspaces source apply', () => { await apply('--yes') - expect(process.exitCode).toBe(1) + expect(process.exitCode).toBe(15) const printed = vi .mocked(console.log) .mock.calls.map(([line]) => String(line)) @@ -1636,6 +1636,28 @@ describe('workspaces source apply', () => { expect(warned).toContain('Held back, not written: workflow ingest') }) + it('exits 1, not 15, when every change it would write was held back and nothing was written', async () => { + request.mockResolvedValue( + answer({ + plan: [{ kind: 'workflow', key: 'ingest', action: 'create', held: true }], + applied: [], + diagnostics: [ + { + code: 'E_SECRET_MISSING', + severity: 'error', + message: 'workflows/ingest is held back: it reads the secret OPENAI_API_KEY.', + kind: 'workflow', + key: 'ingest', + }, + ], + }) + ) + + await apply('--yes') + + expect(process.exitCode).toBe(1) + }) + it('saves the applied answer when the catalog of a workflow it reprinted cannot be fetched, and says its edges are unrecorded', async () => { const configDir = mkdtempSync(join(tmpdir(), 'sim-workspace-apply-config-')) vi.stubEnv('SIM_CONFIG_DIR', configDir) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index b11758c4894..c53bd278bd5 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -23,7 +23,7 @@ import { serverResourceChanges } from '@sim/workspace-code/status' import type { Command } from 'commander' import { printError } from '#sim-cli/output/io' import { setSoftExitCode } from '../../embed-context' -import { SOURCE_PARTIAL_EXIT_CODE } from '../../exit-codes' +import { SOURCE_HELD_EXIT_CODE, SOURCE_PARTIAL_EXIT_CODE } from '../../exit-codes' import type { ApplyWorkspaceSourceBody, ApplyWorkspaceSourceResponse, @@ -886,7 +886,8 @@ export function attachWorkspaceSourceApply(source: Command): void { printError( `Held back, not written: ${held.map((change) => `${change.kind} ${change.key}`).join(', ')}. Fix what each one's error names, then apply again.` ) - setSoftExitCode(1) + // Written in part is not the same outcome as nothing written: a script must tell them apart. + setSoftExitCode(!data.dryRun && data.applied.length > 0 ? SOURCE_HELD_EXIT_CODE : 1) } if (data.failed) { printError(`Stopped at ${data.failed.kind} ${data.failed.key}: ${data.failed.message}`) 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 2f114af9085..7a98d1189f4 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -51,6 +51,7 @@ import { RATE_LIMITED_EXIT_CODE, SOURCE_BUSY_EXIT_CODE, SOURCE_DRIFT_EXIT_CODE, + SOURCE_HELD_EXIT_CODE, SOURCE_LOCAL_CHANGES_EXIT_CODE, SOURCE_PLANNED_EXIT_CODE, SOURCE_STALE_EXIT_CODE, @@ -138,7 +139,7 @@ ${APPLY_ORDER.map((kind) => `- ${WORKSPACE_KIND_SPECS[kind].guide}`).join('\n')} One apply creates resources before the workflows that use them, so a workflow may name a key this directory declares before it exists. \`.sim/sdk/workspace.d.ts\` types the keys the server held at the last get and the ones this directory declares, with each workflow's inputs: \`sim workspaces source check\` (or \`sim workflows source check\` in a workflow folder) regenerates it from the files, so run it before \`tsc\` after adding a resource or a workflow input. The dry run is the authority. -Secrets never appear in source: a workflow reads an environment variable as \`env.NAME\` and tool code as \`$env.NAME\`, both by name, and a saved credential is \`credential('')\`. Declare the ones workflows use in \`${KIND_DIRS.secret}\` and \`${KIND_DIRS.credential}\`: a workflow using a declared secret the workspace has no value for, or a declared credential key nothing binds to, is held back (exit 1, with the command that fixes it) while the rest of the apply is written. The same directory applied to another workspace binds each credential key to that workspace's own credential. +Secrets never appear in source: a workflow reads an environment variable as \`env.NAME\` and tool code as \`$env.NAME\`, both by name, and a saved credential is \`credential('')\`. Declare the ones workflows use in \`${KIND_DIRS.secret}\` and \`${KIND_DIRS.credential}\`: a workflow using a declared secret the workspace has no value for, or a declared credential key nothing binds to, is held back, with the command that fixes it, while the rest of the apply is written (exit ${SOURCE_HELD_EXIT_CODE}; exit 1 when nothing else was). The same directory applied to another workspace binds each credential key to that workspace's own credential. ## Edit loop in detail diff --git a/packages/sim-cli/src/exit-codes.ts b/packages/sim-cli/src/exit-codes.ts index 2841dac4ccd..5f37146b550 100644 --- a/packages/sim-cli/src/exit-codes.ts +++ b/packages/sim-cli/src/exit-codes.ts @@ -79,5 +79,14 @@ export const AUTH_REQUIRED_EXIT_CODE = 13 */ export const SOURCE_PLANNED_EXIT_CODE = 14 +/** + * A `workspaces source apply` (or a promotion with `--to`) that wrote part of its plan and held the + * rest back: a change that uses a declared secret the workspace has no value for, or a declared + * credential key nothing binds to. What was written is saved; set the secret or connect the + * credential and apply again. Apart from exit 1 (nothing written), so a script can tell a clean + * refusal from a target left half-applied. + */ +export const SOURCE_HELD_EXIT_CODE = 15 + /** The error code of an {@link AUTH_REQUIRED_EXIT_CODE} refusal the CLI raises itself. */ export const AUTH_REQUIRED_CODE = 'AUTH_REQUIRED' diff --git a/packages/workflow-sdk/README.md b/packages/workflow-sdk/README.md index b89d18588df..6966af6e1dd 100644 --- a/packages/workflow-sdk/README.md +++ b/packages/workflow-sdk/README.md @@ -122,6 +122,7 @@ Every `sim workflows source` and `sim workspaces source` command exits with one | 12 | `status`: the server changed since the get (drift, or a conflict with your edits) | Follow the `Next:` line it prints | | 13 | Not logged in, or the server refused the credential (`AUTH_REQUIRED`); nothing was sent | `sim login`, or fix or unset `SIM_API_KEY` | | 14 | `apply` or `create` without `--yes` and no terminal to ask: it printed the plan, found no errors, and wrote nothing | Run the same command with `--yes` | +| 15 | `sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret with no value, or a credential key nothing binds to | Set the secret or connect the credential, then apply again | | 130 | Interrupted (Ctrl-C). An apply or create already sent is finished and saved first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and says it may have been written | `sim workflows source status --dir ./wf` | ## Write declarations, not programs From 09f9bd79417e6262ef8d9e53e028f75d033b3e7a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:13:19 -0800 Subject: [PATCH 22/85] fix(table): a write that joins a table transaction keeps that transaction's timeouts withLockedTable reset the 10s statement and 5s idle defaults each time a write joined a TableWriteTx, dropping a scaled timeout an earlier step set. Only a transaction it opens itself gets the defaults now. --- apps/sim/lib/table/rows/writes.integration.ts | 17 +++++++++++++++++ apps/sim/lib/table/service.ts | 3 ++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/table/rows/writes.integration.ts b/apps/sim/lib/table/rows/writes.integration.ts index 3c79f78d18d..00a2b951f53 100644 --- a/apps/sim/lib/table/rows/writes.integration.ts +++ b/apps/sim/lib/table/rows/writes.integration.ts @@ -46,6 +46,7 @@ import { import { lockUniqueColumns, lockUniqueValues } from '@/lib/table/rows/unique-locks' import { getTableById, withTableWriteTx } from '@/lib/table/service' import { getOrCreateTableSnapshot } from '@/lib/table/snapshot-cache' +import { setTableTxTimeouts } from '@/lib/table/tx' import type { ColumnDefinition, JsonValue, RowData, TableDefinition } from '@/lib/table/types' import { checkBatchUniqueConstraintsDb } from '@/lib/table/validation' import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' @@ -376,6 +377,22 @@ describe('table row writes against real PostgreSQL', () => { expect(timeout).toBe('1min') }) + it('keeps the timeouts of the transaction a column write joins', async () => { + const table = await createTable([{ id: 'key', name: 'key', type: 'string' }]) + + const timeouts = await withTableWriteTx(table.id, async (locked, tx) => { + await setTableTxTimeouts(tx.trx, { statementMs: 120_000, idleMs: 120_000 }) + await addTableColumn(locked.id, { name: 'note', type: 'string' }, 'joined-timeouts', { tx }) + const [setting] = await tx.trx.execute<{ statement: string; idle: string }>( + sql`SELECT current_setting('statement_timeout') AS statement, + current_setting('idle_in_transaction_session_timeout') AS idle` + ) + return setting + }) + + expect(timeouts).toEqual({ statement: '2min', idle: '2min' }) + }) + describe('unique columns under concurrent writes', () => { const uniqueColumns: ColumnDefinition[] = [ { id: 'email', name: 'email', type: 'string', unique: true }, diff --git a/apps/sim/lib/table/service.ts b/apps/sim/lib/table/service.ts index c867e63b2e6..a5a28f37449 100644 --- a/apps/sim/lib/table/service.ts +++ b/apps/sim/lib/table/service.ts @@ -134,7 +134,8 @@ export async function withLockedTable( opts?: { includeArchived?: boolean; expectedWorkspaceId?: string; tx?: TableWriteTx } ): Promise { const locked = async (trx: DbTransaction) => { - await setTableTxTimeouts(trx) + // A write joining `opts.tx` keeps the timeouts its opener (or an earlier heavy step) set. + if (!opts?.tx) await setTableTxTimeouts(trx) // Re-entrant: a write joining `opts.tx` that already holds this lock takes it again at once. await acquireAdvisoryXactLock(trx, 'user_table_schema', `user_table_schema:${tableId}`) const table = await getTableById(tableId, { tx: trx, includeArchived: opts?.includeArchived }) From 58227b65fdde9407c54aa6caa994a44d747a2c12 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:15:03 -0800 Subject: [PATCH 23/85] fix(sim-cli): workflows source apply and create print only the JSON with --output json, the starter's next step included --- .../protocol/workflow-source-apply.test.ts | 24 ++++++++++++++----- .../protocol/workflow-source-apply.ts | 24 ++++++++++++++----- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index d59012067f8..9e48bf99a3f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -184,8 +184,10 @@ describe('sim workflows source apply', () => { applied: false, dryRun: true, next: { command: `sim workflows source apply --dir ${dir} --allow-delete --yes` }, + blocksAdded: 1, }) - expect(stderrLines().join('\n')).toContain('Blocks: 1 added') + // The JSON on stdout is the plan: stderr does not repeat it. + expect(stderrLines().join('\n')).not.toContain('Blocks:') }) it('prints the whole next command in a table, never clipping the flag it names', async () => { @@ -253,13 +255,20 @@ describe('sim workflows source apply', () => { }) }) - it('with --yes, prints the summary of what it applied', async () => { + it('with --yes, prints the summary of what it applied for a person, and only the JSON for a machine', async () => { setTerminal(false) request.mockResolvedValue(outcome()) await apply(WORKFLOW_ID, '--dir', dir, '--yes') expect(dryRunFlags()).toEqual([false]) + expect(stderrLines().join('\n')).not.toContain('Blocks:') + expect(stdoutJson()).toMatchObject({ applied: true, blocksAdded: 1 }) + + vi.mocked(console.error).mockClear() + contextMockState.output = 'text' + request.mockResolvedValue(outcome()) + await apply(WORKFLOW_ID, '--dir', dir, '--yes') expect(stderrLines().join('\n')).toContain('Blocks: 1 added, 0 removed') }) @@ -1391,12 +1400,13 @@ describe('sim workflows source create on a directory with no workflow.ts', () => knownKeys: new Set(), }) expect(compiled.diagnostics.filter((d) => d.severity === 'error')).toEqual([]) - expect(stderrLines().join('\n')).toContain('Edit') + expect(stderrLines()).toEqual([]) const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') expect(printed).toMatchObject({ scaffolded: true, workspaceTypes: true, guide: '.sim/AGENTS.md', + next: { command: expect.stringContaining('sim workflows source create --dir') }, }) expect(printed.files).toBeGreaterThan(0) }) @@ -1444,9 +1454,11 @@ describe('sim workflows source create on a directory with no workflow.ts', () => expect(JSON.parse(readFileSync(join(empty, '.sim/starter.json'), 'utf8'))).toEqual({ workspaceId: WORKSPACE_ID, }) - expect(stderrLines().join('\n')).toContain( - `sim workflows source create --dir ${empty} --workspace ${WORKSPACE_ID} --yes` - ) + expect(JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}')).toMatchObject({ + next: { + command: `sim workflows source create --dir ${empty} --workspace ${WORKSPACE_ID} --yes`, + }, + }) }) it('creates a starter in the workspace it was typed for, whatever the profile default', async () => { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index 66c62c5a69c..047b5804e2e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -186,7 +186,11 @@ async function writeWorkflowSource(args: preview: () => send(true), show: (preview) => printFindings(preview, findings, notes), refuses: hasErrors, - explain: (preview) => printError(diffSummary(preview)), + // A machine result carries the same counts, so its stderr holds findings and notes only; a + // person asked to confirm still reads what the write would change. + explain: (preview) => { + if (!findings.machine || mode === 'ask') printError(diffSummary(preview)) + }, commit: async () => { const answer = await send(false) printFindings(answer, findings, notes) @@ -203,7 +207,7 @@ async function writeWorkflowSource(args: }) if (!data) return - if (mode === 'write' && stored(data)) printError(diffSummary(data)) + if (mode === 'write' && stored(data) && !findings.machine) printError(diffSummary(data)) let deployment: DeployOutcome = {} if (stored(data)) { try { @@ -473,10 +477,18 @@ export function attachWorkflowSourceCreate(source: Command): void { const { client, profile } = connectCreate() const workspaceId = client.requireWorkspace() const tree = await writeSourceScaffold(client, options.dir, workspaceId) - printError( - `${options.dir} had no ${ENTRY_FILE}, so a starter, the SDK types for workspace ${workspaceId}, tsconfig.json, .sim/AGENTS.md and the examples in .sim/examples/ were written and nothing was created. Edit ${ENTRY_FILE}, then run \`${createCommand(options.dir, workspaceId)} --yes\`.` - ) - printTreeResult(profile.output, { created: false, scaffolded: true, ...tree }) + const next: NextStep = { + command: `${createCommand(shellWord(options.dir), workspaceId)} --yes`, + reason: `${options.dir} had no ${ENTRY_FILE}, so a starter, the SDK types for workspace ${workspaceId}, tsconfig.json, .sim/AGENTS.md and the examples in .sim/examples/ were written and nothing was created. Edit ${ENTRY_FILE}, check it, then create it.`, + } + const machine = profile.output === 'json' || profile.output === 'yaml' + if (!machine) printError(`${next.reason} Next: ${next.command}`) + printTreeResult(profile.output, { + created: false, + scaffolded: true, + ...tree, + ...(machine ? { next } : {}), + }) return } assertDeployable(options) From 9cbfca70a8d7f82af436bbed9d886c3e994d8649 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:16:29 -0800 Subject: [PATCH 24/85] perf(workspace-source): run a table plan's independent reads a few at a time The column-rename check loaded each using workflow's draft, source and live version one after another, and the allow-delete check read each undeclared table's rows version in turn. Both now run at a bounded concurrency of 4, with findings kept in the same order. --- .../application/kinds/table/adapter.ts | 25 ++-- .../application/kinds/table/renames.ts | 136 ++++++++++-------- 2 files changed, 93 insertions(+), 68 deletions(-) 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 1b07e4359c8..94102ab611a 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts @@ -16,6 +16,7 @@ * directory never read) may only gain columns and rows into an empty table; any other change to * it is refused (`refuseUnreadAdopt`). */ +import { mapWithConcurrency } from '@sim/utils/concurrency' import { setOwn } from '@sim/workflow-code' import { type BaseColumn, @@ -811,6 +812,9 @@ function reshapeInput( } } +/** Tables whose rows version {@link managedRowsMovedSinceBase} reads at once. */ +const ROWS_VERSION_CONCURRENCY = 4 + /** * The undeclared tables an `--allow-delete` plan may delete whose managed rows were written since * the base recorded them (their rows version moved), by id. @@ -820,15 +824,20 @@ async function managedRowsMovedSinceBase( stored: StoredSet, ctx: PlanContext ): Promise> { - const moved = new Set() - if (!ctx.allowDelete) return moved - for (const [key, resource] of stored.bound) { - if (desired.has(key)) continue + if (!ctx.allowDelete) return new Set() + const recorded = [...stored.bound].flatMap(([key, resource]) => { + if (desired.has(key)) return [] const entry = ctx.base?.resources[resourceAddress('table', key)] - if (entry?.id !== resource.id || !entry.rows) continue - if ((await rowsVersion(ctx, resource.id)) !== entry.rows.version) moved.add(resource.id) - } - return moved + return entry?.id === resource.id && entry.rows + ? [{ id: resource.id, version: entry.rows.version }] + : [] + }) + const versions = await mapWithConcurrency(recorded, ROWS_VERSION_CONCURRENCY, ({ id }) => + rowsVersion(ctx, id) + ) + return new Set( + recorded.filter((table, index) => versions[index] !== table.version).map(({ id }) => id) + ) } export const tableAdapter: KindAdapter<'table', StoredTableState> = { diff --git a/apps/sim/lib/workspace-source/application/kinds/table/renames.ts b/apps/sim/lib/workspace-source/application/kinds/table/renames.ts index 5e814e546d7..9f5c65763be 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/renames.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/renames.ts @@ -5,6 +5,7 @@ * the directory declares that workflow. A workflow folder the apply evaluates is checked by its own * lint against the declared columns, so only workflows the apply leaves as stored are scanned here. */ +import { mapWithConcurrency } from '@sim/utils/concurrency' import { escapeRegExp } from '@sim/utils/string' import { splitLines } from '@sim/workflow-code' import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' @@ -19,7 +20,14 @@ import { import { finding, where } from '@/lib/workspace-source/application/findings' import { liveVersionsReplaced, workflowsUsing } from '@/lib/workspace-source/application/in-use' import type { TablePlan } from '@/lib/workspace-source/application/kinds/table/adapter' -import type { PlanContext, PlannedChange } from '@/lib/workspace-source/application/types' +import type { + PlanContext, + PlannedChange, + WorkspaceSourceDiagnostic, +} from '@/lib/workspace-source/application/types' + +/** Workflows whose draft, source or live version the check reads at once. */ +const READ_CONCURRENCY = 4 /** A table this plan renames columns of: its id, name, and each old name → new name. */ interface RenamingTable { @@ -106,73 +114,56 @@ export async function checkColumnRenamesInUse( declared.set(change.storedId, { key: change.key, evaluated: change.refs !== undefined }) } const replacedLive = liveVersionsReplaced(changes) - for (const table of tables) { + const deleted = new Set( + changes.flatMap((c) => + c.kind === 'workflow' && c.action === 'delete' && c.storedId !== undefined ? [c.storedId] : [] + ) + ) + const checks = tables.flatMap((table) => + (using.get(table.tableId) ?? []) + .filter((workflow) => !deleted.has(workflow.id)) + .map((workflow) => ({ table, workflow })) + ) + // Each check loads a workflow's draft, source or live version: independent reads, run a few at + // once, their findings kept in check order. + const found = await mapWithConcurrency(checks, READ_CONCURRENCY, async ({ table, workflow }) => { + const findings: WorkspaceSourceDiagnostic[] = [] const columns = new Map([ [table.tableId, { name: table.tableName, columnNames: table.columnNames }], ]) - for (const workflow of using.get(table.tableId) ?? []) { - const folder = declared.get(workflow.id) - if ( - changes.some( - (c) => c.kind === 'workflow' && c.storedId === workflow.id && c.action === 'delete' - ) - ) { - continue - } - /** `blockId:field` of each finding already made from the draft. */ - const reported = new Set() - if (workflow.draft && !folder?.evaluated) { - const loaded = await loadWorkflowFromNormalizedTables(workflow.id) - const issues = loaded - ? collectTableBlockFieldIssues(loaded.blocks, columns).filter((issue) => - table.renamed.has(issue.field) - ) - : [] - const text = - folder && issues.length > 0 - ? ( - await readWorkflowSource.execute({ - principal: ctx.principal, - input: { workflowId: workflow.id, plan: true }, - }) - ).files[SOURCE_ENTRY_FILE] - : undefined - for (const issue of issues) { - reported.add(`${issue.blockId}:${issue.field}`) - const renamedTo = table.renamed.get(issue.field) - const blockName = issue.blockName ?? issue.blockId - const at = text !== undefined ? locateWrite(text, blockName, issue.field) : undefined - table.change.diagnostics.push( - finding( - 'W_TABLE_COLUMN_RENAMED_IN_USE', - `${where('table', table.change.key)} renames column "${issue.field}" to "${renamedTo}", but block "${blockName}" of workflow "${workflow.name}" still ${issue.rowWrite ? 'writes' : 'reads'} "${issue.field}"; the run drops it.`, - { - hint: `Write "${renamedTo}" in that block${folder ? ` (${workflowFolder(folder.key)}/${SOURCE_ENTRY_FILE})` : ''}, in this apply or right after it.`, - ...(folder - ? { file: `${workflowFolder(folder.key)}/${SOURCE_ENTRY_FILE}`, ...(at ?? {}) } - : {}), - kind: 'table', - key: table.change.key, - } - ) + const folder = declared.get(workflow.id) + /** `blockId:field` of each finding already made from the draft. */ + const reported = new Set() + if (workflow.draft && !folder?.evaluated) { + const loaded = await loadWorkflowFromNormalizedTables(workflow.id) + const issues = loaded + ? collectTableBlockFieldIssues(loaded.blocks, columns).filter((issue) => + table.renamed.has(issue.field) ) - } - } - if (!workflow.live || replacedLive.has(workflow.id)) continue - const live = await liveBlocks(workflow.id) - if (!live) continue - for (const issue of collectTableBlockFieldIssues(live, columns)) { - if (!table.renamed.has(issue.field) || reported.has(`${issue.blockId}:${issue.field}`)) { - continue - } + : [] + const text = + folder && issues.length > 0 + ? ( + await readWorkflowSource.execute({ + principal: ctx.principal, + input: { workflowId: workflow.id, plan: true }, + }) + ).files[SOURCE_ENTRY_FILE] + : undefined + for (const issue of issues) { + reported.add(`${issue.blockId}:${issue.field}`) const renamedTo = table.renamed.get(issue.field) const blockName = issue.blockName ?? issue.blockId - table.change.diagnostics.push( + const at = text !== undefined ? locateWrite(text, blockName, issue.field) : undefined + findings.push( finding( 'W_TABLE_COLUMN_RENAMED_IN_USE', - `${where('table', table.change.key)} renames column "${issue.field}" to "${renamedTo}", but block "${blockName}" of workflow "${workflow.name}" (live version) still ${issue.rowWrite ? 'writes' : 'reads'} "${issue.field}"; its runs drop it until the workflow is deployed again.`, + `${where('table', table.change.key)} renames column "${issue.field}" to "${renamedTo}", but block "${blockName}" of workflow "${workflow.name}" still ${issue.rowWrite ? 'writes' : 'reads'} "${issue.field}"; the run drops it.`, { - hint: `Write "${renamedTo}" in that block and deploy the workflow (\`deployments/.ts\` with live: 'draft'), in this apply or right after it.`, + hint: `Write "${renamedTo}" in that block${folder ? ` (${workflowFolder(folder.key)}/${SOURCE_ENTRY_FILE})` : ''}, in this apply or right after it.`, + ...(folder + ? { file: `${workflowFolder(folder.key)}/${SOURCE_ENTRY_FILE}`, ...(at ?? {}) } + : {}), kind: 'table', key: table.change.key, } @@ -180,5 +171,30 @@ export async function checkColumnRenamesInUse( ) } } - } + if (!workflow.live || replacedLive.has(workflow.id)) return findings + const live = await liveBlocks(workflow.id) + if (!live) return findings + for (const issue of collectTableBlockFieldIssues(live, columns)) { + if (!table.renamed.has(issue.field) || reported.has(`${issue.blockId}:${issue.field}`)) { + continue + } + const renamedTo = table.renamed.get(issue.field) + const blockName = issue.blockName ?? issue.blockId + findings.push( + finding( + 'W_TABLE_COLUMN_RENAMED_IN_USE', + `${where('table', table.change.key)} renames column "${issue.field}" to "${renamedTo}", but block "${blockName}" of workflow "${workflow.name}" (live version) still ${issue.rowWrite ? 'writes' : 'reads'} "${issue.field}"; its runs drop it until the workflow is deployed again.`, + { + hint: `Write "${renamedTo}" in that block and deploy the workflow (\`deployments/.ts\` with live: 'draft'), in this apply or right after it.`, + kind: 'table', + key: table.change.key, + } + ) + ) + } + return findings + }) + checks.forEach(({ table }, index) => { + table.change.diagnostics.push(...found[index]) + }) } From 9a2e2a8c93c1ed3988d3ad83ad446f109c3bdf95 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:18:49 -0800 Subject: [PATCH 25/85] feat(sim-cli): a source apply that deploys prints the URL of each webhook the workflow serves, promotions included --- apps/docs/content/docs/workflows/code.mdx | 2 +- .../src/commands/protocol/deployed-urls.ts | 67 +++++++++++++++++++ .../src/commands/protocol/source-primer.ts | 2 +- .../protocol/workflow-source-apply.test.ts | 54 ++++++++++++++- .../protocol/workflow-source-apply.ts | 25 +++++++ .../protocol/workspace-source-apply.test.ts | 35 ++++++++++ .../protocol/workspace-source-apply.ts | 64 ++++++++++++++++-- 7 files changed, 240 insertions(+), 9 deletions(-) create mode 100644 packages/sim-cli/src/commands/protocol/deployed-urls.ts diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx index 16b5cd48091..1c2ba9a0798 100644 --- a/apps/docs/content/docs/workflows/code.mdx +++ b/apps/docs/content/docs/workflows/code.mdx @@ -86,7 +86,7 @@ Nothing in the file runs on your machine. Sim reads it statically, checks it aga sim workflows source apply --dir ./support-triage --yes ``` - The workflow builder updates for anyone who has the workflow open. Deploy when you are ready, or add `--deploy` to deploy right after the save; without it, a deployed workflow whose draft now differs prints the `sim workflows deploy` command to run. `--yes` refuses everything a dry run would, so step 4 is optional: without `--yes`, and with no terminal to ask, `apply` prints the plan, writes nothing and exits `14`. The save rewrites `workflow.ts` in canonical form, so read it again before the next edit. + The workflow builder updates for anyone who has the workflow open. Deploy when you are ready, or add `--deploy` to deploy right after the save, which also prints the URL of each webhook the workflow now serves; without it, a deployed workflow whose draft now differs prints the `sim workflows deploy` command to run. `--yes` refuses everything a dry run would, so step 4 is optional: without `--yes`, and with no terminal to ask, `apply` prints the plan, writes nothing and exits `14`. The save rewrites `workflow.ts` in canonical form, so read it again before the next edit. Editing the name or description in `workflow('…')` renames or redescribes the workflow; a name another workflow in its folder already has is refused with `E_NAME_TAKEN`. Lines starting with `note:` report something the save did beyond what the file says; read them. diff --git a/packages/sim-cli/src/commands/protocol/deployed-urls.ts b/packages/sim-cli/src/commands/protocol/deployed-urls.ts new file mode 100644 index 00000000000..bff1978029b --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/deployed-urls.ts @@ -0,0 +1,67 @@ +/** + * The URLs a deploy makes live: after a source write deploys a workflow, each webhook it serves is + * named with its URL, so nobody has to look it up with `sim workflows deployment status` after. + */ +import { getErrorMessage } from '@sim/utils/errors' +import { isRecordLike } from '@sim/utils/object' +import { printError } from '#sim-cli/output/io' +import type { GetWorkflowDeploymentResponse } from '../../generated/v2-api' +import type { OperationClient } from '../../runtime/called-operations' + +/** A webhook of a deployed workflow, which callers reach at `url`. */ +export interface DeployedUrl { + /** The block key, with its const name when the lock names one: `leadin (hook)`. */ + block: string + url: string +} + +/** Each block id of a lock (`.sim/lock.json`) mapped to how source names it: `key (ident)`. */ +export function lockBlockNames(lock: unknown): Map { + const names = new Map() + const blocks = isRecordLike(lock) ? lock.blocks : undefined + if (!isRecordLike(blocks)) return names + for (const [key, entry] of Object.entries(blocks)) { + if (!isRecordLike(entry) || typeof entry.id !== 'string') continue + const ident = typeof entry.ident === 'string' && entry.ident !== key ? ` (${entry.ident})` : '' + names.set(entry.id, `${key}${ident}`) + } + return names +} + +/** The deployment's webhook URLs, each named through `names` (block id → source name). */ +export function namedUrls( + webhooks: GetWorkflowDeploymentResponse['data']['webhooks'], + names: ReadonlyMap +): DeployedUrl[] { + return webhooks.map(({ blockId, url }) => ({ + block: (blockId !== null ? names.get(blockId) : undefined) ?? blockId ?? 'webhook', + url, + })) +} + +/** + * The URL of each webhook `workflowId`'s live deployment serves, named through `names`. A failed + * read is reported and yields none: the deploy itself stands. + */ +export async function deployedUrls( + client: OperationClient<'getWorkflowDeployment'>, + workflowId: string, + names: ReadonlyMap +): Promise { + try { + const { data } = await client.request('getWorkflowDeployment', { + params: { workflowId }, + }) + return namedUrls(data.webhooks, names) + } catch (error) { + printError( + `The deploy succeeded, but its webhook URLs could not be read (${getErrorMessage(error)}): \`sim workflows deployment status ${workflowId}\` lists them.` + ) + return [] + } +} + +/** The URLs as one display line: `leadin (hook) https://…, …`. */ +export function deployedUrlsText(urls: readonly DeployedUrl[]): string { + return urls.map(({ block, url }) => `${block} ${url}`).join(', ') +} diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index fa3635a0837..6d93b033901 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -71,7 +71,7 @@ This directory is a Sim workspace as files (\`tables/\`, \`workflows//workf **Edit loop**: edit the files → \`sim workspaces source check --dir .\` (offline; refreshes \`workspace.d.ts\` and \`tsconfig.json\`) → \`${typecheckCommand()}\` → \`sim workspaces source apply --dir . --dry-run\` → \`--yes\`. Rerun each step until it exits 0. Apply rewrites the directory from what it stored: read a file again before the next edit. - **Deletes**: a removed file (a resource this directory managed), table column, workflow block or workflow variable is deleted only with \`apply --allow-delete\` (else refused), and cannot be undone. A kind is managed only when its folder exists. -- **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply; without one, apply never deploys. +- **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply, which prints its webhook URLs; without one, apply never deploys. - **Promote** (dev → prod): \`sim workspaces source apply --dir . --to --dry-run\`, then \`--yes\`. ${sharedRules('sim workspaces source', WORKSPACE_RENAMES)} ` diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index 9e48bf99a3f..2127a7c9e30 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -936,15 +936,63 @@ describe('sim workflows source apply', () => { }, } + const STATUS_PATH = `/api/v2/workflows/${WORKFLOW_ID}/deployment` + const HOOK_URL = 'https://sim.example/api/webhooks/trigger/abc' + /** A deployment status serving one webhook from the block `b-hook`. */ + const liveStatus = { + data: { + ...deployed.data, + needsRedeployment: false, + isPublicApi: false, + webhooks: [{ blockId: 'b-hook', provider: 'generic', url: HOOK_URL }], + }, + } + /** An apply whose stored lock binds `b-hook` as the block `leadin`, const `hook`. */ + const withHookLock = () => { + const answer = outcome() + answer.data.lock = { + ...LOCK, + blocks: { leadin: { id: 'b-hook', parent: null, ident: 'hook', order: 0 } }, + } as typeof LOCK + return answer + } + + it('names each webhook URL the deploy made live, by its block and const', async () => { + setTerminal(false) + request.mockImplementation(async (path: string) => + path === DEPLOY_PATH ? deployed : path === STATUS_PATH ? liveStatus : withHookLock() + ) + + await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--deploy') + + expect(request.mock.calls.map((call) => call[0])).toEqual([ + APPLY_PATH, + DEPLOY_PATH, + STATUS_PATH, + ]) + expect(stdoutJson()).toMatchObject({ urls: [{ block: 'leadin (hook)', url: HOOK_URL }] }) + + vi.mocked(console.log).mockClear() + contextMockState.output = 'text' + await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--deploy') + expect(vi.mocked(console.log).mock.calls.map((call) => call.join(' '))).toContain( + `urls\tleadin (hook) ${HOOK_URL}` + ) + }) + it('deploys through the deploy operation once the apply is saved', async () => { setTerminal(false) request.mockImplementation(async (path: string) => - path === DEPLOY_PATH ? deployed : outcome() + path === DEPLOY_PATH ? deployed : path === STATUS_PATH ? liveStatus : outcome() ) await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--deploy') - expect(request.mock.calls.map((call) => call[0])).toEqual([APPLY_PATH, DEPLOY_PATH]) + expect(request.mock.calls.map((call) => call[0])).toEqual([ + APPLY_PATH, + DEPLOY_PATH, + STATUS_PATH, + ]) // The deploy names the draft the apply stored, so an edit made since is never published. expect(request.mock.calls[1][1].body).toEqual({ expectedDraftFingerprint: outcome().data.base.fingerprint, @@ -959,7 +1007,6 @@ describe('sim workflows source apply', () => { it('deploys no new version when a no-op apply leaves the live version matching the draft', async () => { setTerminal(false) - const STATUS_PATH = `/api/v2/workflows/${WORKFLOW_ID}/deployment` const noop = outcome() noop.data.applied = false noop.data.diff.noop = true @@ -997,6 +1044,7 @@ describe('sim workflows source apply', () => { APPLY_PATH, STATUS_PATH, DEPLOY_PATH, + STATUS_PATH, ]) }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index 047b5804e2e..ddd8a8740b2 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -13,6 +13,13 @@ import type { import { SimApiError } from '../../http/client' import { apiCommand, type OperationClient } from '../../runtime/called-operations' import { searchTasks } from '../search' +import { + type DeployedUrl, + deployedUrls, + deployedUrlsText, + lockBlockNames, + namedUrls, +} from './deployed-urls' import { gitProvenance } from './git-provenance' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' @@ -171,6 +178,7 @@ async function writeWorkflowSource(args: ...(deployment.deployed ? { deployed: `version ${deployment.deployed.version ?? '?'}` } : {}), + ...(deployment.urls?.length ? { urls: deployedUrlsText(deployment.urls) } : {}), } ) } @@ -229,6 +237,8 @@ async function writeWorkflowSource(args: interface DeployOutcome { deployed?: { version?: number; isDeployed: boolean; warnings?: string[] } needsRedeployment?: boolean + /** The URL of each webhook the live deployment serves. */ + urls?: DeployedUrl[] next?: NextStep } @@ -276,6 +286,7 @@ async function deployStep( isDeployed: true, }, needsRedeployment: false, + ...urlsOf(namedUrls(status.webhooks, lockBlockNames(data.lock))), } } } @@ -301,9 +312,23 @@ async function deployStep( ...(options.machine && deployed.warnings.length > 0 ? { warnings: deployed.warnings } : {}), }, needsRedeployment: false, + ...(deployed.isDeployed ? await liveUrls(client, data) : {}), } } +/** The live deployment's webhook URLs, each named as the stored lock names its block. */ +async function liveUrls( + client: OperationClient<'getWorkflowDeployment'>, + data: SourceApplyData +): Promise> { + return urlsOf(await deployedUrls(client, data.workflowId, lockBlockNames(data.lock))) +} + +/** `urls` as a deploy outcome's field: absent when there are none. */ +function urlsOf(urls: DeployedUrl[]): Pick { + return urls.length > 0 ? { urls } : {} +} + /** A failed deploy after a saved write, saying the write itself stands and how to deploy it. */ function deployFailure( error: unknown, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index b4cd34db966..df878877307 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1636,6 +1636,41 @@ describe('workspaces source apply', () => { expect(warned).toContain('Held back, not written: workflow ingest') }) + it('names the webhook URLs of each workflow it deployed, by workflow, block and const', async () => { + const hookUrl = 'https://sim.example/api/webhooks/trigger/abc' + const lock = { + version: 1, + blocks: { leadin: { id: 'b-hook', parent: null, ident: 'hook', order: 0 } }, + variables: {}, + } + request.mockImplementation(async (path: string) => + path === '/api/v2/workflows/wf_1/deployment' + ? { + data: { + id: 'wf_1', + isDeployed: true, + webhooks: [{ blockId: 'b-hook', provider: 'generic', url: hookUrl }], + }, + } + : answer({ + plan: [{ kind: 'deployment', key: 'ingest', action: 'create' }], + applied: [{ kind: 'deployment', key: 'ingest', action: 'create' }], + files: { 'workflows/ingest/.sim/lock.json': JSON.stringify(lock) }, + base: { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } }, + }) + ) + + await apply('--yes') + + const printed = vi + .mocked(console.log) + .mock.calls.map(([line]) => String(line)) + .join('\n') + expect(JSON.parse(printed)).toMatchObject({ + urls: [{ workflow: 'ingest', block: 'leadin (hook)', url: hookUrl }], + }) + }) + it('exits 1, not 15, when every change it would write was held back and nothing was written', async () => { request.mockResolvedValue( answer({ diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index c53bd278bd5..a99b7bbe96d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -32,6 +32,7 @@ import type { import { SimApiError } from '../../http/client' import { apiCommand, type OperationClient } from '../../runtime/called-operations' import { searchTasks } from '../search' +import { type DeployedUrl, deployedUrls, deployedUrlsText, lockBlockNames } from './deployed-urls' import { gitProvenance } from './git-provenance' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' @@ -678,6 +679,7 @@ export function attachWorkspaceSourceApply(source: Command): void { 'stageWorkspaceSourceBlobs', 'getWorkspaceSource', 'getSourceCatalog', + 'getWorkflowDeployment', ]) absoluteDirOption(command) verboseFlag(command) @@ -826,13 +828,21 @@ export function attachWorkspaceSourceApply(source: Command): void { const notSent = notSentFindings(submission.ignored) findings.print(notSent) /** Prints `data` as the result, with the findings about files the CLI did not send. */ - const report = (data: ApplyData, next?: NextStep) => { + const report = (data: ApplyData, next?: NextStep, urls: WorkflowUrl[] = []) => { const diagnostics = [...notSent, ...data.diagnostics] - const result = { ...summarize({ ...data, diagnostics }), ...(next ? { next } : {}) } + const result = { + ...summarize({ ...data, diagnostics }), + ...(urls.length > 0 ? { urls } : {}), + ...(next ? { next } : {}), + } printProtocolResult( profile.output, { ...result, ...findings.result(diagnostics) }, - { created: createdText(result.created), ...(next ? { next: next.command } : {}) } + { + created: createdText(result.created), + ...(urls.length > 0 ? { urls: workflowUrlsText(urls) } : {}), + ...(next ? { next: next.command } : {}), + } ) } const data = await runSourceWrite({ @@ -893,13 +903,59 @@ export function attachWorkspaceSourceApply(source: Command): void { printError(`Stopped at ${data.failed.kind} ${data.failed.key}: ${data.failed.message}`) setSoftExitCode(failedExitCode(data.failed)) } - report(data) + report(data, undefined, await deploymentUrls(client, data)) }, { readOnly: mode === 'dry-run' || mode === 'plan' } ) }) } +/** A webhook URL of a workflow an apply deployed, named by the workflow's key and the block's. */ +interface WorkflowUrl extends DeployedUrl { + workflow: string +} + +/** The URLs as one display line: `lead-intake: leadin (hook) https://…; …`. */ +function workflowUrlsText(urls: readonly WorkflowUrl[]): string { + const byWorkflow = new Map() + for (const { workflow, ...url } of urls) { + byWorkflow.set(workflow, [...(byWorkflow.get(workflow) ?? []), url]) + } + return [...byWorkflow] + .map(([workflow, each]) => `${workflow}: ${deployedUrlsText(each)}`) + .join('; ') +} + +/** + * The webhook URLs of each workflow a written apply deployed (a `deployments/.ts` it created + * or updated), in the workspace it wrote: a promotion's are the target's, which are new URLs. + * Each block is named as the workflow's reprinted lock names it. + */ +async function deploymentUrls( + client: OperationClient<'getWorkflowDeployment'>, + data: ApplyData +): Promise { + if (data.dryRun) return [] + const base = parseWorkspaceBase(data.base).base + const deployed = data.applied.filter( + (change) => change.kind === 'deployment' && change.action !== 'delete' + ) + const perWorkflow = await Promise.all( + deployed.map(async ({ key }): Promise => { + const workflowId = base?.resources[`workflow:${key}`]?.id + if (!workflowId) return [] + const lockText = data.files[`${KIND_DIRS.workflow}/${key}/${SOURCE_LOCK_FILE}`] + let lock: unknown = null + try { + lock = lockText === undefined ? null : JSON.parse(lockText) + } catch {} + const named = await deployedUrls(client, workflowId, lockBlockNames(lock)) + return named.map((url) => ({ workflow: key, ...url })) + }) + ) + return perWorkflow.flat() +} + /** This apply as a command, without `--yes` or `--dry-run`: what a plan run names next. */ function applyCommand(options: ApplyOptions): string { return [ From 7f6438f05209dad05a1f23c9db55b3785c916f5b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:21:35 -0800 Subject: [PATCH 26/85] feat(sim-cli): on GitHub Actions, source findings become file annotations and a workspace apply writes its plan to the step summary --- apps/docs/content/docs/cli/scripting.mdx | 2 +- .../src/commands/protocol/source-check.ts | 10 ++- .../src/commands/protocol/source-status.ts | 2 +- .../src/commands/protocol/source-ui.ts | 52 ++++++++++-- .../protocol/workflow-source-apply.ts | 2 +- .../protocol/workflow-source-check.test.ts | 23 ++++++ .../protocol/workflow-source-check.ts | 1 + .../commands/protocol/workflow-source-get.ts | 2 +- .../protocol/workspace-source-apply.test.ts | 43 ++++++++++ .../protocol/workspace-source-apply.ts | 59 +++++++++++++- .../protocol/workspace-source-check.ts | 7 +- .../commands/protocol/workspace-source-get.ts | 2 +- .../sim-cli/src/output/github-actions.test.ts | 23 ++++++ packages/sim-cli/src/output/github-actions.ts | 81 +++++++++++++++++++ 14 files changed, 292 insertions(+), 17 deletions(-) create mode 100644 packages/sim-cli/src/output/github-actions.test.ts create mode 100644 packages/sim-cli/src/output/github-actions.ts diff --git a/apps/docs/content/docs/cli/scripting.mdx b/apps/docs/content/docs/cli/scripting.mdx index b8f0973f026..cd4dc3307ec 100644 --- a/apps/docs/content/docs/cli/scripting.mdx +++ b/apps/docs/content/docs/cli/scripting.mdx @@ -378,7 +378,7 @@ exit "$status" ## Workspace source in CI -Keep a [workspace source directory](/workflows/workspace-code) in a repository, `.sim/` included, and let CI plan each pull request and apply each merge. The dry run exits `1` on errors and `5` when the workspace changed since the committed base; `check` downloads the block catalog once on a fresh runner. +Keep a [workspace source directory](/workflows/workspace-code) in a repository, `.sim/` included, and let CI plan each pull request and apply each merge. The dry run exits `1` on errors and `5` when the workspace changed since the committed base; `check` downloads the block catalog once on a fresh runner. On GitHub Actions (`GITHUB_ACTIONS=true`), every source command also annotates each error and warning at its file and line, so they show inline on the pull request, and `apply` (a dry run too) appends its plan and errors to the job's step summary. ```yaml title=".github/workflows/sim-workspace.yml" on: diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 2705043c6e4..70fede6d355 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -647,9 +647,15 @@ export function reportCheck( output: Parameters[0], findings: CheckFinding[], result: Record, - options: { verbose?: boolean; bound?: AnswerBound; unlisted?: UnlistedCounts } = {} + options: { + verbose?: boolean + bound?: AnswerBound + unlisted?: UnlistedCounts + /** The source directory, which GitHub Actions annotations resolve finding files under. */ + dir?: string + } = {} ): void { - const shown = findingsOutput(output, options.verbose) + const shown = findingsOutput(output, options.verbose, options.dir) const listed = boundAnswerFindings(findings, options.bound) shown.print(listed) const unlisted = options.unlisted ?? { errors: 0, warnings: 0 } diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index 6a876e1efec..ba7b57ceabe 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -151,7 +151,7 @@ export function printStatusReport( planLine: (plan: Plan) => string, findings: readonly Diagnostic[] ): void { - const shown = findingsOutput(format) + const shown = findingsOutput(format, false, report.dir) if (format === 'json' || format === 'yaml') { printDocument(format, findings.length > 0 ? { ...report, ...shown.result(findings) } : report) return diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index ba63ac6a31c..abb1dffa553 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -8,6 +8,7 @@ import { boundFindingText, type RefusalClass } from '@sim/workflow-code/diagnost import { SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { type FlatDiagnostic, refusalClass } from '@sim/workspace-code' import type { Command } from 'commander' +import { annotationLine, annotationPath, printAnnotations } from '#sim-cli/output/github-actions' import { printError } from '#sim-cli/output/io' import { askLine } from '#sim-cli/terminal/line-input' import type { OutputFormat } from '../../config/index' @@ -202,6 +203,33 @@ export interface FindingsOutput { result(diagnostics: readonly Diagnostic[]): { diagnostics?: ResultDiagnostic[] } } +/** + * A finding as a GitHub Actions annotation at its file, line and column (the file relative to the + * source directory `dir`, when known); none for an info finding. + */ +function findingAnnotation(diagnostic: Diagnostic, dir: string | undefined): string[] { + if (diagnostic.severity === 'info') return [] + const file = + diagnostic.file !== undefined && diagnostic.path === undefined + ? dir === undefined + ? diagnostic.file + : annotationPath(dir, diagnostic.file) + : undefined + const message = diagnostic.hint + ? `${diagnostic.message} Hint: ${diagnostic.hint}` + : diagnostic.message + return [ + annotationLine(diagnostic.severity, message, { + ...(file !== undefined ? { file } : {}), + ...(file !== undefined && diagnostic.line !== undefined ? { line: diagnostic.line } : {}), + ...(file !== undefined && diagnostic.column !== undefined + ? { column: diagnostic.column } + : {}), + title: diagnostic.code, + }), + ] +} + /** * Info findings a display format prints only with `--verbose`: they report what the server does * for the person (a new block placed by autolayout), so there is nothing to act on. @@ -210,22 +238,30 @@ const QUIET_INFO_CODES: ReadonlySet = new Set(['I_MAT_NEEDS_ /** * The {@link FindingsOutput} of `format`; `verbose` keeps info findings in a machine result, and - * the {@link QUIET_INFO_CODES} in a display one. It is + * the {@link QUIET_INFO_CODES} in a display one. In a GitHub Actions step every error and warning + * is also annotated at its file under the source directory `dir`, whatever the format. It is * the CLI's output edge, where each finding's message and hint are cut (`boundFindingText`): a * finding an offline check made is as long as its source made it until here. */ -export function findingsOutput(format: OutputFormat, verbose = false): FindingsOutput { +export function findingsOutput( + format: OutputFormat, + verbose = false, + dir?: string +): FindingsOutput { const printed = new Set() const machine = isMachine(format) return { machine, print(diagnostics) { - const unseen = diagnostics.filter( - (diagnostic) => - (verbose || !QUIET_INFO_CODES.has(diagnostic.code)) && - fresh(printed, findingKey(diagnostic)) - ) - if (!machine) printDiagnostics(unseen.map((diagnostic) => boundFindingText(diagnostic))) + const unseen = diagnostics + .filter( + (diagnostic) => + (verbose || !QUIET_INFO_CODES.has(diagnostic.code)) && + fresh(printed, findingKey(diagnostic)) + ) + .map((diagnostic) => boundFindingText(diagnostic)) + if (!machine) printDiagnostics(unseen) + printAnnotations(unseen.flatMap((diagnostic) => findingAnnotation(diagnostic, dir))) }, result: (diagnostics) => resultDiagnostics( diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index ddd8a8740b2..717bbf75245 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -165,7 +165,7 @@ async function writeWorkflowSource(args: }) } } - const findings = findingsOutput(args.output, options.verbose) + const findings = findingsOutput(args.output, options.verbose, options.dir) const notes = new Set() const report = (data: SourceApplyData, deployment: DeployOutcome = {}) => { const result = { ...summarize(data, creating, findings.machine), ...deployment } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index 9badc5a39cb..737bf89396f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts @@ -451,6 +451,29 @@ describe('sim workflows source check', () => { expect(findingLines()).not.toContain('The workspace has no env variable') }) + it('annotates each finding at its file, line and column in a GitHub Actions job', async () => { + vi.stubEnv('GITHUB_ACTIONS', 'true') + cacheCatalog() + writeWorkspace() + const folder = writeWorkflowFolder( + 'notify', + workspaceWorkflow((source) => source.replace('env.ANTHROPIC_API_KEY', 'env.ANTHROPIC_KEY')) + ) + + await checkIn(folder) + + const annotations = vi + .mocked(console.error) + .mock.calls.map((call) => call.join(' ')) + .filter((line) => line.startsWith('::')) + expect(annotations).toHaveLength(1) + expect(annotations[0]).toMatch( + new RegExp( + `^::warning file=${join(folder, 'workflow.ts')},line=\\d+,col=\\d+,title=W_ENV_UNKNOWN::secrets.ts does not declare ANTHROPIC_KEY` + ) + ) + }) + it('lists at most 20 warnings of one code, as a workflow answer does, and counts every one', async () => { cacheCatalog() writeWorkspace() diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts index ba4ae9b7188..f94cd15c58e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -128,6 +128,7 @@ export function attachWorkflowSourceCheck(source: Command): void { { verbose: options.verbose === true, unlisted, + dir: options.dir, } ) } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts index 4623eb3e402..28c6ec7cf27 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -128,7 +128,7 @@ export function attachWorkflowSourceGet(source: Command): void { workflowSource, workflowSource.blockTypes ) - const findings = findingsOutput(profile.output) + const findings = findingsOutput(profile.output, false, dir) findings.print(workflowSource.diagnostics) printTreeResult(profile.output, { workflowId: workflowSource.workflowId, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index df878877307..6b0450ca008 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1671,6 +1671,49 @@ describe('workspaces source apply', () => { }) }) + it('appends the plan and its errors to the GitHub Actions step summary', async () => { + const summary = join(dir, 'step-summary.md') + vi.stubEnv('GITHUB_ACTIONS', 'true') + vi.stubEnv('GITHUB_STEP_SUMMARY', summary) + request.mockResolvedValue( + answer({ + dryRun: true, + plan: [ + { kind: 'table', key: 'leads', action: 'create' }, + { kind: 'workflow', key: 'ingest', action: 'update', fields: ['blocks'] }, + ], + diagnostics: [ + { + code: 'E_APPLY_UNRESOLVED_REF', + severity: 'error', + message: 'Score lead | has no output teir.', + file: 'workflows/ingest/workflow.ts', + line: 12, + kind: 'workflow', + key: 'ingest', + }, + ], + }) + ) + + await apply('--dry-run') + + const markdown = readFileSync(summary, 'utf8') + expect(markdown).toContain('### Sim workspace plan: ws_local') + expect(markdown).toContain('| + | tables/leads | create | planned |') + expect(markdown).toContain('| ~ | workflows/ingest (blocks) | update | planned |') + expect(markdown).toContain( + '- `E_APPLY_UNRESOLVED_REF` workflows/ingest/workflow.ts:12: Score lead \\| has no output teir.' + ) + const annotations = vi + .mocked(console.error) + .mock.calls.map(([line]) => String(line)) + .filter((line) => line.startsWith('::error')) + expect(annotations).toEqual([ + `::error file=${join(dir, 'workflows/ingest/workflow.ts')},line=12,title=E_APPLY_UNRESOLVED_REF::Score lead | has no output teir.`, + ]) + }) + it('exits 1, not 15, when every change it would write was held back and nothing was written', async () => { request.mockResolvedValue( answer({ diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index a99b7bbe96d..c80b4d37029 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -21,6 +21,7 @@ import { } from '@sim/workspace-code/promote' import { serverResourceChanges } from '@sim/workspace-code/status' import type { Command } from 'commander' +import { appendStepSummary } from '#sim-cli/output/github-actions' import { printError } from '#sim-cli/output/io' import { setSoftExitCode } from '../../embed-context' import { SOURCE_HELD_EXIT_CODE, SOURCE_PARTIAL_EXIT_CODE } from '../../exit-codes' @@ -824,12 +825,13 @@ export function attachWorkspaceSourceApply(source: Command): void { } : data // The apply repeats findings the preview already showed: each is printed once. - const findings = findingsOutput(profile.output, options.verbose) + const findings = findingsOutput(profile.output, options.verbose, options.dir) const notSent = notSentFindings(submission.ignored) findings.print(notSent) /** Prints `data` as the result, with the findings about files the CLI did not send. */ const report = (data: ApplyData, next?: NextStep, urls: WorkflowUrl[] = []) => { const diagnostics = [...notSent, ...data.diagnostics] + appendStepSummary(planMarkdown({ ...data, diagnostics }, options.to ?? workspaceId)) const result = { ...summarize({ ...data, diagnostics }), ...(urls.length > 0 ? { urls } : {}), @@ -910,6 +912,61 @@ export function attachWorkspaceSourceApply(source: Command): void { }) } +/** At most this many changes and errors are listed in a step summary; the rest are counted. */ +const SUMMARY_ROWS = 50 + +/** A Markdown table cell: one line, with its pipes escaped. */ +function cell(text: string): string { + return text.replaceAll('|', '\\|').replace(/\s+/g, ' ') +} + +/** + * The plan of a dry run or apply to `workspaceId` as the Markdown a GitHub Actions step summary + * shows: each change and how it went, then each error. + */ +function planMarkdown(data: ApplyData, workspaceId: string): string { + const summary = summarize(data) + const changes = data.plan.filter((change) => change.action !== 'noop') + const rows = changes.slice(0, SUMMARY_ROWS).map((change) => { + const fields = change.fields?.length ? ` (${change.fields.join(', ')})` : '' + const fate = change.held + ? 'held back' + : data.dryRun + ? 'planned' + : outcomeText(change, data).replace(' — ', '') || 'written' + return `| ${SYMBOLS[change.action]} | ${cell(resourceWhere(change.kind, change.key))}${cell(fields)} | ${change.action} | ${fate} |` + }) + const errors = data.diagnostics.filter((finding) => finding.severity === 'error') + const lines = [ + `### Sim workspace ${data.dryRun ? 'plan' : 'apply'}: ${cell(workspaceId)}`, + '', + `${summary.created.length} to create, ${summary.updated} to update, ${summary.deleted} to delete, ${summary.unchanged} unchanged; ${summary.errors} error(s), ${summary.warnings} warning(s).`, + ...(rows.length > 0 + ? [ + '', + '| | Resource | Change | Outcome |', + '|---|---|---|---|', + ...rows, + ...(changes.length > rows.length ? [`\n…and ${changes.length - rows.length} more.`] : []), + ] + : []), + ...(errors.length > 0 + ? [ + '', + '**Errors**', + '', + ...errors + .slice(0, SUMMARY_ROWS) + .map( + (finding) => + `- \`${finding.code}\`${finding.file ? ` ${cell(finding.file)}${finding.line ? `:${finding.line}` : ''}` : ''}: ${cell(finding.message)}` + ), + ] + : []), + ] + return lines.join('\n') +} + /** A webhook URL of a workflow an apply deployed, named by the workflow's key and the block's. */ interface WorkflowUrl extends DeployedUrl { workflow: string diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts index 33c0f9458d3..3bc84ae964d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -175,7 +175,12 @@ export function attachWorkspaceSourceCheck(source: Command): void { profile.output, findings, { workflows: keys.length, catalogHash: catalog.hash }, - { verbose: options.verbose === true, bound: WORKSPACE_ANSWER_BOUND, unlisted } + { + verbose: options.verbose === true, + bound: WORKSPACE_ANSWER_BOUND, + unlisted, + dir: options.dir, + } ) }) } diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts index 0a25b1fb408..14f69a4794d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -372,7 +372,7 @@ export function attachWorkspaceSourceGet(source: Command): void { throw withSourceExitCode(error) }) const result = await writeWorkspaceSource(client, options.dir, data, options.force === true) - const findings = findingsOutput(profile.output) + const findings = findingsOutput(profile.output, false, options.dir) findings.print(data.diagnostics) for (const { kind, key, reason } of data.skipped) { printError( diff --git a/packages/sim-cli/src/output/github-actions.test.ts b/packages/sim-cli/src/output/github-actions.test.ts new file mode 100644 index 00000000000..b4a0b4366f1 --- /dev/null +++ b/packages/sim-cli/src/output/github-actions.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { annotationLine, inGithubActions } from './github-actions' + +describe('GitHub Actions workflow commands', () => { + it('escapes a message and its properties as the runner unescapes them', () => { + expect( + annotationLine('error', '100% wrong\nsecond line', { + file: 'workflows/a,b/workflow.ts', + line: 3, + column: 9, + title: 'E_X: y', + }) + ).toBe( + '::error file=workflows/a%2Cb/workflow.ts,line=3,col=9,title=E_X%3A y::100%25 wrong%0Asecond line' + ) + }) + + it('emits nothing outside a GitHub Actions job, or with the switch turned off', () => { + expect(inGithubActions({})).toBe(false) + expect(inGithubActions({ GITHUB_ACTIONS: 'false' })).toBe(false) + expect(inGithubActions({ GITHUB_ACTIONS: 'true' })).toBe(true) + }) +}) diff --git a/packages/sim-cli/src/output/github-actions.ts b/packages/sim-cli/src/output/github-actions.ts new file mode 100644 index 00000000000..00f11f7c43c --- /dev/null +++ b/packages/sim-cli/src/output/github-actions.ts @@ -0,0 +1,81 @@ +/** + * GitHub Actions output: inside a GitHub Actions job (`GITHUB_ACTIONS=true`) a finding becomes an + * `::error file=…,line=…::` workflow command, which the runner shows inline on the pull request, + * and a source write appends its plan to the job's step summary (`$GITHUB_STEP_SUMMARY`). + * + * The commands go to stderr: the runner reads workflow commands from both streams, and stdout + * stays the one result document a script parses. + */ +import { appendFileSync } from 'node:fs' +import { isAbsolute, join, relative } from 'node:path' +import { getErrorMessage } from '@sim/utils/errors' +import { embedStore } from '../embed-context' +import { isEnabled } from '../environment' +import { printError } from './io' + +/** Whether this process runs as a GitHub Actions step (never inside an embedded host). */ +export function inGithubActions(env: NodeJS.ProcessEnv = process.env): boolean { + return isEnabled(env.GITHUB_ACTIONS) && !embedStore.getStore() +} + +/** A workflow command's message, escaped as the runner unescapes it. */ +function escapeData(text: string): string { + return text.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A') +} + +/** A workflow command's property value, which also may not hold `:` or `,`. */ +function escapeProperty(text: string): string { + return escapeData(text).replaceAll(':', '%3A').replaceAll(',', '%2C') +} + +/** Where an annotation points: a file relative to the repository, and a line and column in it. */ +export interface AnnotationSite { + file?: string + line?: number + column?: number + title?: string +} + +/** One `::error`/`::warning`/`::notice` workflow command line. */ +export function annotationLine( + level: 'error' | 'warning' | 'notice', + message: string, + site: AnnotationSite = {} +): string { + const properties = [ + site.file !== undefined ? `file=${escapeProperty(site.file)}` : null, + site.line !== undefined ? `line=${site.line}` : null, + site.column !== undefined ? `col=${site.column}` : null, + site.title !== undefined ? `title=${escapeProperty(site.title)}` : null, + ].filter((property) => property !== null) + return `::${level}${properties.length > 0 ? ` ${properties.join(',')}` : ''}::${escapeData(message)}` +} + +/** + * `file` (relative to the source directory `dir`) as the runner resolves an annotation's path: + * relative to the job's working directory, where the checkout is. A path outside it stays absolute. + */ +export function annotationPath(dir: string, file: string): string { + const path = relative(process.cwd(), isAbsolute(file) ? file : join(dir, file)) + return path.startsWith('..') || isAbsolute(path) ? join(dir, file) : path +} + +/** Prints `lines` as workflow commands, when this is a GitHub Actions step. */ +export function printAnnotations(lines: readonly string[]): void { + if (!inGithubActions()) return + for (const line of lines) printError(line) +} + +/** + * Appends `markdown` to the job's step summary, when this is a GitHub Actions step that has one. A + * summary that cannot be written is reported and skipped: the command's own result stands. + */ +export function appendStepSummary(markdown: string, env: NodeJS.ProcessEnv = process.env): void { + const path = env.GITHUB_STEP_SUMMARY + if (!inGithubActions(env) || !path) return + try { + appendFileSync(path, `${markdown.trimEnd()}\n\n`) + } catch (error) { + printError(`The step summary could not be written: ${getErrorMessage(error)}`) + } +} From ab7d8deaeab8d8f2deb211d180888d2b673a73d5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:22:50 -0800 Subject: [PATCH 27/85] feat(sim-cli): workflows run --dir maps a failed run to the source file and line of the block that failed --- apps/docs/content/docs/cli/reference.mdx | 3 +- apps/docs/content/docs/cli/workflows.mdx | 1 + apps/docs/content/docs/cli/workspaces.mdx | 2 +- .../commands/protocol/run-source-location.ts | 103 ++++++++++++++++++ .../src/commands/protocol/source-primer.ts | 2 +- .../protocol/workflow-run-follow.test.ts | 65 +++++++++++ .../commands/protocol/workflow-run-follow.ts | 14 ++- 7 files changed, 185 insertions(+), 5 deletions(-) create mode 100644 packages/sim-cli/src/commands/protocol/run-source-location.ts diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 99a701c1bc3..f270d87229a 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8446,6 +8446,7 @@ sim workflows run [options] | `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | | `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | +| `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | | `--follow` | No | Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns. | | `--include-thinking` | No | Show model reasoning while following (requires --follow). | @@ -9993,7 +9994,7 @@ sim workspaces source apply [options] Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run that would hold changes back exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. -API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog). +API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). ### sim workspaces source check diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 3f62b7861ef..fe1c50cf92d 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -776,6 +776,7 @@ sim workflows run [options] | `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | | `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | +| `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | | `--follow` | No | Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns. | | `--include-thinking` | No | Show model reasoning while following (requires --follow). | diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 6e950abe5a9..7b1c2751806 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -762,7 +762,7 @@ sim workspaces source apply [options] Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run that would hold changes back exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. -API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog). +API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). ### Compile every workflow of a workspace source directory locally, without the server diff --git a/packages/sim-cli/src/commands/protocol/run-source-location.ts b/packages/sim-cli/src/commands/protocol/run-source-location.ts new file mode 100644 index 00000000000..69eb47350cd --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/run-source-location.ts @@ -0,0 +1,103 @@ +/** + * Where in a workflow source directory a failed run failed: the run names the failing block by id, + * the directory's lock binds that id to the block's key, const and function file, and a function + * block's error names its line, which the stored code keeps one to one with the file. + */ +import { isRecordLike, toRecord } from '@sim/utils/object' +import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' +import { annotationLine, annotationPath, printAnnotations } from '#sim-cli/output/github-actions' +import { printError } from '#sim-cli/output/io' +import { readPreviousLock, readSourceJson, readSourceText } from './source-dir' + +/** A failed block, as the source directory names it. */ +export interface RunFailureSite { + /** The file to open (relative to the working directory): the block's function file, else the entry. */ + file: string + line: number | null + /** The block's key, and its const when it differs: `normalize`, or `leadin (hook)`. */ + block: string + /** The entry file and the line of the block's declaration, when it is found there. */ + declaredAt: string | null +} + +/** The line a function block's error names (`Type Error: Line 3: …`), else `null`. */ +function errorLine(message: string): number | null { + const match = /\bLine (\d+)\b/.exec(message) + return match ? Number(match[1]) : null +} + +/** The 1-based line of `const =` in `entry`, else `null`. */ +function declarationLine(entry: string, ident: string): number | null { + const pattern = new RegExp(`^\\s*const\\s+${ident.replace(/\$/g, '\\$')}\\s*=`) + const index = entry.split('\n').findIndex((line) => pattern.test(line)) + return index === -1 ? null : index + 1 +} + +/** + * Where the run's failure sits in the workflow source directory `dir`: `null` when the error names + * no block, the directory holds another workflow's source, or its lock does not bind the block. + */ +export async function runFailureSite( + dir: string, + workflowId: string, + error: unknown +): Promise { + const { blockId, message } = toRecord(error) + if (typeof blockId !== 'string') return null + if (toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)).workflowId !== workflowId) return null + const blocks = toRecord(await readPreviousLock(dir)).blocks + if (!isRecordLike(blocks)) return null + const bound = Object.entries(blocks).find( + ([, entry]) => isRecordLike(entry) && entry.id === blockId + ) + if (!bound) return null + const [key, entry] = bound as [string, Record] + const ident = typeof entry.ident === 'string' ? entry.ident : key + const entryText = await readSourceText(dir, SOURCE_ENTRY_FILE) + const declared = entryText === null ? null : declarationLine(entryText, ident) + const entryPath = annotationPath(dir, SOURCE_ENTRY_FILE) + const declaredAt = declared === null ? null : `${entryPath}:${declared}` + const block = ident === key ? key : `${key} (${ident})` + if (typeof entry.codeFile === 'string') { + return { + file: annotationPath(dir, entry.codeFile), + line: typeof message === 'string' ? errorLine(message) : null, + block, + declaredAt, + } + } + return { file: entryPath, line: declared, block, declaredAt } +} + +/** + * Prints where a failed run failed in `dir` (on stderr, and as a GitHub Actions annotation in a + * job), or that `dir` cannot say. + */ +export async function printRunFailureSite( + dir: string, + workflowId: string, + error: unknown +): Promise { + const site = await runFailureSite(dir, workflowId, error) + if (!site) { + printError( + `${dir} does not bind the block that failed (another workflow's source, or a block added since the get), so the failure is not mapped to a source line.` + ) + return + } + const where = `${site.file}${site.line === null ? '' : `:${site.line}`}` + const declared = + site.declaredAt && !site.declaredAt.startsWith(`${site.file}:`) + ? `, declared at ${site.declaredAt}` + : '' + const message = toRecord(error).message + const text = typeof message === 'string' ? message : 'The block failed.' + printError(`${where}: ${text} (block ${site.block}${declared})`) + printAnnotations([ + annotationLine('error', text, { + file: site.file, + ...(site.line !== null ? { line: site.line } : {}), + title: `Run failed in ${site.block}`, + }), + ]) +} diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 6d93b033901..94a1302aa3f 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -45,7 +45,7 @@ function sharedRules(group: string, extraRenames = ''): string { - **Look up a builder**: \`${PARAMS_COMMAND} \` (\`agent\`, \`trigger.schedule\`; a namespace like \`gmail\` lists its builders), offline. - **Credentials**: \`sim credentials connect --name ""\`, give the owner its link, then \`credential('')\` (\`sim workflows source resources\`). - **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, reading the message as \`x.error\`. A retry is block meta, the third argument: \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\`. Branches that each reply: a \`response\` per branch. -- **Run and debug**: \`sim workflows run --manual --input '{…}'\` runs the saved draft, no deploy needed (without \`--manual\` it runs the deployed version). Runs write real data (rows, emails): test on test resources. A failed run: \`sim logs get --trace --no-include-workflow-state\` (spans hold resolved inputs). +- **Run and debug**: \`sim workflows run --manual --input '{…}'\` runs the saved draft, no deploy needed (without \`--manual\` it runs the deployed version). Runs write real data (rows, emails): test on test resources. With \`--dir \`, a failed run names the file and line that failed; then \`sim logs get --trace --no-include-workflow-state\` (spans hold resolved inputs). - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (\`${group} get --dir \`, redo the edit there), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed. Every code: \`${SOURCE_AGENTS_FILE}\`.` } diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index efc920960dd..ee3c11372fc 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -1,3 +1,6 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { Command } from 'commander' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SimApiError } from '../../http/client' @@ -404,6 +407,68 @@ describe('sim workflows run --follow', () => { expect(stdout).toHaveBeenCalled() }) + it('with --dir, names the source file and line of the block that failed, through the lock', async () => { + const dir = mkdtempSync(join(tmpdir(), 'sim-run-site-')) + try { + mkdirSync(join(dir, '.sim'), { recursive: true }) + writeFileSync(join(dir, '.sim/base.json'), JSON.stringify({ workflowId: WORKFLOW_ID })) + writeFileSync( + join(dir, '.sim/lock.json'), + JSON.stringify({ + version: 1, + blocks: { + normalize: { + id: 'b-fn', + parent: null, + ident: 'clean', + order: 0, + codeFile: 'functions/normalize.js', + }, + }, + variables: {}, + }) + ) + writeFileSync( + join(dir, 'workflow.ts'), + "export default workflow('W', () => {\n const start = trigger.start('Start', {})\n const clean = fn('Normalize', { code: codeFile('./functions/normalize.js') })\n})\n" + ) + const failed = (blockId: string) => + ndjsonResponse({ + type: 'final', + data: { + runId: 'run-1', + workflowId: WORKFLOW_ID, + status: 'failed', + output: {}, + error: { + message: + "Type Error: Line 3: `raw.email.split('@')` - Cannot read properties of undefined", + code: 'BLOCK_EXECUTION_FAILED', + blockId, + }, + }, + }) + vi.spyOn(console, 'log').mockImplementation(() => {}) + const stderr = vi.spyOn(console, 'error').mockImplementation(() => {}) + + requestRaw.mockResolvedValue(failed('b-fn')) + await expect(run(WORKFLOW_ID, '--dir', dir)).rejects.toThrow('Type Error') + const lines = stderr.mock.calls.map((call) => call.join(' ')) + expect(lines).toContain( + `${join(dir, 'functions/normalize.js')}:3: Type Error: Line 3: \`raw.email.split('@')\` - Cannot read properties of undefined (block normalize (clean), declared at ${join(dir, 'workflow.ts')}:3)` + ) + + stderr.mockClear() + requestRaw.mockResolvedValue(failed('b-unbound')) + await expect(run(WORKFLOW_ID, '--dir', dir)).rejects.toThrow('Type Error') + expect(stderr.mock.calls.map((call) => call.join(' ')).join('\n')).toContain( + 'is not mapped to a source line' + ) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + it('explains a deployment that answers JSON instead of an event stream', async () => { const cancel = vi.fn().mockResolvedValue(undefined) requestRaw.mockResolvedValue({ 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 f4bcf07d326..692ef162e2b 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,4 @@ -import { isRecordLike } from '@sim/utils/object' +import { isRecordLike, toRecord } from '@sim/utils/object' import type { Command } from 'commander' import { writeStderr } from '#sim-cli/output/io' import { styles } from '#sim-cli/output/presentation' @@ -14,6 +14,7 @@ import { retypeApiError } from '../../runtime/naming' import { buildRequest } from '../../runtime/request' import { renderResult } from '../../runtime/result' import type { OperationSpec } from '../../runtime/types' +import { printRunFailureSite } from './run-source-location' import { parseWaitTimeout, type RunSnapshot, @@ -250,7 +251,12 @@ async function runWithResultStream( }) const failure = runFailureMessage('executeWorkflow', payload) - if (failure) throw new SimApiError(failure, 0) + if (failure) { + if (typeof flags.dir === 'string') { + await printRunFailureSite(flags.dir, workflowId, toRecord(payload).error) + } + throw new SimApiError(failure, 0) + } } catch (error) { throw retypeApiError(error, 'executeWorkflow', commandSpec, operation) } @@ -595,6 +601,10 @@ export function attachWorkflowRunFollow(workflows: Command): void { '--stop-after ', 'Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual)' ) + .option( + '--dir ', + "This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json" + ) .option( WAIT_TIMEOUT_FLAG, 'Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow' From f0aec11d9fa9a0bd8db832971306b15eae8f3f24 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:26:23 -0800 Subject: [PATCH 28/85] feat(tables): a table route given a workspace finds the table by its name too (sim tables rows list leads) --- apps/docs/content/docs/cli/reference.mdx | 80 ++++---- apps/docs/content/docs/cli/tables.mdx | 80 ++++---- apps/docs/openapi-v2-tables.json | 156 +++++++-------- apps/sim/lib/api/contracts/tables.ts | 7 +- .../function-execute-table-mounts.test.ts | 2 + .../lib/table/application/analytics.test.ts | 1 + .../sim/lib/table/application/context.test.ts | 31 +++ apps/sim/lib/table/application/context.ts | 15 +- packages/sim-cli/src/generated/v2-api.ts | 187 ++++++++++++++---- 9 files changed, 357 insertions(+), 202 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index f270d87229a..d3a175846eb 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -5868,7 +5868,7 @@ sim tables columns create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -5900,7 +5900,7 @@ sim tables columns delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -5931,7 +5931,7 @@ sim tables columns update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -5962,7 +5962,7 @@ sim tables groups create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -5997,7 +5997,7 @@ sim tables groups delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6028,7 +6028,7 @@ sim tables groups list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6048,7 +6048,7 @@ sim tables groups update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6113,7 +6113,7 @@ sim tables rows update-each [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6143,7 +6143,7 @@ sim tables rows create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6176,7 +6176,7 @@ sim tables rows delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | @@ -6209,7 +6209,7 @@ sim tables rows batch-delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6242,7 +6242,7 @@ sim tables rows get [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | @@ -6274,7 +6274,7 @@ sim tables rows list [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6307,7 +6307,7 @@ sim tables rows query [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6342,7 +6342,7 @@ sim tables rows count [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6372,7 +6372,7 @@ sim tables rows enrich | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | | `groupId` | Yes | Workflow or enrichment group to run. | @@ -6394,7 +6394,7 @@ sim tables rows search [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6428,7 +6428,7 @@ sim tables rows batch-update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6461,7 +6461,7 @@ sim tables rows update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | @@ -6494,7 +6494,7 @@ sim tables dispatches cancel [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `dispatchId` | Yes | Unique table run-dispatch identifier. | @@ -6525,7 +6525,7 @@ sim tables dispatches create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6560,7 +6560,7 @@ sim tables dispatches get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `dispatchId` | Yes | Unique table run-dispatch identifier. | @@ -6581,7 +6581,7 @@ sim tables dispatches list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6601,7 +6601,7 @@ sim tables exports cancel | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `exportId` | Yes | Unique table-export identifier. | @@ -6622,7 +6622,7 @@ sim tables exports create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6652,7 +6652,7 @@ sim tables exports get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `exportId` | Yes | Unique table-export identifier. | @@ -6673,7 +6673,7 @@ sim tables exports download | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `exportId` | Yes | Unique table-export identifier. | @@ -6748,7 +6748,7 @@ sim tables cancel-runs [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6926,7 +6926,7 @@ sim tables views create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -6959,7 +6959,7 @@ sim tables views delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `viewId` | Yes | Unique saved-view identifier. | @@ -6990,7 +6990,7 @@ sim tables views get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `viewId` | Yes | Unique saved-view identifier. | @@ -7011,7 +7011,7 @@ sim tables views list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -7031,7 +7031,7 @@ sim tables views update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `viewId` | Yes | Unique saved-view identifier. | @@ -7068,7 +7068,7 @@ sim tables delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -7098,7 +7098,7 @@ sim tables enrichment get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | | `groupId` | Yes | Workflow or enrichment group to run. | @@ -7120,7 +7120,7 @@ sim tables get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -7187,7 +7187,7 @@ sim tables restore | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -7207,7 +7207,7 @@ sim tables update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -7239,7 +7239,7 @@ sim tables mv | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `folder` | Yes | Folder path as shown in the app; the leading / is optional | @@ -7260,7 +7260,7 @@ sim tables upsert [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | diff --git a/apps/docs/content/docs/cli/tables.mdx b/apps/docs/content/docs/cli/tables.mdx index ce1f3e06bec..5bf72591cdb 100644 --- a/apps/docs/content/docs/cli/tables.mdx +++ b/apps/docs/content/docs/cli/tables.mdx @@ -48,7 +48,7 @@ sim tables get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -87,7 +87,7 @@ sim tables update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -137,7 +137,7 @@ sim tables mv | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `folder` | Yes | Folder path as shown in the app; the leading / is optional | @@ -158,7 +158,7 @@ sim tables delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -208,7 +208,7 @@ sim tables restore | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -228,7 +228,7 @@ sim tables rows list [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -259,7 +259,7 @@ sim tables rows get [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | @@ -289,7 +289,7 @@ sim tables rows query [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -322,7 +322,7 @@ sim tables rows count [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -350,7 +350,7 @@ sim tables rows search [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -380,7 +380,7 @@ sim tables rows create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -409,7 +409,7 @@ sim tables rows update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | @@ -438,7 +438,7 @@ sim tables rows update-each [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -468,7 +468,7 @@ sim tables rows batch-update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -499,7 +499,7 @@ sim tables rows enrich | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | | `groupId` | Yes | Workflow or enrichment group to run. | @@ -521,7 +521,7 @@ sim tables rows delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | @@ -552,7 +552,7 @@ sim tables rows batch-delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -583,7 +583,7 @@ sim tables upsert [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -614,7 +614,7 @@ sim tables columns create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -642,7 +642,7 @@ sim tables columns update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -673,7 +673,7 @@ sim tables columns delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -704,7 +704,7 @@ sim tables views list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -722,7 +722,7 @@ sim tables views get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `viewId` | Yes | Unique saved-view identifier. | @@ -741,7 +741,7 @@ sim tables views create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -770,7 +770,7 @@ sim tables views update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `viewId` | Yes | Unique saved-view identifier. | @@ -805,7 +805,7 @@ sim tables views delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `viewId` | Yes | Unique saved-view identifier. | @@ -836,7 +836,7 @@ sim tables groups list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -854,7 +854,7 @@ sim tables groups create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -885,7 +885,7 @@ sim tables groups update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -926,7 +926,7 @@ sim tables groups delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -955,7 +955,7 @@ sim tables enrichment get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `rowId` | Yes | Unique table row identifier. | | `groupId` | Yes | Workflow or enrichment group to run. | @@ -975,7 +975,7 @@ sim tables dispatches list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -993,7 +993,7 @@ sim tables dispatches get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `dispatchId` | Yes | Unique table run-dispatch identifier. | @@ -1012,7 +1012,7 @@ sim tables dispatches create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -1047,7 +1047,7 @@ sim tables dispatches cancel [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `dispatchId` | Yes | Unique table run-dispatch identifier. | @@ -1078,7 +1078,7 @@ sim tables cancel-runs [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -1205,7 +1205,7 @@ sim tables exports create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | @@ -1233,7 +1233,7 @@ sim tables exports get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `exportId` | Yes | Unique table-export identifier. | @@ -1252,7 +1252,7 @@ sim tables exports download | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `exportId` | Yes | Unique table-export identifier. | @@ -1271,7 +1271,7 @@ sim tables exports cancel | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | | `exportId` | Yes | Unique table-export identifier. | diff --git a/apps/docs/openapi-v2-tables.json b/apps/docs/openapi-v2-tables.json index 4ee8a0156ac..b02dd46f6f6 100644 --- a/apps/docs/openapi-v2-tables.json +++ b/apps/docs/openapi-v2-tables.json @@ -318,11 +318,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -405,11 +405,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -492,11 +492,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -597,11 +597,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -702,11 +702,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -841,11 +841,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -945,11 +945,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -1067,11 +1067,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -1172,11 +1172,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -1285,11 +1285,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -1389,11 +1389,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -1497,11 +1497,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -1612,11 +1612,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -1712,11 +1712,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -1820,11 +1820,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -1959,11 +1959,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -2064,11 +2064,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -2148,11 +2148,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -2266,11 +2266,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -2361,11 +2361,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -2472,11 +2472,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -2569,11 +2569,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -2653,11 +2653,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -2771,11 +2771,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -2877,11 +2877,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -2981,11 +2981,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -3080,11 +3080,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -3166,11 +3166,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -3286,11 +3286,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -3397,11 +3397,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -4039,11 +4039,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -4143,11 +4143,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -4239,11 +4239,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -4340,11 +4340,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -4441,11 +4441,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -5056,11 +5056,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -5159,11 +5159,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } } ], @@ -5276,11 +5276,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { @@ -5372,11 +5372,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." } }, { diff --git a/apps/sim/lib/api/contracts/tables.ts b/apps/sim/lib/api/contracts/tables.ts index cae899749ab..92f4a903e8f 100644 --- a/apps/sim/lib/api/contracts/tables.ts +++ b/apps/sim/lib/api/contracts/tables.ts @@ -177,7 +177,12 @@ const descriptionSchema = z export const tableScopeSchema = z.enum(['active', 'archived', 'all']) export const tableIdParamsSchema = z.object({ - tableId: z.string().min(1).describe('Unique table identifier.'), + tableId: z + .string() + .min(1) + .describe( + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.' + ), }) export const tableRowParamsSchema = tableIdParamsSchema.extend({ diff --git a/apps/sim/lib/mothership/tools/handlers/function-execute-table-mounts.test.ts b/apps/sim/lib/mothership/tools/handlers/function-execute-table-mounts.test.ts index 19a460bad5f..a494bd83659 100644 --- a/apps/sim/lib/mothership/tools/handlers/function-execute-table-mounts.test.ts +++ b/apps/sim/lib/mothership/tools/handlers/function-execute-table-mounts.test.ts @@ -163,6 +163,8 @@ describe('Mothership table mounts through code calls', () => { 'conceals %s IDs before materialization', async (mode) => { mocks.table.mockResolvedValue(mode === 'missing' ? null : { ...table, workspaceId: 'other' }) + // Missing means by id and by name: an id the workspace lacks is also looked up as a name. + mocks.named.mockResolvedValue([]) await expect(run('table-orders')).rejects.toThrow('not found') expect(mocks.snapshot).not.toHaveBeenCalled() expect(mocks.download).not.toHaveBeenCalled() diff --git a/apps/sim/lib/table/application/analytics.test.ts b/apps/sim/lib/table/application/analytics.test.ts index e883c218e5f..f64dd4724ac 100644 --- a/apps/sim/lib/table/application/analytics.test.ts +++ b/apps/sim/lib/table/application/analytics.test.ts @@ -41,6 +41,7 @@ const input = { } beforeEach(() => { mocks.flag.mockResolvedValue(undefined) + tableServiceMockFns.mockFindActiveTablesByExactName.mockResolvedValue([]) mocks.table.mockResolvedValue({ id: 'tbl_test', workspaceId: 'workspace_test', diff --git a/apps/sim/lib/table/application/context.test.ts b/apps/sim/lib/table/application/context.test.ts index 75a4e17d13e..a4480ca680f 100644 --- a/apps/sim/lib/table/application/context.test.ts +++ b/apps/sim/lib/table/application/context.test.ts @@ -14,6 +14,7 @@ import { } from '@/lib/table/application/context' const getTableById = tableServiceMockFns.mockGetTableById +const findByName = tableServiceMockFns.mockFindActiveTablesByExactName const loadWorkspace = workspaceContextMockFns.mockLoadActiveWorkspaceApplicationContext const WORKSPACE_ONE = { @@ -71,6 +72,36 @@ describe('table application context', () => { expect(loadWorkspace).toHaveBeenCalledWith('workspace-1') }) + it('finds a table by its name within the asserted workspace, an id always first', async () => { + getTableById.mockImplementation(async (id: string) => + id === 'table-1' ? { id: 'table-1', workspaceId: 'workspace-1', name: 'leads' } : null + ) + findByName.mockImplementation(async (workspaceId: string, name: string) => + workspaceId === 'workspace-1' && name === 'leads' + ? [{ id: 'table-1', workspaceId: 'workspace-1', name: 'leads' }] + : [] + ) + + await expect( + resolveActiveTableContext({ tableId: 'leads', assertedWorkspaceId: 'workspace-1' }) + ).resolves.toMatchObject({ tableId: 'table-1', workspaceId: 'workspace-1' }) + expect(findByName).toHaveBeenCalledWith('workspace-1', 'leads') + + findByName.mockClear() + await resolveActiveTableContext({ tableId: 'table-1', assertedWorkspaceId: 'workspace-1' }) + expect(findByName).not.toHaveBeenCalled() + + // A name never reaches past the asserted workspace, and without one it is not looked up. + await expect( + resolveActiveTableContext({ tableId: 'leads', assertedWorkspaceId: 'workspace-2' }) + ).rejects.toMatchObject({ code: 'not_found' }) + findByName.mockClear() + await expect(resolveActiveTableContext({ tableId: 'leads' })).rejects.toMatchObject({ + code: 'not_found', + }) + expect(findByName).not.toHaveBeenCalled() + }) + it('conceals an asserted cross-workspace table as not found', async () => { await expect( resolveActiveTableContext({ tableId: 'table-1', assertedWorkspaceId: 'workspace-2' }) diff --git a/apps/sim/lib/table/application/context.ts b/apps/sim/lib/table/application/context.ts index 561ae94c5e1..1dadeb84400 100644 --- a/apps/sim/lib/table/application/context.ts +++ b/apps/sim/lib/table/application/context.ts @@ -1,6 +1,6 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import type { TableAuthorizationContext } from '@/lib/table/application/authorization' -import { getTableById } from '@/lib/table/service' +import { findActiveTablesByExactName, getTableById } from '@/lib/table/service' import type { TableDefinition } from '@/lib/table/types' import { loadActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' @@ -23,14 +23,21 @@ export async function resolveTableWorkspaceContext( * Loads a table and asserts it lives in `workspaceId` when the caller named one. * * Shared by both resolvers below so the not-found concealment — a table outside the asserted - * workspace is reported as missing, never as forbidden — is written once. + * workspace is reported as missing, never as forbidden — is written once. Within an asserted + * workspace a table is also found by its name (`sim tables rows list leads`), which is unique + * among the workspace's active tables; an id always wins, and a name never reaches past the + * asserted workspace. */ async function requireTable(tableId: string, workspaceId: string | undefined) { - const table = await getTableById(tableId) + let table = await getTableById(tableId) + if (!table && workspaceId !== undefined) { + const named = await findActiveTablesByExactName(workspaceId, tableId) + if (named.length === 1) table = named[0] + } if (!table || (workspaceId !== undefined && table.workspaceId !== workspaceId)) { throw new OrchestrationError( 'not_found', - `Table "${tableId}" not found in this workspace — it may not exist or may belong to a different workspace. List the tables in this workspace to see the ids you can use here.` + `Table "${tableId}" not found in this workspace, by id or by name — it may not exist or may belong to a different workspace. List the tables in this workspace to see the ids and names you can use here.` ) } return table diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 55c4fe4438e..d440597bfb9 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -20527,7 +20527,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/columns', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Add column', body: { @@ -20539,7 +20542,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/groups', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Add workflow group', body: { @@ -20909,7 +20915,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/rows/bulk-update', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Bulk update rows', body: { @@ -20956,7 +20965,8 @@ export const V2_OPERATIONS = { path: '/api/v2/tables/[tableId]/dispatches/[dispatchId]', pathParams: ['tableId', 'dispatchId'] as const, pathParamDocs: { - tableId: 'Unique table identifier.', + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', dispatchId: 'Unique table run-dispatch identifier.', }, responseMode: 'json', @@ -20974,7 +20984,8 @@ export const V2_OPERATIONS = { path: '/api/v2/tables/[tableId]/exports/[exportId]', pathParams: ['tableId', 'exportId'] as const, pathParamDocs: { - tableId: 'Unique table identifier.', + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', exportId: 'Unique table-export identifier.', }, responseMode: 'json', @@ -21012,7 +21023,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/cancel-runs', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Cancel column runs', body: { @@ -22108,7 +22122,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/dispatches', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Create run dispatch', body: { @@ -22138,7 +22155,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/exports', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Create table export', body: { @@ -22217,7 +22237,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/rows', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Create rows', body: { @@ -22229,7 +22252,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/views', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Create view', body: { @@ -22753,7 +22779,10 @@ export const V2_OPERATIONS = { method: 'DELETE', path: '/api/v2/tables/[tableId]', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Delete table', query: { @@ -22764,7 +22793,10 @@ export const V2_OPERATIONS = { method: 'DELETE', path: '/api/v2/tables/[tableId]/columns', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Delete column', body: { @@ -22807,7 +22839,11 @@ export const V2_OPERATIONS = { method: 'DELETE', path: '/api/v2/tables/[tableId]/rows/[rowId]', pathParams: ['tableId', 'rowId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.', rowId: 'Unique table row identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + rowId: 'Unique table row identifier.', + }, responseMode: 'json', summary: 'Delete row', query: { @@ -22818,7 +22854,10 @@ export const V2_OPERATIONS = { method: 'DELETE', path: '/api/v2/tables/[tableId]/rows', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Delete rows', body: { @@ -22836,7 +22875,11 @@ export const V2_OPERATIONS = { method: 'DELETE', path: '/api/v2/tables/[tableId]/views/[viewId]', pathParams: ['tableId', 'viewId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.', viewId: 'Unique saved-view identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + viewId: 'Unique saved-view identifier.', + }, responseMode: 'json', summary: 'Delete view', query: { @@ -22895,7 +22938,10 @@ export const V2_OPERATIONS = { method: 'DELETE', path: '/api/v2/tables/[tableId]/groups', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Delete workflow group', body: { @@ -23997,7 +24043,8 @@ export const V2_OPERATIONS = { path: '/api/v2/tables/[tableId]/rows/[rowId]/enrichment/[groupId]', pathParams: ['tableId', 'rowId', 'groupId'] as const, pathParamDocs: { - tableId: 'Unique table identifier.', + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', rowId: 'Unique table row identifier.', groupId: 'Workflow or enrichment group to run.', }, @@ -24278,7 +24325,10 @@ export const V2_OPERATIONS = { method: 'GET', path: '/api/v2/tables/[tableId]', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Get table', query: { @@ -24290,7 +24340,8 @@ export const V2_OPERATIONS = { path: '/api/v2/tables/[tableId]/dispatches/[dispatchId]', pathParams: ['tableId', 'dispatchId'] as const, pathParamDocs: { - tableId: 'Unique table identifier.', + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', dispatchId: 'Unique table run-dispatch identifier.', }, responseMode: 'json', @@ -24308,7 +24359,8 @@ export const V2_OPERATIONS = { path: '/api/v2/tables/[tableId]/exports/[exportId]', pathParams: ['tableId', 'exportId'] as const, pathParamDocs: { - tableId: 'Unique table identifier.', + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', exportId: 'Unique table-export identifier.', }, responseMode: 'json', @@ -24346,7 +24398,11 @@ export const V2_OPERATIONS = { method: 'GET', path: '/api/v2/tables/[tableId]/rows/[rowId]', pathParams: ['tableId', 'rowId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.', rowId: 'Unique table row identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + rowId: 'Unique table row identifier.', + }, responseMode: 'json', summary: 'Get row', query: { @@ -24362,7 +24418,11 @@ export const V2_OPERATIONS = { method: 'GET', path: '/api/v2/tables/[tableId]/views/[viewId]', pathParams: ['tableId', 'viewId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.', viewId: 'Unique saved-view identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + viewId: 'Unique saved-view identifier.', + }, responseMode: 'json', summary: 'Get view', query: { @@ -26857,7 +26917,10 @@ export const V2_OPERATIONS = { method: 'GET', path: '/api/v2/tables/[tableId]/dispatches', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'List run dispatches', query: { @@ -26904,7 +26967,10 @@ export const V2_OPERATIONS = { method: 'GET', path: '/api/v2/tables/[tableId]/rows', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'List rows', query: { @@ -26986,7 +27052,10 @@ export const V2_OPERATIONS = { method: 'GET', path: '/api/v2/tables/[tableId]/views', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'List views', query: { @@ -27086,7 +27155,10 @@ export const V2_OPERATIONS = { method: 'GET', path: '/api/v2/tables/[tableId]/groups', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'List workflow groups', query: { @@ -27945,7 +28017,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/query', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Query rows', body: { @@ -27975,7 +28050,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/query/count', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Count rows', body: { @@ -28517,7 +28595,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/restore', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Restore table', body: { @@ -28699,7 +28780,8 @@ export const V2_OPERATIONS = { path: '/api/v2/tables/[tableId]/rows/[rowId]/enrichment/[groupId]', pathParams: ['tableId', 'rowId', 'groupId'] as const, pathParamDocs: { - tableId: 'Unique table identifier.', + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', rowId: 'Unique table row identifier.', groupId: 'Workflow or enrichment group to run.', }, @@ -29155,7 +29237,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/rows/search', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Search rows', body: { @@ -29258,7 +29343,8 @@ export const V2_OPERATIONS = { path: '/api/v2/tables/[tableId]/exports/[exportId]/download', pathParams: ['tableId', 'exportId'] as const, pathParamDocs: { - tableId: 'Unique table identifier.', + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', exportId: 'Unique table-export identifier.', }, responseMode: 'json', @@ -29875,7 +29961,10 @@ export const V2_OPERATIONS = { method: 'PATCH', path: '/api/v2/tables/[tableId]/rows', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Update rows by filter', body: { @@ -30002,7 +30091,10 @@ export const V2_OPERATIONS = { method: 'PATCH', path: '/api/v2/tables/[tableId]', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Update table', body: { @@ -30023,7 +30115,10 @@ export const V2_OPERATIONS = { method: 'PATCH', path: '/api/v2/tables/[tableId]/columns', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Update column', body: { @@ -30040,7 +30135,11 @@ export const V2_OPERATIONS = { method: 'PATCH', path: '/api/v2/tables/[tableId]/rows/[rowId]', pathParams: ['tableId', 'rowId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.', rowId: 'Unique table row identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + rowId: 'Unique table row identifier.', + }, responseMode: 'json', summary: 'Update row', body: { @@ -30056,7 +30155,11 @@ export const V2_OPERATIONS = { method: 'PATCH', path: '/api/v2/tables/[tableId]/views/[viewId]', pathParams: ['tableId', 'viewId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.', viewId: 'Unique saved-view identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + viewId: 'Unique saved-view identifier.', + }, responseMode: 'json', summary: 'Update view', body: { @@ -30096,7 +30199,10 @@ export const V2_OPERATIONS = { method: 'PATCH', path: '/api/v2/tables/[tableId]/groups', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Update workflow group', body: { @@ -30364,7 +30470,10 @@ export const V2_OPERATIONS = { method: 'POST', path: '/api/v2/tables/[tableId]/rows/upsert', pathParams: ['tableId'] as const, - pathParamDocs: { tableId: 'Unique table identifier.' }, + pathParamDocs: { + tableId: + 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + }, responseMode: 'json', summary: 'Upsert row', body: { From 24166522936ced9f219201d849752e41ba0fb604 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:27:07 -0800 Subject: [PATCH 29/85] improvement(workflow-code): block meta written among a block's params is pointed at the third argument --- packages/workflow-code/src/compile/blocks.ts | 15 ++++++++++++++- .../workflow-code/src/compile/ergonomics.test.ts | 10 ++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 4bb0b2d8805..3907e243d38 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -208,6 +208,17 @@ function registerList( for (const [key, property] of entries) addItem(property, anchorOf(key)) } +/** + * The block meta keys an author most often writes among the params by mistake, each with the call + * that places it: the meta object is a builder's third argument, beside the params. + */ +const BLOCK_META_HINTS: Readonly> = { + retry: "agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })", + disabled: "agent('Name', {…}, { disabled: true })", + locked: "agent('Name', {…}, { locked: true })", + errorPort: "agent('Name', {…}, { errorPort: true })", +} + /** `meta`: block-level fields, in the printer's vocabulary. */ function compileMeta(ctx: CompileContext, node: Node | undefined, site: ValueSite): CompiledMeta { const meta: CompiledMeta = { @@ -1140,7 +1151,9 @@ function compileWrittenParams( { hint: alias ? `Write it as ${alias}; the value kind picks the basic or advanced field.` - : didYouMean(key, index.fields.keys()), + : Object.hasOwn(BLOCK_META_HINTS, key) + ? `${key} is block meta, not a param: pass it in the third argument, ${BLOCK_META_HINTS[key]}.` + : didYouMean(key, index.fields.keys()), blockKey: decl.key, param: key, } diff --git a/packages/workflow-code/src/compile/ergonomics.test.ts b/packages/workflow-code/src/compile/ergonomics.test.ts index cf89e3c1ba8..129cb7fb1a8 100644 --- a/packages/workflow-code/src/compile/ergonomics.test.ts +++ b/packages/workflow-code/src/compile/ergonomics.test.ts @@ -68,6 +68,16 @@ describe('param aliases', () => { const unknown = result.diagnostics.find((d) => d.code === 'E_UNKNOWN_PARAM') expect(unknown?.hint).toMatch(/^Write it as credential;/) }) + + it('points block meta written among the params at the third argument', () => { + const result = run( + source(" mail.send('M', { to: 'a@b.c', retry: { enabled: true, maxTries: 3 } })") + ) + const unknown = result.diagnostics.find((d) => d.code === 'E_UNKNOWN_PARAM') + expect(unknown?.hint).toMatch( + /^retry is block meta, not a param: pass it in the third argument/ + ) + }) }) describe('stored()', () => { From 62361fa10b936c3aa8e751ab6334488b32ba1698 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:28:59 -0800 Subject: [PATCH 30/85] improvement(workflows): two variables renamed in one apply are refused with a hint to rename them one at a time --- .../apply-workflow-source.integration.ts | 28 +++++++++++++++++++ .../source-pipeline/evaluate/refusals.ts | 8 ++++-- packages/workflow-code/src/compile/SYNTAX.md | 2 +- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts index 4fd3ba74049..17cff30564f 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -3250,6 +3250,34 @@ describe('workflow variables in source', () => { } ) + check( + 'two variables renamed in one apply are refused with a hint to rename them one apply at a time', + async () => { + const seeded = await seedWorkflow() + const first = await getSource(seeded.workflowId) + const added = await apply( + first, + withVariables( + first.files, + "{ threshold: { type: 'number', value: 3 }, limit: { type: 'string', value: 'x' } }" + ) + ) + expect(added.applied).toBe(true) + const source = await getSource(seeded.workflowId) + const entry = source.files['workflow.ts'] + const renamed = entry.replace('threshold:', 'ceiling:').replace('limit:', 'cap:') + expect(renamed, 'the source declares both variables').not.toBe(entry) + + const error = await expectRejected( + apply(source, { ...source.files, 'workflow.ts': renamed }), + 'E_APPLY_VARIABLE_DELETE' + ) + expect(error.diagnostics.find((d) => d.code === 'E_APPLY_VARIABLE_DELETE')?.hint).toMatch( + /rename them one apply at a time/ + ) + } + ) + check('deleting a variable is refused without allowDelete, like deleting a block', async () => { const seeded = await seedWorkflow() const source = await getSource(seeded.workflowId) diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/refusals.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/refusals.ts index 3cfa38064d1..e0873fe2c43 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/refusals.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/refusals.ts @@ -82,7 +82,9 @@ interface NamedVariable { /** * `E_APPLY_VARIABLE_DELETE` for the stored variables an apply removes, by name. When it removes * one and adds one of the same type, the edit may be a rename the apply could not tie to the - * stored variable (its value changed too, or says nothing), so the hint says how to keep the id. + * stored variable (its value changed too, or says nothing), so the hint says how to keep the id; + * when it removes several and adds any, they may be renames made together, which the apply never + * ties, so the hint says to make them one apply at a time. */ function variableDeleteRefusal( removed: readonly NamedVariable[], @@ -95,7 +97,9 @@ function variableDeleteRefusal( const rename = removed.length === 1 && added.length === 1 && former.type === next.type ? `If ${next.name} renames ${former.name}, keep the value ${former.name} holds and move every vars reference to the new key in this apply, then change the value in a second apply, so the variable keeps its id; a variable no block reads that holds 0, false or an empty value cannot be tied, so pass --allow-delete (allowDelete=true) to replace it.` - : undefined + : removed.length > 1 && added.length > 0 + ? `If these are renames, an apply ties only one renamed variable to its stored one: rename them one apply at a time (${listNames(names)}), so each keeps its id. Or pass --allow-delete (allowDelete=true) to delete them and create the new ones.` + : undefined return diagnostic( 'E_APPLY_VARIABLE_DELETE', `This apply deletes ${names.length} variable${names.length === 1 ? '' : 's'} the source no longer declares: ${listNames(names)}.`, diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index bd7d10e9b38..df584b1c3be 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -424,7 +424,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `W_EDGE_CYCLE` | A cycle the stored workflow already holds, kept so it round-trips; none of it runs. An offline check reports it for a cycle among blocks the lock binds, which an apply keeps only if the stored workflow holds every edge of it. | | `W_BRANCH_UNWIRED` | A condition or router branch no edge leaves, so a run that takes it ends there; the hint names the wiring. Not reported for a branch the stored workflow already leaves unwired. | | `E_UNKNOWN_BUILDER` | A builder path the catalog does not have, a bare builder-shaped call (`apii('Name', …)`) nothing binds, or a namespace the SDK lacks or the file did not import; `hint` names the builder a common other name stands for (`http.request` → `api`), then prefers a synonymous verb (`postMessage` → `sendMessage`), then the closest path, then the namespace's builders. | -| `E_UNKNOWN_PARAM` | A param the block does not have; the hint has a did-you-mean. | +| `E_UNKNOWN_PARAM` | A param the block does not have; the hint has a did-you-mean, or for block meta written there (`retry`, `disabled`, `locked`, `errorPort`) the third argument that takes it. | | `E_FIXED_PARAM` | A param the builder already pins. | | `W_FIELD_NOT_APPLICABLE` | A param not visible under the block's values; apply keeps the stored value and the written-back source drops it. | | `W_REQUIRED_MISSING` | A required field left empty, including `todo()`; not repeated for a field an `E_UNKNOWN_PARAM` did-you-mean names, or one written with a value that failed to compile. | From 03ba3bd06e2c9f97400ee91a6600bcf9074915a0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:29:20 -0800 Subject: [PATCH 31/85] fix(workspace-source): staged blobs count against the payer's storage quota, and only staging renews them A lookup (blobs/missing) or a plan renewed every staged blob it found, so a daily request kept up to the per-caller cap stored forever, and nothing counted it against storage. Lookups and plans now only read. Sending a blob's bytes renews it, and blobs/missing lists one that expires within the hour, so the client stages it again before applying. Staging also checks the payer's storage quota: what the payer stores, plus bytes staged in any of its workspaces, plus the new bytes, under a per-payer lock. --- .../platform/self-hosting/background-jobs.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 4 +- .../contracts/v2/openapi/workspace-source.ts | 4 +- apps/sim/lib/billing/storage/limits.ts | 23 ++-- .../application/files.integration.ts | 22 +++ .../application/stage-blobs.ts | 18 ++- .../application/staging.integration.ts | 64 ++++++++- .../sim/lib/workspace-source/staging/store.ts | 130 ++++++++++++++---- .../protocol/workspace-source-apply.test.ts | 2 +- 9 files changed, 223 insertions(+), 46 deletions(-) diff --git a/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx b/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx index 909f1908f46..bea471f0a56 100644 --- a/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx +++ b/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx @@ -182,7 +182,7 @@ Create a workflow with a Schedule trigger set to every minute, deploy it, and wa | Table row TTL cleanup | `/api/cron/cleanup-table-row-ttl` | `*/15 * * * *` | Deletes table rows whose TTL column has expired | | Stale execution cleanup | `/api/cron/cleanup-stale-executions` | `*/30 * * * *` | Fails runs whose worker died without finishing — workflow executions, background jobs, table jobs and table runs — so they stop showing as running | | OAuth token cleanup | `/api/cron/cleanup-oauth-tokens` | `0 * * * *` | Deletes access and refresh tokens after the retention tail | -| Workspace source staging cleanup | `/api/cron/cleanup-source-staging` | `30 * * * *` | Deletes binary files staged for a workspace source apply a day after their last use | +| Workspace source staging cleanup | `/api/cron/cleanup-source-staging` | `30 * * * *` | Deletes binary files staged for a workspace source apply a day after they were last staged | | SCIM reconciliation | `/api/cron/scim-reconcile` | `17 * * * *` | Re-applies directory group mappings | | Data drains | `/api/cron/run-data-drains` | `0 * * * *` | Enterprise data drains | | Renew subscriptions | `/api/cron/renew-subscriptions` | `0 */12 * * *` | Renews Microsoft Teams chat subscriptions (Graph caps them at ~3 days) | diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 785097e19cd..94c004c260c 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -9225,7 +9225,7 @@ "post": { "operationId": "findMissingWorkspaceSourceBlobs", "summary": "Find missing workspace source blobs", - "description": "List which binary files of a workspace source directory the caller has not staged in this workspace, by SHA-256, so a client stages only those; an interrupted upload resumes without resending what is already staged. The staged ones are renewed: staged bytes expire a day after they were last staged, checked for, or planned with. Staging is per caller (a person, or one workspace API key). Requires workspace write access. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:write`.", + "description": "List which binary files of a workspace source directory the caller has not staged in this workspace, by SHA-256, so a client stages only those; an interrupted upload resumes without resending what is already staged. Asking renews nothing: staged bytes expire a day after they were last staged, and one that expires within the hour is listed as missing, so the client stages it again before applying. Staging is per caller (a person, or one workspace API key). Requires workspace write access. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:write`.", "x-sim-operation": "workspaces.source.blobs.missing", "x-oauth-scope": "api:write", "tags": ["Workflows"], @@ -9350,7 +9350,7 @@ "post": { "operationId": "stageWorkspaceSourceBlobs", "summary": "Stage workspace source blobs", - "description": "Stage the bytes of binary files (workspace files, knowledge documents) for a workspace source apply, as multipart form data: one file part per blob, its field name the SHA-256 of its bytes. At most 1000 files and 8000000 bytes per request, 10000000 bytes per file; a larger file goes in a request of its own. A body over 10001024 bytes answers `413` (`PAYLOAD_TOO_LARGE`) before it is read. A part whose bytes hash to another SHA-256 refuses the whole request (`400`), nothing staged. Staged files are scoped to the workspace and the caller, capped at 20000 files and 4000000000 bytes (`413` with `details.code` `SOURCE_STAGING_FULL` past either), and expire a day after their last use (staged, asked for, or applied); an apply does not remove them, so applying the same bytes again uploads nothing. Staging the same bytes again only renews them. Requires workspace write access. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:write`.", + "description": "Stage the bytes of binary files (workspace files, knowledge documents) for a workspace source apply, as multipart form data: one file part per blob, its field name the SHA-256 of its bytes. At most 1000 files and 8000000 bytes per request, 10000000 bytes per file; a larger file goes in a request of its own. A body over 10001024 bytes answers `413` (`PAYLOAD_TOO_LARGE`) before it is read. A part whose bytes hash to another SHA-256 refuses the whole request (`400`), nothing staged. Staged files are scoped to the workspace and the caller, capped at 20000 files and 4000000000 bytes (`413` with `details.code` `SOURCE_STAGING_FULL` past either), count against the workspace payer's storage quota while held (`413` with `SOURCE_STAGING_FULL` past it), and expire a day after they were last staged; asking for them or applying with them never renews them, and an apply does not remove them. Staging the same bytes again only renews them. Requires workspace write access. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:write`.", "x-sim-operation": "workspaces.source.blobs.stage", "x-oauth-scope": "api:write", "tags": ["Workflows"], diff --git a/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts b/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts index 796a7bf60ea..076511bb7c2 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts @@ -210,7 +210,7 @@ export const workspaceSourceOpenApiRoutes = [ applicationOperation: workspaceSourceOperations.findMissingBlobs, operationId: 'findMissingWorkspaceSourceBlobs', summary: 'Find missing workspace source blobs', - description: `List which binary files of a workspace source directory the caller has not staged in this workspace, by SHA-256, so a client stages only those; an interrupted upload resumes without resending what is already staged. The staged ones are renewed: staged bytes expire a day after they were last staged, checked for, or planned with. Staging is per caller (a person, or one workspace API key). Requires workspace write access. Returns \`403\` while workflows as code is not enabled.`, + description: `List which binary files of a workspace source directory the caller has not staged in this workspace, by SHA-256, so a client stages only those; an interrupted upload resumes without resending what is already staged. Asking renews nothing: staged bytes expire a day after they were last staged, and one that expires within the hour is listed as missing, so the client stages it again before applying. Staging is per caller (a person, or one workspace API key). Requires workspace write access. Returns \`403\` while workflows as code is not enabled.`, tags: ['Workflows'], errors: [...RESOURCE_MUTATION_ERRORS, 'PayloadTooLarge'], success: { description: 'The binary files still to stage.', headers: RATE_LIMIT_HEADERS }, @@ -250,7 +250,7 @@ export const workspaceSourceOpenApiRoutes = [ applicationOperation: workspaceSourceOperations.stageBlobs, operationId: 'stageWorkspaceSourceBlobs', summary: 'Stage workspace source blobs', - description: `Stage the bytes of binary files (workspace files, knowledge documents) for a workspace source apply, as multipart form data: one file part per blob, its field name the SHA-256 of its bytes. At most ${WORKSPACE_SOURCE_LIMITS.maxBlobsPerRequest} files and ${WORKSPACE_SOURCE_LIMITS.maxBlobBytesPerRequest} bytes per request, ${WORKSPACE_SOURCE_LIMITS.maxBlobBytes} bytes per file; a larger file goes in a request of its own. A body over ${WORKSPACE_SOURCE_STAGE_MAX_BYTES} bytes answers \`413\` (\`PAYLOAD_TOO_LARGE\`) before it is read. A part whose bytes hash to another SHA-256 refuses the whole request (\`400\`), nothing staged. Staged files are scoped to the workspace and the caller, capped at ${WORKSPACE_SOURCE_LIMITS.maxStagedBlobs} files and ${WORKSPACE_SOURCE_LIMITS.maxStagedBytes} bytes (\`413\` with \`details.code\` \`SOURCE_STAGING_FULL\` past either), and expire a day after their last use (staged, asked for, or applied); an apply does not remove them, so applying the same bytes again uploads nothing. Staging the same bytes again only renews them. Requires workspace write access. Returns \`403\` while workflows as code is not enabled.`, + description: `Stage the bytes of binary files (workspace files, knowledge documents) for a workspace source apply, as multipart form data: one file part per blob, its field name the SHA-256 of its bytes. At most ${WORKSPACE_SOURCE_LIMITS.maxBlobsPerRequest} files and ${WORKSPACE_SOURCE_LIMITS.maxBlobBytesPerRequest} bytes per request, ${WORKSPACE_SOURCE_LIMITS.maxBlobBytes} bytes per file; a larger file goes in a request of its own. A body over ${WORKSPACE_SOURCE_STAGE_MAX_BYTES} bytes answers \`413\` (\`PAYLOAD_TOO_LARGE\`) before it is read. A part whose bytes hash to another SHA-256 refuses the whole request (\`400\`), nothing staged. Staged files are scoped to the workspace and the caller, capped at ${WORKSPACE_SOURCE_LIMITS.maxStagedBlobs} files and ${WORKSPACE_SOURCE_LIMITS.maxStagedBytes} bytes (\`413\` with \`details.code\` \`SOURCE_STAGING_FULL\` past either), count against the workspace payer's storage quota while held (\`413\` with \`SOURCE_STAGING_FULL\` past it), and expire a day after they were last staged; asking for them or applying with them never renews them, and an apply does not remove them. Staging the same bytes again only renews them. Requires workspace write access. Returns \`403\` while workflows as code is not enabled.`, tags: ['Workflows'], errors: [...RESOURCE_MUTATION_ERRORS, 'PayloadTooLarge'], success: { description: 'The binary files staged.', headers: RATE_LIMIT_HEADERS }, diff --git a/apps/sim/lib/billing/storage/limits.ts b/apps/sim/lib/billing/storage/limits.ts index d3f5433d7cb..2218be61434 100644 --- a/apps/sim/lib/billing/storage/limits.ts +++ b/apps/sim/lib/billing/storage/limits.ts @@ -22,6 +22,7 @@ import { getLegacyStorageBillingEntity } from '@/lib/billing/storage/entity' import { getEnv } from '@/lib/core/config/env' import { isBillingEnabled } from '@/lib/core/config/env-flags' import { OrchestrationError } from '@/lib/core/orchestration/types' +import type { DbOrTx } from '@/lib/db/types' const logger = createLogger('StorageLimits') @@ -253,9 +254,12 @@ export async function getUserStorageLimit( /** * Reads one user or organization storage counter. */ -async function readStorageUsageForEntity(billingEntity: Readonly): Promise { +async function readStorageUsageForEntity( + billingEntity: Readonly, + executor: DbOrTx = db +): Promise { if (billingEntity.type === 'organization') { - const [record] = await db + const [record] = await executor .select({ storageUsedBytes: organization.storageUsedBytes }) .from(organization) .where(eq(organization.id, billingEntity.id)) @@ -263,7 +267,7 @@ async function readStorageUsageForEntity(billingEntity: Readonly) return record?.storageUsedBytes ?? 0 } - const [record] = await db + const [record] = await executor .select({ storageUsedBytes: userStats.storageUsedBytes }) .from(userStats) .where(eq(userStats.userId, billingEntity.id)) @@ -320,10 +324,11 @@ async function resolveUserStorageQuota(userId: string): Promise { return { - currentUsage: await readStorageUsageForEntity(context.billingEntity), + currentUsage: await readStorageUsageForEntity(context.billingEntity, executor), limit: getStorageLimitForBillingContext(context), } } @@ -365,15 +370,17 @@ export async function checkStorageQuota( } /** - * Checks storage quota against a workspace-selected immutable payer. + * Checks storage quota against a workspace-selected immutable payer, reading its counter through + * `executor` (a caller's transaction, so the read joins it). */ export async function checkStorageQuotaForBillingContext( context: StoragePayerContext, - additionalBytes: number + additionalBytes: number, + executor: DbOrTx = db ): Promise { return checkStorageQuotaWithResolver( additionalBytes, - () => resolveBillingContextStorageQuota(context), + () => resolveBillingContextStorageQuota(context, executor), (error) => logger.error('Error checking workspace payer storage quota:', error) ) } diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index 90f98d7d107..abc65f62d1f 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -20,6 +20,7 @@ import { workspaceFiles, workspaceFileVersion, workspaceResourceKey, + workspaceSourceStagedBlob, } from '@sim/db/schema' import { sha256Hex } from '@sim/security/hash' import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' @@ -279,6 +280,27 @@ describe('workspace source files', () => { expect(read.base.resources).toEqual(created.base.resources) }) + check('a dry run plans with staged bytes and leaves their expiry as it was', async () => { + const workspaceId = await newWorkspace() + await stageBlobsAs( + owner, + workspaceId, + blobsOf(STARTER).map(({ sha256, content }) => ({ sha256, content: content ?? '' })) + ) + const soon = new Date(Date.now() + 30 * 60 * 1000) + const staged = eq(workspaceSourceStagedBlob.workspaceId, workspaceId) + await db.update(workspaceSourceStagedBlob).set({ expiresAt: soon }).where(staged) + + const dryRun = await apply(workspaceId, STARTER, { dryRun: true }) + + expect(dryRun.needBlobs).toEqual([]) + const expiries = await db + .select({ expiresAt: workspaceSourceStagedBlob.expiresAt }) + .from(workspaceSourceStagedBlob) + .where(staged) + expect(expiries.map((row) => row.expiresAt.getTime())).toEqual([soon.getTime(), soon.getTime()]) + }) + check('re-applying what a get read changes nothing and records no version', async () => { const workspaceId = await newWorkspace() const read = await setUp(workspaceId) diff --git a/apps/sim/lib/workspace-source/application/stage-blobs.ts b/apps/sim/lib/workspace-source/application/stage-blobs.ts index f2dcc4e877a..433c209460c 100644 --- a/apps/sim/lib/workspace-source/application/stage-blobs.ts +++ b/apps/sim/lib/workspace-source/application/stage-blobs.ts @@ -2,8 +2,9 @@ * Staging the binary files of a workspace source apply: a client uploads each blob's bytes first, * keyed by SHA-256, then sends one apply that names them by hash. Staged blobs are scoped to the * workspace and the caller (a person, or a workspace API key), capped per scope - * (`maxStagedBlobs`, `maxStagedBytes`) and expire a day after they were last used. A client asks - * which hashes are missing before uploading, so a resumed apply never sends a blob twice. + * (`maxStagedBlobs`, `maxStagedBytes`), count against the workspace payer's storage quota while + * held, and expire a day after they were last staged. A client asks which hashes are missing + * before uploading, so a resumed apply never sends a blob twice. */ import type { Principal } from '@sim/auth/principal' import { sha256Hex } from '@sim/security/hash' @@ -14,6 +15,7 @@ import { workspaceSourceOperations } from '@/lib/workspace-source/application/op import { assertStagingFits, findStagedBlobs, + STAGED_BLOB_RESTAGE_MARGIN_MS, type StagingScope, stageBlobs, stagedUsage, @@ -72,7 +74,8 @@ export interface StageSourceBlobsResult { * Stages a batch of blobs: refuses one over `maxBlobBytes`, a batch over the request caps (a single * blob may fill its request alone), and any * blob whose bytes do not hash to the SHA-256 it was named by (nothing of the batch is staged), - * then stores the rest within the scope's caps. Staging a blob already staged only renews it. + * then stores the rest within the scope's caps and the payer's storage quota. Staging a blob already + * staged only renews it. */ export const stageSourceBlobs = defineAuthorizedWorkspaceUseCase({ operation: workspaceSourceOperations.stageBlobs, @@ -129,8 +132,10 @@ export interface FindMissingSourceBlobsInput { } /** - * Which of `blobs` the caller has not staged in the workspace (or staged at another size), in the - * order asked; those it has are renewed, so they outlive the apply that follows. + * Which of `blobs` the caller has not staged in the workspace (or staged at another size, or + * staged but expiring within {@link STAGED_BLOB_RESTAGE_MARGIN_MS}), in the order asked. A read: + * asking never renews a staged blob, so one about to expire is reported missing, and staging its + * bytes again renews it before the apply that follows. */ export const findMissingSourceBlobs = defineAuthorizedWorkspaceUseCase({ operation: workspaceSourceOperations.findMissingBlobs, @@ -146,7 +151,8 @@ export const findMissingSourceBlobs = defineAuthorizedWorkspaceUseCase({ } const staged = await findStagedBlobs( stagingScopeOf(principal, context.workspaceId), - input.blobs.map((blob) => blob.sha256) + input.blobs.map((blob) => blob.sha256), + new Date(Date.now() + STAGED_BLOB_RESTAGE_MARGIN_MS) ) const missing = [ ...new Set( diff --git a/apps/sim/lib/workspace-source/application/staging.integration.ts b/apps/sim/lib/workspace-source/application/staging.integration.ts index 1fd331b9802..0ca806ea8a8 100644 --- a/apps/sim/lib/workspace-source/application/staging.integration.ts +++ b/apps/sim/lib/workspace-source/application/staging.integration.ts @@ -11,7 +11,7 @@ import { tmpdir } from 'node:os' import path from 'node:path' import type { Principal } from '@sim/auth/principal' import { db } from '@sim/db' -import { user, workspaceSourceStagedBlob } from '@sim/db/schema' +import { user, userStats, workspaceSourceStagedBlob } from '@sim/db/schema' import { sha256Hex } from '@sim/security/hash' import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/feature-flags.mock' @@ -50,6 +50,9 @@ const readerId = generateId() const owner = createSessionPrincipal({ userId: ownerId, sessionId: generateId() }) const writer = createSessionPrincipal({ userId: writerId, sessionId: generateId() }) const reader = createSessionPrincipal({ userId: readerId, sessionId: generateId() }) +/** A payer of its own, so no other check's staged bytes count toward its storage quota. */ +const payerId = generateId() +const payer = createSessionPrincipal({ userId: payerId, sessionId: generateId() }) const { check, writeReport } = sourceChecks( 'WORKSPACE_SOURCE_STAGING_REPORT_PATH', 'workspace-source-staging.json' @@ -140,7 +143,7 @@ beforeAll(async () => { ) const now = new Date() await db.insert(user).values( - [ownerId, writerId, readerId].map((id) => ({ + [ownerId, writerId, readerId, payerId].map((id) => ({ id, name: 'Workspace source staging fixture', email: `${id}@workspace-source.invalid`, @@ -155,7 +158,7 @@ afterAll(async () => { await writeReport() resetUploadsSetupMock() await workspaces.cleanup() - await db.delete(user).where(inArray(user.id, [ownerId, writerId, readerId])) + await db.delete(user).where(inArray(user.id, [ownerId, writerId, readerId, payerId])) await rm(storageRoot, { recursive: true, force: true }) }) @@ -179,6 +182,61 @@ describe('workspace source staging', () => { } ) + check( + 'asking what is missing never renews a staged blob: one about to expire reads as missing until its bytes are staged again', + async () => { + const workspaceId = await newWorkspace() + const a = blob('expiring alpha') + await stage(owner, workspaceId, [a]) + const soon = new Date(Date.now() + 30 * 60 * 1000) + await db + .update(workspaceSourceStagedBlob) + .set({ expiresAt: soon }) + .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) + const expiryOf = async () => + ( + await db + .select({ expiresAt: workspaceSourceStagedBlob.expiresAt }) + .from(workspaceSourceStagedBlob) + .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) + ).map((row) => row.expiresAt.getTime()) + + expect(await missing(owner, workspaceId, [a])).toEqual([a.sha256]) + expect(await expiryOf()).toEqual([soon.getTime()]) + + await stage(owner, workspaceId, [a]) + expect(await missing(owner, workspaceId, [a])).toEqual([]) + const [renewed] = await expiryOf() + expect(renewed).toBeGreaterThan(Date.now() + 23 * 60 * 60 * 1000) + expect(await rows(workspaceId)).toHaveLength(1) + } + ) + + check( + "staging counts against the payer's storage quota, across the payer's workspaces, on top of what it stores", + async () => { + const quota = 1024 ** 3 + await db + .insert(userStats) + .values({ id: generateId(), userId: payerId, storageUsedBytes: quota - 10 }) + const create = () => workspaces.create({ name: 'Staging quota', ownerId: payerId }) + const [first, second] = [await create(), await create()] + vi.stubEnv('FREE_STORAGE_LIMIT_GB', '1') + try { + await stage(payer, first, [blob('six b1')]) + const refused = await failure(stage(payer, second, [blob('six b2')])) + expect(refused).toMatchObject({ + code: 'payload_too_large', + name: 'SourceStagingFullError', + }) + expect(await rows(second)).toEqual([]) + expect(objectsUnder(second)).toEqual([]) + } finally { + vi.unstubAllEnvs() + } + } + ) + check('bytes that do not hash to their name refuse the whole batch, nothing stored', async () => { const workspaceId = await newWorkspace() const good = blob('good bytes') diff --git a/apps/sim/lib/workspace-source/staging/store.ts b/apps/sim/lib/workspace-source/staging/store.ts index 9e86bc55a30..9c99f0cdd8a 100644 --- a/apps/sim/lib/workspace-source/staging/store.ts +++ b/apps/sim/lib/workspace-source/staging/store.ts @@ -3,25 +3,41 @@ * their SHA-256 and scoped to one workspace and one caller, so an apply names them by hash and a * resumed upload skips what is already here. Rows (`workspace_source_staged_blob`) hold the hash, * size, storage key and expiry; the bytes live in object storage under the workspace's prefix. + * Only staging (sending the bytes) sets the expiry: looking blobs up or planning with them never + * extends it. While held, staged bytes count against the workspace payer's storage quota, on top + * of what the payer already stores, so staging can never hold more than the quota leaves. * Callers pass canonical ids and a scope string, never a principal: the use cases in * `application/stage-blobs.ts` authorize first. */ import { db } from '@sim/db' -import { workspaceSourceStagedBlob } from '@sim/db/schema' +import { workspace, workspaceSourceStagedBlob } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { sha256Hex } from '@sim/security/hash' import { generateId, generateShortId } from '@sim/utils/id' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' -import { and, asc, eq, gt, inArray, lt, lte, notInArray, sql } from 'drizzle-orm' +import { and, asc, eq, gt, inArray, isNull, lt, lte, notInArray, sql } from 'drizzle-orm' +import type { BillingEntity } from '@/lib/billing/core/usage-log' +import { resolveStorageBillingContext } from '@/lib/billing/storage/context' +import { + checkStorageQuotaForBillingContext, + isStorageEnforcementEnabled, +} from '@/lib/billing/storage/limits' import { OrchestrationError } from '@/lib/core/orchestration/types' import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' +import type { DbTransaction } from '@/lib/db/types' import { deleteFiles, downloadFile, uploadFile } from '@/lib/uploads/core/storage-service' const logger = createLogger('WorkspaceSourceStaging') -/** How long a staged blob is kept after it was last staged, checked for, or planned with. */ +/** How long a staged blob is kept after it was last staged. */ const STAGED_BLOB_TTL_MS = 24 * 60 * 60 * 1000 +/** + * A staged blob that expires sooner than this reads as missing to a client asking what to stage, + * so it sends the bytes again (renewing it) rather than applying with one about to go. + */ +export const STAGED_BLOB_RESTAGE_MARGIN_MS = 60 * 60 * 1000 + /** Rows one sweep pass deletes. */ const SWEEP_BATCH = 500 @@ -57,30 +73,30 @@ const inScope = ({ workspaceId, scope }: StagingScope) => ) /** - * The staged blobs among `hashes` (unexpired), by hash; each one found has its expiry pushed out, - * so what a client just checked for or an apply just planned with outlives the apply. + * The staged blobs among `hashes` that are still staged `until` (default now), by hash, with when + * each expires. A read: it never extends an expiry. */ export async function findStagedBlobs( target: StagingScope, - hashes: readonly string[] + hashes: readonly string[], + until: Date = new Date() ): Promise> { const found = new Map() if (hashes.length === 0) return found const rows = await db - .update(workspaceSourceStagedBlob) - .set({ expiresAt: expiry() }) + .select({ + sha256: workspaceSourceStagedBlob.sha256, + size: workspaceSourceStagedBlob.size, + storageKey: workspaceSourceStagedBlob.storageKey, + }) + .from(workspaceSourceStagedBlob) .where( and( inScope(target), inArray(workspaceSourceStagedBlob.sha256, [...new Set(hashes)]), - gt(workspaceSourceStagedBlob.expiresAt, new Date()) + gt(workspaceSourceStagedBlob.expiresAt, until) ) ) - .returning({ - sha256: workspaceSourceStagedBlob.sha256, - size: workspaceSourceStagedBlob.size, - storageKey: workspaceSourceStagedBlob.storageKey, - }) for (const row of rows) found.set(row.sha256, row) return found } @@ -101,9 +117,62 @@ export async function stagedUsage( } /** - * A caller's staging area has no room for what it stages: `413` like a body over the limit, told - * apart by `details.code` `SOURCE_STAGING_FULL`, since freeing staged files (or waiting for them - * to expire) fixes it and sending smaller requests does not. + * The bytes staged (unexpired) in every workspace `payer` pays for, across callers: what staging + * holds against the payer's storage quota. + */ +async function payerStagedBytes(tx: DbTransaction, payer: BillingEntity): Promise { + const [usage] = await tx + .select({ + bytes: sql`coalesce(sum(${workspaceSourceStagedBlob.size}), 0)::bigint`, + }) + .from(workspaceSourceStagedBlob) + .innerJoin(workspace, eq(workspace.id, workspaceSourceStagedBlob.workspaceId)) + .where( + and( + gt(workspaceSourceStagedBlob.expiresAt, new Date()), + payer.type === 'organization' + ? eq(workspace.organizationId, payer.id) + : and(isNull(workspace.organizationId), eq(workspace.billedAccountUserId, payer.id)) + ) + ) + return Number(usage?.bytes ?? 0) +} + +/** + * Refuses staging `bytes` more in `workspaceId` when the bytes its payer stores, plus those staged + * in any of the payer's workspaces, plus these would pass the payer's storage quota. Holds the + * payer's staging lock until `tx` ends, so concurrent staging in another workspace of the same + * payer cannot pass the check together. + */ +async function assertStagingWithinQuota( + tx: DbTransaction, + workspaceId: string, + bytes: number +): Promise { + if (!isStorageEnforcementEnabled()) return + const billing = await resolveStorageBillingContext(workspaceId, tx) + const { type, id } = billing.billingEntity + await acquireAdvisoryXactLock( + tx, + 'workspace_source_staging', + `workspace-source-staging-payer:${type}:${id}` + ) + const quota = await checkStorageQuotaForBillingContext( + billing, + (await payerStagedBytes(tx, billing.billingEntity)) + bytes, + tx + ) + if (!quota.allowed) { + throw new SourceStagingFullError( + `${quota.error ?? 'Storage limit exceeded'}. Staged files count toward storage until they expire, a day after they were last staged.` + ) + } +} + +/** + * A caller's staging area, or the payer's storage quota, has no room for what it stages: `413` + * like a body over the limit, told apart by `details.code` `SOURCE_STAGING_FULL`, since freeing + * staged files (or waiting for them to expire) fixes it and sending smaller requests does not. */ export class SourceStagingFullError extends OrchestrationError { constructor(message: string) { @@ -120,20 +189,21 @@ export function assertStagingFits( const { maxStagedBlobs, maxStagedBytes } = WORKSPACE_SOURCE_LIMITS if (usage.count + adding.count > maxStagedBlobs) { throw new SourceStagingFullError( - `Staging ${adding.count} more binary files would hold ${usage.count + adding.count}, over the ${maxStagedBlobs}-file limit. Staged files expire a day after their last use.` + `Staging ${adding.count} more binary files would hold ${usage.count + adding.count}, over the ${maxStagedBlobs}-file limit. Staged files expire a day after they were last staged.` ) } if (usage.bytes + adding.bytes > maxStagedBytes) { throw new SourceStagingFullError( - `Staging ${adding.bytes} more bytes would hold ${usage.bytes + adding.bytes}, over the ${maxStagedBytes}-byte limit. Staged files expire a day after their last use.` + `Staging ${adding.bytes} more bytes would hold ${usage.bytes + adding.bytes}, over the ${maxStagedBytes}-byte limit. Staged files expire a day after they were last staged.` ) } } /** * Stages `blobs` (bytes the caller already hashed): writes each one not yet staged to storage, - * then records them under one lock on the scope, refusing a batch that would pass the caps (and - * removing the objects it wrote). A blob already staged only has its expiry pushed out. + * then records them under one lock on the scope, refusing a batch that would pass the caps or the + * payer's storage quota (and removing the objects it wrote). A blob already staged is not written + * again: sending its bytes renews it. */ export async function stageBlobs( target: StagingScope, @@ -165,11 +235,25 @@ export async function stageBlobs( 'workspace_source_staging', `workspace-source-staging:${target.workspaceId}:${target.scope}` ) + if (known.size > 0) { + await tx + .update(workspaceSourceStagedBlob) + .set({ expiresAt: expiry() }) + .where( + and( + inScope(target), + inArray(workspaceSourceStagedBlob.sha256, [...known.keys()]), + gt(workspaceSourceStagedBlob.expiresAt, new Date()) + ) + ) + } if (fresh.length === 0) return new Map() - assertStagingFits(await stagedUsage(target, tx), { + const adding = { count: fresh.length, bytes: fresh.reduce((sum, blob) => sum + blob.bytes.byteLength, 0), - }) + } + assertStagingFits(await stagedUsage(target, tx), adding) + await assertStagingWithinQuota(tx, target.workspaceId, adding.bytes) const hashes = fresh.map((blob) => blob.sha256) // An expired row of the same hash is replaced, so the unique index admits the new one. const expired = await tx diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index a054f034f21..d71a5f05b50 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1129,7 +1129,7 @@ describe('workspaces source apply', () => { it('keeps the server’s refusal of a staging area with no room, which no CLI update or proxy fixes', async () => { write('files/a.bin', Buffer.alloc(3_000, 1)) const full = - 'Staging 3000 more bytes would hold 2000000001, over the 2000000000-byte limit. Staged files expire a day after their last use.' + 'Staging 3000 more bytes would hold 2000000001, over the 2000000000-byte limit. Staged files expire a day after they were last staged.' mockRequest.mockImplementation(async (path: string, options: { body?: unknown }) => { if (path.endsWith('/source/blobs')) { throw new SimApiError(full, 413, 'PAYLOAD_TOO_LARGE', { code: 'SOURCE_STAGING_FULL' }) From 4d5832606a9b4198f20d2a801fe8f18f4b8c4300 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:11:22 -0800 Subject: [PATCH 32/85] fix(docs): close the API-samples loopback fixture's connections after each response A blocking spawnSync syntax check (csharp/java) holds the event loop past the node:http idle keep-alive timeout, so the server closes the pooled socket in the same tick Bun's fetch reuses it for the next JavaScript loopback check, which fails with ECONNRESET. Answering with Connection: close keeps no socket to reuse. --- apps/docs/scripts/verify-api-samples.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/docs/scripts/verify-api-samples.ts b/apps/docs/scripts/verify-api-samples.ts index 22075a2dae3..52aa6150e4b 100644 --- a/apps/docs/scripts/verify-api-samples.ts +++ b/apps/docs/scripts/verify-api-samples.ts @@ -120,6 +120,9 @@ const captured: Array<{ method?: string; url: string; body: string; contentType: const binary = new Uint8Array([0, 255, 254, 65, 128, 10]) const eventStream = 'data: {"ok":true}\n\n' const server = createServer(async (request, response) => { + // A `spawnSync` syntax check blocks the loop past the idle keep-alive timeout, so the server + // closes a pooled socket just as the next request reuses it: Bun's fetch then reports ECONNRESET. + response.setHeader('Connection', 'close') const chunks: Buffer[] = [] let bytes = 0 for await (const chunk of request) { From c8d0a807dc0a2a1a665a815aa6e1cb3663ebf6c4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:17:12 -0800 Subject: [PATCH 33/85] fix(files): wait on the outcome, not a 50ms sleep, in the superseded-key content tests Both tests slept a fixed 50ms and then asserted on the 404 handling (fetch, record refetch, surfaced error). On a loaded runner that chain takes longer than 50ms and the assertions run first. Poll for the outcome instead; with a 60ms delay injected into the fetch mock the old tests fail and these pass. --- apps/sim/hooks/queries/workspace-files.test.tsx | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/apps/sim/hooks/queries/workspace-files.test.tsx b/apps/sim/hooks/queries/workspace-files.test.tsx index 95bf6b293b4..9551852c5b9 100644 --- a/apps/sim/hooks/queries/workspace-files.test.tsx +++ b/apps/sim/hooks/queries/workspace-files.test.tsx @@ -15,7 +15,6 @@ import { apiClientRequestMock, apiClientRequestMockFns, } from '@sim/testing/mocks/api-client-request.mock' -import { sleep } from '@sim/utils/helpers' import { focusManager, QueryClient, QueryClientProvider } from '@tanstack/react-query' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -271,9 +270,7 @@ describe('useWorkspaceFileContent stale storage key', () => { const { queryClient, unmount } = renderContentHook() const refetchQueries = vi.spyOn(queryClient, 'refetchQueries') - await act(async () => { - await sleep(50) - }) + await vi.waitFor(() => expect(refetchQueries).toHaveBeenCalled()) expect(fetchCount).toBe(1) expect(refetchQueries).toHaveBeenCalledWith( @@ -368,11 +365,8 @@ describe('useWorkspaceFileContent while a superseded key is being re-resolved', }) ) const { getResult, resolveRecord, unmount } = renderDuringRecovery() - await act(async () => { - await sleep(50) - }) - - expect(getResult().error).not.toBeNull() + // The record re-resolve stays held open, so this error can only be the surfaced failure. + await vi.waitFor(() => expect(getResult().error).not.toBeNull()) resolveRecord() unmount() }) From a0f482cd749259e61928080d0f50a0c1fd522863 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:27:36 -0800 Subject: [PATCH 34/85] fix(extension): open a fresh connection for each API-context call in the extension e2e Both recorded browser-extension-access failures (runs 44886983219, 44016408354) hang up on the second access iteration's discovery GET exactly 6.0s after the previous API-context request, which is when Node 24's server destroys an idle keep-alive socket (keepAliveTimeout 5s plus keepAliveTimeoutBuffer 1s). The request never reaches a route handler. Send Connection: close so no fixture request reuses a pooled socket the server may be closing. --- .../sim/scripts/test-browser-extension-e2e.ts | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/apps/sim/scripts/test-browser-extension-e2e.ts b/apps/sim/scripts/test-browser-extension-e2e.ts index 44f22606838..86d2002b4e0 100644 --- a/apps/sim/scripts/test-browser-extension-e2e.ts +++ b/apps/sim/scripts/test-browser-extension-e2e.ts @@ -38,6 +38,12 @@ const logger = createLogger('BrowserExtensionAppE2E') const expect = browserExpect.configure({ timeout: 30_000 }) const ACCESS_REVALIDATION_TIMEOUT_MS = 35_000 const ACCESS_POLL_INTERVAL_MS = 30_000 +/** + * `next start` on Node 24 destroys a keep-alive socket idle for 6s (keepAliveTimeout plus its 1s + * buffer), and an API-context request reusing that socket as it closes hangs up (ECONNRESET), so + * every fixture call opens its own connection. + */ +const FRESH_CONNECTION = { Connection: 'close' } as const function required(name: string): string { const value = process.env[name] assert(value, `${name} must be explicitly provided`) @@ -538,7 +544,7 @@ try { }) const signInAndSeed = async () => { const signup = await browserContext.request.post(`${base.origin}/api/auth/sign-up/email`, { - headers: { origin: base.origin }, + headers: { ...FRESH_CONNECTION, origin: base.origin }, data: { name: 'Extension QA', email: `extension-${generateId()}@example.test`, @@ -1129,7 +1135,7 @@ try { for (const theme of ['light', 'dark'] as const) { const settings = await browserContext.request.patch( `${base.origin}/api/users/me/settings`, - { data: { theme } } + { headers: FRESH_CONNECTION, data: { theme } } ) assert.equal(settings.status(), 200) await navigate(`${base.origin}/extension/${alphaId}`) @@ -2181,7 +2187,7 @@ try { const active = await browserContext.request.post( `${base.origin}/api/auth/organization/set-active`, { - headers: { origin: base.origin }, + headers: { ...FRESH_CONNECTION, origin: base.origin }, data: { organizationId }, } ) @@ -2889,7 +2895,8 @@ try { await expect(attachments()).toHaveCount(1) await shell.bringToFront() const discovery = await browserContext.request.get( - `${base.origin}/api/access-requests/discovery?kind=workspace&workspaceId=${hostedWorkspaceId}&targetKind=feature` + `${base.origin}/api/access-requests/discovery?kind=workspace&workspaceId=${hostedWorkspaceId}&targetKind=feature`, + { headers: FRESH_CONNECTION } ) assert.equal(discovery.status(), 200) assert.equal(toRecord(await discovery.json()).enabled, allowRequests) @@ -2897,7 +2904,8 @@ try { values (${permissionGroupId}, ${otherOrganizationId}, 'Revoked Chat access', ${sql.json({ hideCopilot: true })}, ${otherUserId}, true)` const policy = await browserContext.request.get( - `${base.origin}/api/permission-groups/user?workspaceId=${hostedWorkspaceId}` + `${base.origin}/api/permission-groups/user?workspaceId=${hostedWorkspaceId}`, + { headers: FRESH_CONNECTION } ) assert.equal(policy.status(), 200) assert.equal(toRecord(toRecord(await policy.json()).config).hideCopilot, true) @@ -3338,7 +3346,7 @@ try { async () => { await capture() const response = await browserContext.request.post(`${base.origin}/api/auth/sign-out`, { - headers: { origin: base.origin }, + headers: { ...FRESH_CONNECTION, origin: base.origin }, data: {}, }) assert.equal(response.status(), 200) From f2e82fefeb6468cfd2d90a28052537527bb9efac Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:34:48 -0800 Subject: [PATCH 35/85] chore(sim-cli): simplify the DX changes: one lock reader, shared list and regex helpers, lazy GitHub output, resolved stop block only --- .../sim/lib/table/application/context.test.ts | 6 +++ apps/sim/lib/table/application/context.ts | 9 ++-- apps/sim/lib/table/ids.ts | 5 +- .../application/execute-manual-workflow.ts | 25 +++++----- .../src/commands/protocol/deployed-urls.ts | 30 +++++++----- .../commands/protocol/run-source-location.ts | 37 ++++++-------- .../src/commands/protocol/source-ui.ts | 31 ++++++------ .../protocol/workflow-source-apply.ts | 22 +++------ .../protocol/workflow-source-params.ts | 3 +- .../protocol/workspace-source-apply.ts | 49 ++++++++++--------- packages/sim-cli/src/output/github-actions.ts | 9 ++-- packages/workflow-code/src/compile/blocks.ts | 15 +----- .../src/compile/ergonomics.test.ts | 2 +- 13 files changed, 122 insertions(+), 121 deletions(-) diff --git a/apps/sim/lib/table/application/context.test.ts b/apps/sim/lib/table/application/context.test.ts index a4480ca680f..f5d3e484d31 100644 --- a/apps/sim/lib/table/application/context.test.ts +++ b/apps/sim/lib/table/application/context.test.ts @@ -91,6 +91,12 @@ describe('table application context', () => { await resolveActiveTableContext({ tableId: 'table-1', assertedWorkspaceId: 'workspace-1' }) expect(findByName).not.toHaveBeenCalled() + // A stale id is never read as a name, so it costs no second query. + await expect( + resolveActiveTableContext({ tableId: 'tbl_gone', assertedWorkspaceId: 'workspace-1' }) + ).rejects.toMatchObject({ code: 'not_found' }) + expect(findByName).not.toHaveBeenCalled() + // A name never reaches past the asserted workspace, and without one it is not looked up. await expect( resolveActiveTableContext({ tableId: 'leads', assertedWorkspaceId: 'workspace-2' }) diff --git a/apps/sim/lib/table/application/context.ts b/apps/sim/lib/table/application/context.ts index 1dadeb84400..441f58fbb2a 100644 --- a/apps/sim/lib/table/application/context.ts +++ b/apps/sim/lib/table/application/context.ts @@ -1,5 +1,6 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import type { TableAuthorizationContext } from '@/lib/table/application/authorization' +import { TABLE_ID_PREFIX } from '@/lib/table/ids' import { findActiveTablesByExactName, getTableById } from '@/lib/table/service' import type { TableDefinition } from '@/lib/table/types' import { loadActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' @@ -25,12 +26,14 @@ export async function resolveTableWorkspaceContext( * Shared by both resolvers below so the not-found concealment — a table outside the asserted * workspace is reported as missing, never as forbidden — is written once. Within an asserted * workspace a table is also found by its name (`sim tables rows list leads`), which is unique - * among the workspace's active tables; an id always wins, and a name never reaches past the - * asserted workspace. + * among the workspace's active tables; an id always wins, a reference shaped like an id is never + * read as a name (a stale id costs no second query), and a name never reaches past the asserted + * workspace. */ + async function requireTable(tableId: string, workspaceId: string | undefined) { let table = await getTableById(tableId) - if (!table && workspaceId !== undefined) { + if (!table && workspaceId !== undefined && !tableId.startsWith(TABLE_ID_PREFIX)) { const named = await findActiveTablesByExactName(workspaceId, tableId) if (named.length === 1) table = named[0] } diff --git a/apps/sim/lib/table/ids.ts b/apps/sim/lib/table/ids.ts index 85931337551..5eea789dff7 100644 --- a/apps/sim/lib/table/ids.ts +++ b/apps/sim/lib/table/ids.ts @@ -1,5 +1,8 @@ import { generateId } from '@sim/utils/id' +/** What every table id starts with: a reference that does not is no table id. */ +export const TABLE_ID_PREFIX = 'tbl_' + /** * Mints a fresh table id: `tbl_` plus a dash-stripped v4 UUID, the shape Tables have carried * since they shipped and the one the CLI and Copilot describe to users. Every path that @@ -7,5 +10,5 @@ import { generateId } from '@sim/utils/id' * a table's id never reveals which path made it. */ export function generateTableId(): string { - return `tbl_${generateId().replace(/-/g, '')}` + return `${TABLE_ID_PREFIX}${generateId().replace(/-/g, '')}` } diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.ts index bed58c59f47..bd69f895b17 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.ts @@ -1,4 +1,5 @@ import { requirePrincipalSubjectUserId, type WorkflowExecutionPrincipal } from '@sim/auth/principal' +import { formatQuotedNameList } from '@sim/utils/string' import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks' import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -60,13 +61,13 @@ type ManualWorkflowState = Awaited> /** At most this many block names are listed when a block selector matches none. */ const MAX_LISTED_BLOCKS = 25 -/** `name (id)` for each block of `ids`, at most {@link MAX_LISTED_BLOCKS} of them. */ -function listBlocks(state: ManualWorkflowState, ids: readonly string[]): string { - const shown = ids - .slice(0, MAX_LISTED_BLOCKS) - .map((id) => `"${state.blocks[id]?.name ?? id}" (${id})`) - const more = ids.length > MAX_LISTED_BLOCKS ? `, and ${ids.length - MAX_LISTED_BLOCKS} more` : '' - return `${shown.join(', ')}${more}` +/** `"name" (id)` for each block of `ids`, at most {@link MAX_LISTED_BLOCKS} of them. */ +function listBlocks(state: ManualWorkflowState, ids: string[]): string { + return formatQuotedNameList( + ids, + MAX_LISTED_BLOCKS, + (id) => `"${state.blocks[id]?.name ?? id}" (${id})` + ) } /** @@ -162,6 +163,8 @@ function executionServiceInput(params: { context: Awaited> input: ManualExecutionInput draftState: NormalizedWorkflowData + /** The resolved id of the block to stop after, never the caller's raw selector. */ + stopAfterBlockId: string | undefined }) { return { workflowId: params.context.workflowId, @@ -179,7 +182,7 @@ function executionServiceInput(params: { ), base64MaxBytes: params.input.base64MaxBytes, selectedOutputs: params.input.selectedOutputs, - stopAfterBlockId: params.input.stopAfterBlockId, + stopAfterBlockId: params.stopAfterBlockId, rateLimitCounter: 'sync' as const, requestedTimeoutSeconds: params.input.requestedTimeoutSeconds, abortSignal: params.input.abortSignal, @@ -243,8 +246,7 @@ export const executeManualWorkflowOperation = defineAuthorizedWorkflowUseCase({ } const result = await executeWorkflowService({ - ...executionServiceInput({ principal, context, input, draftState: state }), - stopAfterBlockId, + ...executionServiceInput({ principal, context, input, draftState: state, stopAfterBlockId }), input: executionInput, triggerBlockId: selected.triggerBlockId, }) @@ -269,8 +271,7 @@ export const executeManualWorkflowFromBlockOperation = defineAuthorizedWorkflowU } const result = await executeWorkflowService({ - ...executionServiceInput({ principal, context, input, draftState: state }), - stopAfterBlockId, + ...executionServiceInput({ principal, context, input, draftState: state, stopAfterBlockId }), input: input.input, runFromBlock: { startBlockId: blockId, diff --git a/packages/sim-cli/src/commands/protocol/deployed-urls.ts b/packages/sim-cli/src/commands/protocol/deployed-urls.ts index bff1978029b..e3b925dd3f0 100644 --- a/packages/sim-cli/src/commands/protocol/deployed-urls.ts +++ b/packages/sim-cli/src/commands/protocol/deployed-urls.ts @@ -3,7 +3,7 @@ * named with its URL, so nobody has to look it up with `sim workflows deployment status` after. */ import { getErrorMessage } from '@sim/utils/errors' -import { isRecordLike } from '@sim/utils/object' +import { parseWorkflowLock } from '@sim/workflow-code' import { printError } from '#sim-cli/output/io' import type { GetWorkflowDeploymentResponse } from '../../generated/v2-api' import type { OperationClient } from '../../runtime/called-operations' @@ -15,17 +15,23 @@ export interface DeployedUrl { url: string } -/** Each block id of a lock (`.sim/lock.json`) mapped to how source names it: `key (ident)`. */ -export function lockBlockNames(lock: unknown): Map { - const names = new Map() - const blocks = isRecordLike(lock) ? lock.blocks : undefined - if (!isRecordLike(blocks)) return names - for (const [key, entry] of Object.entries(blocks)) { - if (!isRecordLike(entry) || typeof entry.id !== 'string') continue - const ident = typeof entry.ident === 'string' && entry.ident !== key ? ` (${entry.ident})` : '' - names.set(entry.id, `${key}${ident}`) - } - return names +/** How source names a block: its key, with its const when that differs (`leadin (hook)`). */ +export function blockLabel(key: string, ident: string): string { + return ident === key ? key : `${key} (${ident})` +} + +/** + * Each block id of a lock (`.sim/lock.json`, parsed or as JSON text) mapped to its + * {@link blockLabel}; empty when the lock does not parse. + */ +export function lockBlockNames(lockInput: unknown): Map { + const { lock } = parseWorkflowLock(lockInput) + return new Map( + Object.entries(lock?.blocks ?? {}).map(([key, entry]) => [ + entry.id, + blockLabel(key, entry.ident), + ]) + ) } /** The deployment's webhook URLs, each named through `names` (block id → source name). */ diff --git a/packages/sim-cli/src/commands/protocol/run-source-location.ts b/packages/sim-cli/src/commands/protocol/run-source-location.ts index 69eb47350cd..bc0e72a021b 100644 --- a/packages/sim-cli/src/commands/protocol/run-source-location.ts +++ b/packages/sim-cli/src/commands/protocol/run-source-location.ts @@ -3,10 +3,13 @@ * the directory's lock binds that id to the block's key, const and function file, and a function * block's error names its line, which the stored code keeps one to one with the file. */ -import { isRecordLike, toRecord } from '@sim/utils/object' +import { toRecord } from '@sim/utils/object' +import { escapeRegExp } from '@sim/utils/string' +import { parseWorkflowLock } from '@sim/workflow-code' import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' import { annotationLine, annotationPath, printAnnotations } from '#sim-cli/output/github-actions' import { printError } from '#sim-cli/output/io' +import { blockLabel } from './deployed-urls' import { readPreviousLock, readSourceJson, readSourceText } from './source-dir' /** A failed block, as the source directory names it. */ @@ -16,7 +19,7 @@ export interface RunFailureSite { line: number | null /** The block's key, and its const when it differs: `normalize`, or `leadin (hook)`. */ block: string - /** The entry file and the line of the block's declaration, when it is found there. */ + /** Where the entry file declares a block whose code is in its own file, when found. */ declaredAt: string | null } @@ -28,7 +31,7 @@ function errorLine(message: string): number | null { /** The 1-based line of `const =` in `entry`, else `null`. */ function declarationLine(entry: string, ident: string): number | null { - const pattern = new RegExp(`^\\s*const\\s+${ident.replace(/\$/g, '\\$')}\\s*=`) + const pattern = new RegExp(`^\\s*const\\s+${escapeRegExp(ident)}\\s*=`) const index = entry.split('\n').findIndex((line) => pattern.test(line)) return index === -1 ? null : index + 1 } @@ -45,28 +48,23 @@ export async function runFailureSite( const { blockId, message } = toRecord(error) if (typeof blockId !== 'string') return null if (toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)).workflowId !== workflowId) return null - const blocks = toRecord(await readPreviousLock(dir)).blocks - if (!isRecordLike(blocks)) return null - const bound = Object.entries(blocks).find( - ([, entry]) => isRecordLike(entry) && entry.id === blockId - ) + const { lock } = parseWorkflowLock(await readPreviousLock(dir)) + const bound = Object.entries(lock?.blocks ?? {}).find(([, entry]) => entry.id === blockId) if (!bound) return null - const [key, entry] = bound as [string, Record] - const ident = typeof entry.ident === 'string' ? entry.ident : key + const [key, entry] = bound + const block = blockLabel(key, entry.ident) const entryText = await readSourceText(dir, SOURCE_ENTRY_FILE) - const declared = entryText === null ? null : declarationLine(entryText, ident) + const declared = entryText === null ? null : declarationLine(entryText, entry.ident) const entryPath = annotationPath(dir, SOURCE_ENTRY_FILE) - const declaredAt = declared === null ? null : `${entryPath}:${declared}` - const block = ident === key ? key : `${key} (${ident})` - if (typeof entry.codeFile === 'string') { + if (entry.codeFile !== undefined) { return { file: annotationPath(dir, entry.codeFile), line: typeof message === 'string' ? errorLine(message) : null, block, - declaredAt, + declaredAt: declared === null ? null : `${entryPath}:${declared}`, } } - return { file: entryPath, line: declared, block, declaredAt } + return { file: entryPath, line: declared, block, declaredAt: null } } /** @@ -86,17 +84,14 @@ export async function printRunFailureSite( return } const where = `${site.file}${site.line === null ? '' : `:${site.line}`}` - const declared = - site.declaredAt && !site.declaredAt.startsWith(`${site.file}:`) - ? `, declared at ${site.declaredAt}` - : '' + const declared = site.declaredAt ? `, declared at ${site.declaredAt}` : '' const message = toRecord(error).message const text = typeof message === 'string' ? message : 'The block failed.' printError(`${where}: ${text} (block ${site.block}${declared})`) printAnnotations([ annotationLine('error', text, { file: site.file, - ...(site.line !== null ? { line: site.line } : {}), + line: site.line ?? undefined, title: `Run failed in ${site.block}`, }), ]) diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index abb1dffa553..98cd337785f 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -8,7 +8,12 @@ import { boundFindingText, type RefusalClass } from '@sim/workflow-code/diagnost import { SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { type FlatDiagnostic, refusalClass } from '@sim/workspace-code' import type { Command } from 'commander' -import { annotationLine, annotationPath, printAnnotations } from '#sim-cli/output/github-actions' +import { + annotationLine, + annotationPath, + inGithubActions, + printAnnotations, +} from '#sim-cli/output/github-actions' import { printError } from '#sim-cli/output/io' import { askLine } from '#sim-cli/terminal/line-input' import type { OutputFormat } from '../../config/index' @@ -139,7 +144,7 @@ function printDiagnostics(diagnostics: readonly Diagnostic[]): void { type ResultDiagnostic = Omit & { code: Diagnostic['code'] } /** Whether `format` prints one machine document on stdout rather than lines for a person. */ -function isMachine(format: OutputFormat): boolean { +export function isMachine(format: OutputFormat): boolean { return format === 'json' || format === 'yaml' } @@ -210,24 +215,16 @@ export interface FindingsOutput { function findingAnnotation(diagnostic: Diagnostic, dir: string | undefined): string[] { if (diagnostic.severity === 'info') return [] const file = - diagnostic.file !== undefined && diagnostic.path === undefined - ? dir === undefined + diagnostic.file === undefined || diagnostic.path !== undefined + ? undefined + : dir === undefined ? diagnostic.file : annotationPath(dir, diagnostic.file) - : undefined + const site = file === undefined ? {} : { file, line: diagnostic.line, column: diagnostic.column } const message = diagnostic.hint ? `${diagnostic.message} Hint: ${diagnostic.hint}` : diagnostic.message - return [ - annotationLine(diagnostic.severity, message, { - ...(file !== undefined ? { file } : {}), - ...(file !== undefined && diagnostic.line !== undefined ? { line: diagnostic.line } : {}), - ...(file !== undefined && diagnostic.column !== undefined - ? { column: diagnostic.column } - : {}), - title: diagnostic.code, - }), - ] + return [annotationLine(diagnostic.severity, message, { ...site, title: diagnostic.code })] } /** @@ -261,7 +258,9 @@ export function findingsOutput( ) .map((diagnostic) => boundFindingText(diagnostic)) if (!machine) printDiagnostics(unseen) - printAnnotations(unseen.flatMap((diagnostic) => findingAnnotation(diagnostic, dir))) + if (inGithubActions()) { + printAnnotations(unseen.flatMap((diagnostic) => findingAnnotation(diagnostic, dir))) + } }, result: (diagnostics) => resultDiagnostics( diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index 717bbf75245..b5117550ab8 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -43,6 +43,7 @@ import { type FindingsOutput, findingsOutput, fresh, + isMachine, printRefusal, refusedExitCode, shellWord, @@ -286,7 +287,7 @@ async function deployStep( isDeployed: true, }, needsRedeployment: false, - ...urlsOf(namedUrls(status.webhooks, lockBlockNames(data.lock))), + urls: namedUrls(status.webhooks, lockBlockNames(data.lock)), } } } @@ -312,23 +313,12 @@ async function deployStep( ...(options.machine && deployed.warnings.length > 0 ? { warnings: deployed.warnings } : {}), }, needsRedeployment: false, - ...(deployed.isDeployed ? await liveUrls(client, data) : {}), + ...(deployed.isDeployed + ? { urls: await deployedUrls(client, data.workflowId, lockBlockNames(data.lock)) } + : {}), } } -/** The live deployment's webhook URLs, each named as the stored lock names its block. */ -async function liveUrls( - client: OperationClient<'getWorkflowDeployment'>, - data: SourceApplyData -): Promise> { - return urlsOf(await deployedUrls(client, data.workflowId, lockBlockNames(data.lock))) -} - -/** `urls` as a deploy outcome's field: absent when there are none. */ -function urlsOf(urls: DeployedUrl[]): Pick { - return urls.length > 0 ? { urls } : {} -} - /** A failed deploy after a saved write, saying the write itself stands and how to deploy it. */ function deployFailure( error: unknown, @@ -506,7 +496,7 @@ export function attachWorkflowSourceCreate(source: Command): void { command: `${createCommand(shellWord(options.dir), workspaceId)} --yes`, reason: `${options.dir} had no ${ENTRY_FILE}, so a starter, the SDK types for workspace ${workspaceId}, tsconfig.json, .sim/AGENTS.md and the examples in .sim/examples/ were written and nothing was created. Edit ${ENTRY_FILE}, check it, then create it.`, } - const machine = profile.output === 'json' || profile.output === 'yaml' + const machine = isMachine(profile.output) if (!machine) printError(`${next.reason} Next: ${next.command}`) printTreeResult(profile.output, { created: false, diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts index 03262398508..c6fc048d5fc 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts @@ -9,6 +9,7 @@ import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' import { readSourceJson, workspaceFolderOf } from './source-dir' import { cachedCatalog, cachedSourceCatalog } from './source-tree' +import { isMachine } from './source-ui' const PARAMS_HELP = ` Prints a builder's params (required first, with enums and defaults), the gate field that picks @@ -61,7 +62,7 @@ export function attachWorkflowSourceParams(source: Command): void { const profile = profileFrom(command) const catalog = await lookupCatalog(options.dir, profile.workspaceId) const found = lookupBuilder(catalog, query) - const machine = profile.output === 'json' || profile.output === 'yaml' + const machine = isMachine(profile.output) switch (found.kind) { case 'builder': if (machine) printProtocolResult(profile.output, { builder: found.reference }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index c80b4d37029..13a2c807911 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -8,9 +8,11 @@ import { KIND_DIRS, parseResourceAddress, parseWorkspaceBase, + resourceAddress, type WorkspaceKind, } from '@sim/workspace-code' import { isBlobPath, KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' +import { workflowFolder } from '@sim/workspace-code/kinds/workflow' import { kindOfPath, WORKSPACE_BASE_FILE } from '@sim/workspace-code/layout' import { type PromotionRecord, @@ -31,6 +33,7 @@ import type { GetWorkspaceSourceResponse, } from '../../generated/v2-api' import { SimApiError } from '../../http/client' +import { safeOneLine } from '../../output/render' import { apiCommand, type OperationClient } from '../../runtime/called-operations' import { searchTasks } from '../search' import { type DeployedUrl, deployedUrls, deployedUrlsText, lockBlockNames } from './deployed-urls' @@ -155,13 +158,21 @@ function notWritten(data: ApplyData): string[] { .map((change) => `${change.kind}:${change.key}`) } -/** How a stopped apply left one planned write: written, the one that failed, or not attempted. */ -function outcomeText(change: Change, outcome: PlanOutcome): string { - if (change.held) return '' - if (wasWritten(change, outcome)) return ' — written' +/** How an apply left one planned change: held back, written, the one that failed, or not attempted. */ +function changeOutcome( + change: Change, + outcome: PlanOutcome +): 'held back' | 'written' | 'failed, not written' | 'not written' { + if (change.held) return 'held back' + if (wasWritten(change, outcome)) return 'written' return outcome.failed && sameChange(outcome.failed, change) - ? ' — failed, not written' - : ' — not written' + ? 'failed, not written' + : 'not written' +} + +/** {@link changeOutcome} as a plan line's suffix; a held change says so on its own. */ +function outcomeText(change: Change, outcome: PlanOutcome): string { + return change.held ? '' : ` — ${changeOutcome(change, outcome)}` } /** @@ -831,7 +842,9 @@ export function attachWorkspaceSourceApply(source: Command): void { /** Prints `data` as the result, with the findings about files the CLI did not send. */ const report = (data: ApplyData, next?: NextStep, urls: WorkflowUrl[] = []) => { const diagnostics = [...notSent, ...data.diagnostics] - appendStepSummary(planMarkdown({ ...data, diagnostics }, options.to ?? workspaceId)) + appendStepSummary(() => + planMarkdown({ ...data, diagnostics }, options.to ?? workspaceId) + ) const result = { ...summarize({ ...data, diagnostics }), ...(urls.length > 0 ? { urls } : {}), @@ -917,7 +930,7 @@ const SUMMARY_ROWS = 50 /** A Markdown table cell: one line, with its pipes escaped. */ function cell(text: string): string { - return text.replaceAll('|', '\\|').replace(/\s+/g, ' ') + return safeOneLine(text).replaceAll('|', '\\|') } /** @@ -928,13 +941,9 @@ function planMarkdown(data: ApplyData, workspaceId: string): string { const summary = summarize(data) const changes = data.plan.filter((change) => change.action !== 'noop') const rows = changes.slice(0, SUMMARY_ROWS).map((change) => { - const fields = change.fields?.length ? ` (${change.fields.join(', ')})` : '' - const fate = change.held - ? 'held back' - : data.dryRun - ? 'planned' - : outcomeText(change, data).replace(' — ', '') || 'written' - return `| ${SYMBOLS[change.action]} | ${cell(resourceWhere(change.kind, change.key))}${cell(fields)} | ${change.action} | ${fate} |` + const fields = change.fields?.length ? ` (${cell(change.fields.join(', '))})` : '' + const fate = data.dryRun && !change.held ? 'planned' : changeOutcome(change, data) + return `| ${SYMBOLS[change.action]} | ${cell(resourceWhere(change.kind, change.key))}${fields} | ${change.action} | ${fate} |` }) const errors = data.diagnostics.filter((finding) => finding.severity === 'error') const lines = [ @@ -999,14 +1008,10 @@ async function deploymentUrls( ) const perWorkflow = await Promise.all( deployed.map(async ({ key }): Promise => { - const workflowId = base?.resources[`workflow:${key}`]?.id + const workflowId = base?.resources[resourceAddress('workflow', key)]?.id if (!workflowId) return [] - const lockText = data.files[`${KIND_DIRS.workflow}/${key}/${SOURCE_LOCK_FILE}`] - let lock: unknown = null - try { - lock = lockText === undefined ? null : JSON.parse(lockText) - } catch {} - const named = await deployedUrls(client, workflowId, lockBlockNames(lock)) + const lock = data.files[`${workflowFolder(key)}/${SOURCE_LOCK_FILE}`] + const named = await deployedUrls(client, workflowId, lockBlockNames(lock ?? null)) return named.map((url) => ({ workflow: key, ...url })) }) ) diff --git a/packages/sim-cli/src/output/github-actions.ts b/packages/sim-cli/src/output/github-actions.ts index 00f11f7c43c..1ec21086913 100644 --- a/packages/sim-cli/src/output/github-actions.ts +++ b/packages/sim-cli/src/output/github-actions.ts @@ -67,14 +67,17 @@ export function printAnnotations(lines: readonly string[]): void { } /** - * Appends `markdown` to the job's step summary, when this is a GitHub Actions step that has one. A + * Appends `markdown()` (built only then) to the job's step summary, when this is a GitHub Actions step that has one. A * summary that cannot be written is reported and skipped: the command's own result stands. */ -export function appendStepSummary(markdown: string, env: NodeJS.ProcessEnv = process.env): void { +export function appendStepSummary( + markdown: () => string, + env: NodeJS.ProcessEnv = process.env +): void { const path = env.GITHUB_STEP_SUMMARY if (!inGithubActions(env) || !path) return try { - appendFileSync(path, `${markdown.trimEnd()}\n\n`) + appendFileSync(path, `${markdown().trimEnd()}\n\n`) } catch (error) { printError(`The step summary could not be written: ${getErrorMessage(error)}`) } diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 3907e243d38..8b437b3993f 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -208,17 +208,6 @@ function registerList( for (const [key, property] of entries) addItem(property, anchorOf(key)) } -/** - * The block meta keys an author most often writes among the params by mistake, each with the call - * that places it: the meta object is a builder's third argument, beside the params. - */ -const BLOCK_META_HINTS: Readonly> = { - retry: "agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })", - disabled: "agent('Name', {…}, { disabled: true })", - locked: "agent('Name', {…}, { locked: true })", - errorPort: "agent('Name', {…}, { errorPort: true })", -} - /** `meta`: block-level fields, in the printer's vocabulary. */ function compileMeta(ctx: CompileContext, node: Node | undefined, site: ValueSite): CompiledMeta { const meta: CompiledMeta = { @@ -1151,8 +1140,8 @@ function compileWrittenParams( { hint: alias ? `Write it as ${alias}; the value kind picks the basic or advanced field.` - : Object.hasOwn(BLOCK_META_HINTS, key) - ? `${key} is block meta, not a param: pass it in the third argument, ${BLOCK_META_HINTS[key]}.` + : (BLOCK_META_KEYS as readonly string[]).includes(key) + ? `${key} is block meta, not a param: pass it in the builder's third argument, ('Name', {…}, { ${key}: … }).` : didYouMean(key, index.fields.keys()), blockKey: decl.key, param: key, diff --git a/packages/workflow-code/src/compile/ergonomics.test.ts b/packages/workflow-code/src/compile/ergonomics.test.ts index 129cb7fb1a8..63e38f8cb8d 100644 --- a/packages/workflow-code/src/compile/ergonomics.test.ts +++ b/packages/workflow-code/src/compile/ergonomics.test.ts @@ -75,7 +75,7 @@ describe('param aliases', () => { ) const unknown = result.diagnostics.find((d) => d.code === 'E_UNKNOWN_PARAM') expect(unknown?.hint).toMatch( - /^retry is block meta, not a param: pass it in the third argument/ + /^retry is block meta, not a param: pass it in the builder's third argument/ ) }) }) From 2729a0d2c6b89779adf075b33d3196bca21ed275 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:35:52 -0800 Subject: [PATCH 36/85] refactor(workflow-code): simplify the final server fixes One shared workspacesPaidBy predicate for staging's payer sum, the payer resolved before the staging transaction, the file adapter's stale mapping in one helper (dropping a pre-read the locked delete check made redundant), the dry-run deployment check owned by the outcome module, an optional rowLimit instead of a -1 sentinel, one Retry-After header constant, and table rename findings returned with their table. --- .../app/api/workflows/[id]/source/route.ts | 9 ++--- apps/sim/lib/billing/core/payer-context.ts | 16 +++++--- apps/sim/lib/table/application/reshape.ts | 2 +- apps/sim/lib/table/rows/keyed-write.ts | 20 ++++++---- apps/sim/lib/table/rows/writes.integration.ts | 1 - apps/sim/lib/workflows/api/source-slots.ts | 19 +++------- .../application/apply-workflow-source.ts | 15 +------- .../application/source-pipeline/outcome.ts | 30 ++++++++++----- .../application/kinds/files/adapter.ts | 38 +++++++++---------- .../application/kinds/table/renames.ts | 27 +++++++------ .../sim/lib/workspace-source/staging/store.ts | 32 ++++++++-------- packages/workflow-persistence/src/load.ts | 5 +-- 12 files changed, 105 insertions(+), 109 deletions(-) diff --git a/apps/sim/app/api/workflows/[id]/source/route.ts b/apps/sim/app/api/workflows/[id]/source/route.ts index 27759d3301f..ff4457a5d60 100644 --- a/apps/sim/app/api/workflows/[id]/source/route.ts +++ b/apps/sim/app/api/workflows/[id]/source/route.ts @@ -36,12 +36,9 @@ const SOURCE_READ_RATE_LIMIT: TokenBucketConfig = { * The bare fingerprint would not do: it ignores what it does not hash (canvas positions, * comments), which the printed files and lock can still carry. * - * The tag is taken after the read, so a `304` still loads, canonicalizes and prints the draft: the - * printed resource keys are known only once the stored graph is canonicalized (a reference the - * graph gained loads its key then), and a workspace apply that rebinds or releases a key changes - * the print without touching this workflow's rows, so no tag taken before that would be sound. Like the v2 - * read, it runs in a source read slot, and a server already running as many answers `429` with - * `Retry-After`. + * Runs in a source read slot, like the v2 read (`429` with `Retry-After` when the server is full). + * The tag is taken after the read: the printed resource keys are known only once the graph is + * canonicalized, so no earlier tag would be sound. * * `headSafe: false` because the first read that references a resource with no key allocates one * (`workspace_resource_key`), so a `HEAD` probe must not run it. diff --git a/apps/sim/lib/billing/core/payer-context.ts b/apps/sim/lib/billing/core/payer-context.ts index e16b29dde63..2d822937669 100644 --- a/apps/sim/lib/billing/core/payer-context.ts +++ b/apps/sim/lib/billing/core/payer-context.ts @@ -9,15 +9,21 @@ export interface BillingBlockState { blockedByOrgOwner: boolean } +type PayerTarget = { type: 'user'; id: string } | { type: 'organization'; id: string } + +/** The `workspace` rows whose host billing identity is `payer`: an organization's, or a person's own. */ +export function workspacesPaidBy(payer: PayerTarget) { + return payer.type === 'organization' + ? eq(workspace.organizationId, payer.id) + : and(eq(workspace.billedAccountUserId, payer.id), isNull(workspace.organizationId)) +} + /** Finds an active workspace whose host billing identity is the requested payer. */ export async function getUpgradeWorkspaceId( - target: { type: 'user'; id: string } | { type: 'organization'; id: string }, + target: PayerTarget, executor: DbClient = db ): Promise { - const targetPredicate = - target.type === 'organization' - ? eq(workspace.organizationId, target.id) - : and(eq(workspace.billedAccountUserId, target.id), isNull(workspace.organizationId)) + const targetPredicate = workspacesPaidBy(target) const [record] = await executor .select({ id: workspace.id }) diff --git a/apps/sim/lib/table/application/reshape.ts b/apps/sim/lib/table/application/reshape.ts index 272a093303a..e8a214bd736 100644 --- a/apps/sim/lib/table/application/reshape.ts +++ b/apps/sim/lib/table/application/reshape.ts @@ -332,7 +332,7 @@ export const reshapeTableUseCase = defineAuthorizedTableUseCase({ columnIds: rows.columns.flatMap((name) => idByName.get(name) ?? []), rows: stored, allowDelete: rows.allowDelete, - rowLimit: rowLimit ?? -1, + ...(rowLimit !== null ? { rowLimit } : {}), }, actor, requestId diff --git a/apps/sim/lib/table/rows/keyed-write.ts b/apps/sim/lib/table/rows/keyed-write.ts index 039cf68c35a..20d9e668ac4 100644 --- a/apps/sim/lib/table/rows/keyed-write.ts +++ b/apps/sim/lib/table/rows/keyed-write.ts @@ -4,9 +4,9 @@ * row service's transaction-bound writers: stored rows whose key no declared row has are deleted, * rows whose declared cells changed are patched (cells of other columns, a workflow group's * outputs say, are left alone), and new keys are inserted. A stored row with no key value (the - * grid's "add row" makes one) is no declared row's, so it is kept, and counts toward the table's row - * limit with the rest. An unchanged row is not touched, so - * its id, `updated_at`, run state and provenance stay, and no trigger fires for it. + * grid's "add row" makes one) is no declared row's, so it is kept, and counts toward the table's + * row limit with the rest. An unchanged row is not touched, so its id, `updated_at`, run state and + * provenance stay, and no trigger fires for it. */ import { isDeepStrictEqual } from 'node:util' @@ -37,10 +37,10 @@ export interface KeyedRows { /** Whether stored rows no declared row matches are deleted; otherwise they refuse the write. */ allowDelete: boolean /** - * The plan's row limit for the table (negative: unlimited). The write is refused when the rows - * it leaves, the stored rows with no key value it keeps included, would cross it. + * The plan's row limit for the table, when it has one: the write is refused when the rows it + * leaves, the stored rows with no key value it keeps included, would cross it. */ - rowLimit: number + rowLimit?: number } /** What a keyed write changed, and the triggers to fire once the transaction commits. */ @@ -138,8 +138,12 @@ export async function writeKeyedRowsWithTx( `${removed.length} stored row(s) of "${table.name}" match no declared row; deleting them needs allow-delete.` ) } - if (wouldExceedRowLimit(declared.rowLimit, stored.length - removed.length, inserts.length)) { - throw new TableRowLimitError(declared.rowLimit) + const { rowLimit } = declared + if ( + rowLimit !== undefined && + wouldExceedRowLimit(rowLimit, stored.length - removed.length, inserts.length) + ) { + throw new TableRowLimitError(rowLimit) } const deletion = diff --git a/apps/sim/lib/table/rows/writes.integration.ts b/apps/sim/lib/table/rows/writes.integration.ts index 00a2b951f53..15d293371e6 100644 --- a/apps/sim/lib/table/rows/writes.integration.ts +++ b/apps/sim/lib/table/rows/writes.integration.ts @@ -361,7 +361,6 @@ describe('table row writes against real PostgreSQL', () => { columnIds: ['key', 'note'], rows: [{ key: 'kept', note: 'new' }], allowDelete: true, - rowLimit: -1, }, { userId, capabilityGovernedUserId: null }, 'keyed-timeout' diff --git a/apps/sim/lib/workflows/api/source-slots.ts b/apps/sim/lib/workflows/api/source-slots.ts index f1a360555db..74c7886370c 100644 --- a/apps/sim/lib/workflows/api/source-slots.ts +++ b/apps/sim/lib/workflows/api/source-slots.ts @@ -16,8 +16,8 @@ const LANE_NOUNS: Record = { read: 'gets', plan: 'plans', ap const runningSourceRequests: Record = { read: 0, plan: 0, apply: 0 } -/** Seconds a request refused for want of a slot is told to wait. */ -const SOURCE_BUSY_RETRY_AFTER_SECONDS = 5 +/** The wait a request refused for want of a slot is told to take. */ +const SOURCE_BUSY_HEADERS = { 'Retry-After': '5' } /** A source request refused because this process already runs as many as it may. */ class SourceSlotBusyError extends Error { @@ -32,7 +32,8 @@ class SourceSlotBusyError extends Error { /** * `useCase`, run in one of its lane's slots (`laneOf`, or the lane it picks for the input): a get, * plan or apply (each holds a workflow's or a directory's worth of text, stored state and - * canonical forms in memory) waits for nothing, and is refused with a `429` (see {@link renderSourceSlotBusy}) when the process already runs + * canonical forms in memory) waits for nothing, and is refused with a `429` (see + * {@link renderSourceSlotBusy}) when the process already runs * {@link MAX_CONCURRENT_SOURCE_REQUESTS} of them, so a burst cannot run the process out of memory. */ export function withSourceSlot( @@ -67,19 +68,11 @@ export function applyOrDryRunLane(input: { dryRun?: boolean }): SourceLane { /** A request {@link withSourceSlot} refused, as `429` with `Retry-After`; `null` for any other error. */ export function renderSourceSlotBusy(error: unknown): NextResponse | null { if (!(error instanceof SourceSlotBusyError)) return null - return v2Error('RATE_LIMITED', error.message, { - headers: { 'Retry-After': String(SOURCE_BUSY_RETRY_AFTER_SECONDS) }, - }) + return v2Error('RATE_LIMITED', error.message, { headers: SOURCE_BUSY_HEADERS }) } /** {@link renderSourceSlotBusy} for an internal route. */ export function projectInternalSourceSlotBusy(error: unknown): JsonErrorResponseDescriptor | null { if (!(error instanceof SourceSlotBusyError)) return null - return internalErrorResponse( - 429, - { error: error.message }, - { - 'Retry-After': String(SOURCE_BUSY_RETRY_AFTER_SECONDS), - } - ) + return internalErrorResponse(429, { error: error.message }, SOURCE_BUSY_HEADERS) } diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.ts b/apps/sim/lib/workflows/application/apply-workflow-source.ts index 9bfddc8a8a1..e04588c9ef6 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.ts @@ -29,7 +29,6 @@ import { sourceApplyAudit, sourceCreateAudit, } from '@/lib/workflows/application/source-pipeline' -import { checkNeedsRedeployment } from '@/lib/workflows/deployment-status' import { resolveActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' export interface ApplyWorkflowSourceInput { @@ -66,15 +65,6 @@ export interface CreateWorkflowFromSourceInput { provenance?: SourceProvenance } -/** - * Whether the draft as it is differs from its deployment, for a dry run that leaves it so (a no-op - * or a refusal). A new workflow has no deployment. A dry run that would change the draft compares - * what it would write instead, so this runs only once the plan says it will not. - */ -async function draftNeedsRedeployment(target: SourceTarget): Promise { - return target.kind === 'new' ? false : checkNeedsRedeployment(target.context.workflowId) -} - /** * Plans the submission onto `target`, then answers: a refused plan throws (409 when stale, else * 400), or on a dry run answers 200 with its findings; a planned one is previewed on a dry run @@ -91,11 +81,10 @@ async function writeSource( if (planned.kind === 'refused') throw refusalError(planned) return commitSource(principal, planned, target) } - const needsRedeployment = () => draftNeedsRedeployment(target) const planned = await planSource(principal, target, submission, { allocate: false }) return planned.kind === 'refused' - ? refusedOutcome(planned, target, submission, needsRedeployment) - : previewSource(principal, planned, needsRedeployment) + ? refusedOutcome(planned, target, submission) + : previewSource(principal, planned) } /** diff --git a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts index 3a757b99dd2..17396801def 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts @@ -15,7 +15,10 @@ import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/sourc import { type CommitTarget, targetIds } from '@/lib/workflows/application/source-pipeline/load' import type { PlannedSource, RefusedSource } from '@/lib/workflows/application/source-pipeline/plan' import { type PrintedSource, printStoredSource } from '@/lib/workflows/code/print-stored' -import { checkDraftNeedsRedeployment } from '@/lib/workflows/deployment-status' +import { + checkDraftNeedsRedeployment, + checkNeedsRedeployment, +} from '@/lib/workflows/deployment-status' const logger = createLogger('ApplyWorkflowSource') @@ -126,15 +129,23 @@ export function printWritten( ) } +/** + * Whether the draft as it is differs from its deployment, for a dry run that leaves it so (a no-op + * or a refusal); a new workflow has none. Run only once the plan says so: a dry run that would + * change the draft compares what it would write instead. + */ +async function draftNeedsRedeployment(target: CommitTarget): Promise { + return target.kind === 'new' ? false : checkNeedsRedeployment(target.context.workflowId) +} + /** * The dry run of a plan: what a commit would store, re-printed, and whether the draft would then - * differ from its deployment. A graph no-op reports the source meta a commit would store, and - * `draftNeedsRedeployment`, the deployment check of the draft as it is, run only for a no-op. + * differ from its deployment. A graph no-op reports the source meta a commit would store, and the + * deployment check of the draft as it is. */ export async function previewSource( principal: Principal, - planned: PlannedSource, - draftNeedsRedeployment: () => Promise + planned: PlannedSource ): Promise { const { plan, loaded, target } = planned const frame = { @@ -151,7 +162,7 @@ export async function previewSource( workflowName: plan.meta.name, diff: plan.diff, diagnostics: plan.diagnostics, - needsRedeployment: await draftNeedsRedeployment(), + needsRedeployment: await draftNeedsRedeployment(target), }) } const preview = await previewSourceCommit(planned.workflowId, plan) @@ -181,13 +192,12 @@ export async function previewSource( * The dry-run answer for a refused plan: its findings with a 200, echoing the submission. It echoes * the caller's own base fingerprint, so applying its response after a stale or mismatched read * still fails the freshness check rather than overwriting the newer draft, and the deployment check - * of the draft as it is (`draftNeedsRedeployment`). + * of the draft as it is. */ export async function refusedOutcome( refused: RefusedSource, target: CommitTarget, - submission: { files: Record; lock: WorkflowLockV1 }, - draftNeedsRedeployment: () => Promise + submission: { files: Record; lock: WorkflowLockV1 } ): Promise { return shapeOutcome( { @@ -201,7 +211,7 @@ export async function refusedOutcome( applied: false, diff: emptyDiffSummary(), diagnostics: refused.diagnostics, - needsRedeployment: await draftNeedsRedeployment(), + needsRedeployment: await draftNeedsRedeployment(target), } ) } diff --git a/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts index dc92c5ea6d0..8bb9c7ed1cb 100644 --- a/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts @@ -227,6 +227,19 @@ async function stateOf(ctx: SourceContext, fileId: string): Promise { + if (error instanceof OrchestrationError && error.code === 'conflict') { + throw new ResourceChangedError(change) + } + throw error + } +} + /** Why a directory never writes a file at a workflow test's path. */ const WORKFLOW_TEST_REASON = 'is where a workflow test lives, which is not a plain workspace file' @@ -578,20 +591,12 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { const fileId = change.storedId const rev = change.detail?.rev if (!fileId || rev === undefined) throw new Error('A file delete needs its plan') - if ((await stateOf(ctx, fileId)).rev !== rev) { - throw new ResourceChangedError(change) - } - try { - await deleteWorkspaceFileOperation.execute({ + await deleteWorkspaceFileOperation + .execute({ principal, input: { fileId, assertedWorkspaceId: workspaceId, expectedRevision: rev }, }) - } catch (error) { - if (error instanceof OrchestrationError && error.code === 'conflict') { - throw new ResourceChangedError(change) - } - throw error - } + .catch(staleAs(change)) return { id: fileId, text: {} } } const { content, sha256 } = await contentOf(change, ctx) @@ -617,8 +622,8 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { const fileId = change.storedId const rev = change.detail?.rev if (!fileId || rev === undefined) throw new Error('A file update needs its plan') - try { - await updateWorkspaceFileContentFromBuffer.execute({ + await updateWorkspaceFileContentFromBuffer + .execute({ principal, input: { fileId, @@ -628,12 +633,7 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { expectedRevision: rev, }, }) - } catch (error) { - if (error instanceof OrchestrationError && error.code === 'conflict') { - throw new ResourceChangedError(change) - } - throw error - } + .catch(staleAs(change)) return written(ctx, change.key, fileId, sha256) }, diff --git a/apps/sim/lib/workspace-source/application/kinds/table/renames.ts b/apps/sim/lib/workspace-source/application/kinds/table/renames.ts index 9f5c65763be..1b68a60b0d0 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/renames.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/renames.ts @@ -119,18 +119,19 @@ export async function checkColumnRenamesInUse( c.kind === 'workflow' && c.action === 'delete' && c.storedId !== undefined ? [c.storedId] : [] ) ) - const checks = tables.flatMap((table) => - (using.get(table.tableId) ?? []) + const checks = tables.flatMap((table) => { + const columns = new Map([ + [table.tableId, { name: table.tableName, columnNames: table.columnNames }], + ]) + return (using.get(table.tableId) ?? []) .filter((workflow) => !deleted.has(workflow.id)) - .map((workflow) => ({ table, workflow })) - ) + .map((workflow) => ({ table, columns, workflow })) + }) // Each check loads a workflow's draft, source or live version: independent reads, run a few at // once, their findings kept in check order. - const found = await mapWithConcurrency(checks, READ_CONCURRENCY, async ({ table, workflow }) => { + const found = await mapWithConcurrency(checks, READ_CONCURRENCY, async (check) => { + const { table, columns, workflow } = check const findings: WorkspaceSourceDiagnostic[] = [] - const columns = new Map([ - [table.tableId, { name: table.tableName, columnNames: table.columnNames }], - ]) const folder = declared.get(workflow.id) /** `blockId:field` of each finding already made from the draft. */ const reported = new Set() @@ -171,9 +172,9 @@ export async function checkColumnRenamesInUse( ) } } - if (!workflow.live || replacedLive.has(workflow.id)) return findings + if (!workflow.live || replacedLive.has(workflow.id)) return { table, findings } const live = await liveBlocks(workflow.id) - if (!live) return findings + if (!live) return { table, findings } for (const issue of collectTableBlockFieldIssues(live, columns)) { if (!table.renamed.has(issue.field) || reported.has(`${issue.blockId}:${issue.field}`)) { continue @@ -192,9 +193,7 @@ export async function checkColumnRenamesInUse( ) ) } - return findings - }) - checks.forEach(({ table }, index) => { - table.change.diagnostics.push(...found[index]) + return { table, findings } }) + for (const { table, findings } of found) table.change.diagnostics.push(...findings) } diff --git a/apps/sim/lib/workspace-source/staging/store.ts b/apps/sim/lib/workspace-source/staging/store.ts index 9c99f0cdd8a..9cd88cd570f 100644 --- a/apps/sim/lib/workspace-source/staging/store.ts +++ b/apps/sim/lib/workspace-source/staging/store.ts @@ -15,9 +15,13 @@ import { createLogger } from '@sim/logger' import { sha256Hex } from '@sim/security/hash' 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' +import { and, asc, eq, gt, inArray, lt, lte, notInArray, sql } from 'drizzle-orm' +import { workspacesPaidBy } from '@/lib/billing/core/payer-context' import type { BillingEntity } from '@/lib/billing/core/usage-log' -import { resolveStorageBillingContext } from '@/lib/billing/storage/context' +import { + resolveStorageBillingContext, + type StorageBillingContext, +} from '@/lib/billing/storage/context' import { checkStorageQuotaForBillingContext, isStorageEnforcementEnabled, @@ -127,30 +131,21 @@ async function payerStagedBytes(tx: DbTransaction, payer: BillingEntity): Promis }) .from(workspaceSourceStagedBlob) .innerJoin(workspace, eq(workspace.id, workspaceSourceStagedBlob.workspaceId)) - .where( - and( - gt(workspaceSourceStagedBlob.expiresAt, new Date()), - payer.type === 'organization' - ? eq(workspace.organizationId, payer.id) - : and(isNull(workspace.organizationId), eq(workspace.billedAccountUserId, payer.id)) - ) - ) + .where(and(gt(workspaceSourceStagedBlob.expiresAt, new Date()), workspacesPaidBy(payer))) return Number(usage?.bytes ?? 0) } /** - * Refuses staging `bytes` more in `workspaceId` when the bytes its payer stores, plus those staged - * in any of the payer's workspaces, plus these would pass the payer's storage quota. Holds the + * Refuses staging `bytes` more in `billing`'s workspace when the bytes its payer stores, plus those + * staged in any of the payer's workspaces, plus these would pass the payer's storage quota. Holds the * payer's staging lock until `tx` ends, so concurrent staging in another workspace of the same * payer cannot pass the check together. */ async function assertStagingWithinQuota( tx: DbTransaction, - workspaceId: string, + billing: StorageBillingContext, bytes: number ): Promise { - if (!isStorageEnforcementEnabled()) return - const billing = await resolveStorageBillingContext(workspaceId, tx) const { type, id } = billing.billingEntity await acquireAdvisoryXactLock( tx, @@ -215,6 +210,11 @@ export async function stageBlobs( const keys = new Map() const replaced: string[] = [] let recorded = new Map() + // The payer resolves before the transaction, so its locks are held only for the quota sums. + const billing = + fresh.length > 0 && isStorageEnforcementEnabled() + ? await resolveStorageBillingContext(target.workspaceId) + : null try { for (const blob of fresh) { const key = newStorageKey(target, blob.sha256) @@ -253,7 +253,7 @@ export async function stageBlobs( bytes: fresh.reduce((sum, blob) => sum + blob.bytes.byteLength, 0), } assertStagingFits(await stagedUsage(target, tx), adding) - await assertStagingWithinQuota(tx, target.workspaceId, adding.bytes) + if (billing) await assertStagingWithinQuota(tx, billing, adding.bytes) const hashes = fresh.map((blob) => blob.sha256) // An expired row of the same hash is replaced, so the unique index admits the new one. const expired = await tx diff --git a/packages/workflow-persistence/src/load.ts b/packages/workflow-persistence/src/load.ts index 57afef0d7d6..247a85e0641 100644 --- a/packages/workflow-persistence/src/load.ts +++ b/packages/workflow-persistence/src/load.ts @@ -183,9 +183,8 @@ export async function loadWorkflowsFromNormalizedTablesRaw( * The order a workflow's block, edge or subflow rows load in: creation order. A save stamps the * rows it inserts together a microsecond apart, in the order the state listed them, so this is * that order; rows written in one statement with one timestamp (older saves, a duplicate, a - * paste) keep the order they were inserted in, as the unordered index scan before this returned - * them. The executor reads it for a condition or router edge with no handle, and the editor for - * its node order. + * paste) keep the order they were inserted in. The executor reads it for a condition or router + * edge with no handle, and the editor for its node order. */ export function creationOrder(table: GraphTable) { return [asc(table.createdAt), sql`ctid`] as const From 867a3b2a0ea882f172fdad3f80445dd36e828468 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:37:02 -0800 Subject: [PATCH 37/85] chore: cleanup pass on the DX changes: comments and test audit --- apps/sim/lib/logs/execution/logging-session.ts | 1 - apps/sim/lib/table/application/context.test.ts | 4 +++- apps/sim/lib/workflows/executor/execution-core.ts | 2 +- packages/sim-cli/src/output/github-actions.test.ts | 8 +------- packages/sim-cli/src/output/github-actions.ts | 5 +++-- 5 files changed, 8 insertions(+), 12 deletions(-) diff --git a/apps/sim/lib/logs/execution/logging-session.ts b/apps/sim/lib/logs/execution/logging-session.ts index e461b36d00e..b949f83ae6a 100644 --- a/apps/sim/lib/logs/execution/logging-session.ts +++ b/apps/sim/lib/logs/execution/logging-session.ts @@ -182,7 +182,6 @@ export interface SessionCancelledParams { endedAt?: string totalDurationMs?: number traceSpans?: TraceSpan[] - /** The input the run started with. */ workflowInput?: unknown executionState?: SerializableExecutionState } diff --git a/apps/sim/lib/table/application/context.test.ts b/apps/sim/lib/table/application/context.test.ts index f5d3e484d31..67d2a7a7b8d 100644 --- a/apps/sim/lib/table/application/context.test.ts +++ b/apps/sim/lib/table/application/context.test.ts @@ -97,10 +97,12 @@ describe('table application context', () => { ).rejects.toMatchObject({ code: 'not_found' }) expect(findByName).not.toHaveBeenCalled() - // A name never reaches past the asserted workspace, and without one it is not looked up. + // A name never reaches past the asserted workspace, even if the lookup returned a foreign row. + findByName.mockResolvedValueOnce([{ id: 'table-1', workspaceId: 'workspace-1', name: 'leads' }]) await expect( resolveActiveTableContext({ tableId: 'leads', assertedWorkspaceId: 'workspace-2' }) ).rejects.toMatchObject({ code: 'not_found' }) + expect(findByName).toHaveBeenLastCalledWith('workspace-2', 'leads') findByName.mockClear() await expect(resolveActiveTableContext({ tableId: 'leads' })).rejects.toMatchObject({ code: 'not_found', diff --git a/apps/sim/lib/workflows/executor/execution-core.ts b/apps/sim/lib/workflows/executor/execution-core.ts index 9aaea8aad30..3de1bec9296 100644 --- a/apps/sim/lib/workflows/executor/execution-core.ts +++ b/apps/sim/lib/workflows/executor/execution-core.ts @@ -707,7 +707,7 @@ async function executeWorkflowCoreImpl( } let processedInput = input || {} - /** The input the executor ran with, once the input stage (file fields, PII redaction) finished. */ + // Set once the input stage (file fields, PII redaction) finishes. let executorInput: unknown let deploymentVersionId: string | undefined let loggingStarted = false diff --git a/packages/sim-cli/src/output/github-actions.test.ts b/packages/sim-cli/src/output/github-actions.test.ts index b4a0b4366f1..e7bc1025c52 100644 --- a/packages/sim-cli/src/output/github-actions.test.ts +++ b/packages/sim-cli/src/output/github-actions.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { annotationLine, inGithubActions } from './github-actions' +import { annotationLine } from './github-actions' describe('GitHub Actions workflow commands', () => { it('escapes a message and its properties as the runner unescapes them', () => { @@ -14,10 +14,4 @@ describe('GitHub Actions workflow commands', () => { '::error file=workflows/a%2Cb/workflow.ts,line=3,col=9,title=E_X%3A y::100%25 wrong%0Asecond line' ) }) - - it('emits nothing outside a GitHub Actions job, or with the switch turned off', () => { - expect(inGithubActions({})).toBe(false) - expect(inGithubActions({ GITHUB_ACTIONS: 'false' })).toBe(false) - expect(inGithubActions({ GITHUB_ACTIONS: 'true' })).toBe(true) - }) }) diff --git a/packages/sim-cli/src/output/github-actions.ts b/packages/sim-cli/src/output/github-actions.ts index 1ec21086913..2934822d511 100644 --- a/packages/sim-cli/src/output/github-actions.ts +++ b/packages/sim-cli/src/output/github-actions.ts @@ -67,8 +67,9 @@ export function printAnnotations(lines: readonly string[]): void { } /** - * Appends `markdown()` (built only then) to the job's step summary, when this is a GitHub Actions step that has one. A - * summary that cannot be written is reported and skipped: the command's own result stands. + * Appends `markdown()` (built only then) to the job's step summary, when this is a GitHub Actions + * step that has one. A summary that cannot be written is reported and skipped: the command's own + * result stands. */ export function appendStepSummary( markdown: () => string, From e4ca0181f3bfe6358f6506fbf5f0367aa1a0ae17 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:38:40 -0800 Subject: [PATCH 38/85] chore(workflow-code): tighten comments and prove dry-run create charging by behaviour Replaces the bucket-name assertion test with the plan-budget behaviour test covering dry-run creates, and rewraps the TSDoc the final fixes touched. --- .../[workflowId]/source/route.test.ts | 47 +++++++------------ .../v2/workflows/[workflowId]/source/route.ts | 10 ++-- apps/sim/lib/workflows/api/source-slots.ts | 4 +- .../application/stage-blobs.ts | 7 ++- packages/workflow-persistence/src/save.ts | 4 +- 5 files changed, 29 insertions(+), 43 deletions(-) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts index b71b4976b08..429e10ff8b6 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts @@ -466,34 +466,6 @@ describe('source write rate limit', () => { expect((await GET(request(), context)).status).toBe(200) }) - it('charges a dry run, which writes nothing, to the plan bucket, and a real apply and create to the write bucket', async () => { - const charges = () => - v2RouteMocks.operationRate.mock.calls - .filter(([key]) => String(key).endsWith(':api-key:key-1')) - .map(([key]) => String(key).split(':')[1]) - const create = (query: string) => - CREATE( - new NextRequest( - `http://localhost:3000/api/v2/workspaces/${WORKSPACE_ID}/workflows/source${query}`, - { - method: 'POST', - headers: { 'x-api-key': 'key', 'content-type': 'application/json' }, - body: JSON.stringify({ files: source.files }), - } - ), - { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) } - ) - - expect((await POST(applyRequest(applyBody, '?dryRun=true'), context)).status).toBe(200) - expect((await create('?dryRun=true')).status).toBe(200) - expect(charges()).toEqual(['source.plan', 'source.plan']) - - v2RouteMocks.operationRate.mockClear() - expect((await POST(applyRequest(applyBody), context)).status).toBe(200) - expect((await create('')).status).toBe(200) - expect(charges()).toEqual(['workflows.source.write', 'workflows.source.write']) - }) - it('runs dry runs in plan slots, never in an apply’s: past the plans this server runs at once a dry run answers 429 and a real apply still runs', async () => { const finish: Array<() => void> = [] mocks.apply.mockImplementation(({ input }: { input: { dryRun?: boolean } }) => @@ -581,14 +553,29 @@ describe('source plan budget', () => { mocks.apply.mockResolvedValue({ ...applied, dryRun: true, applied: false }) }) - it('answers 429 to plans well inside the generic budget, and never spends the write budget', async () => { + it('answers 429 to plans well inside the generic budget, and dry-run applies and creates share it, never the write budget', async () => { mocks.apply.mockResolvedValue(applied) + mocks.create.mockResolvedValue(applied) + const create = (query: string) => + CREATE( + new NextRequest( + `http://localhost:3000/api/v2/workspaces/${WORKSPACE_ID}/workflows/source${query}`, + { + method: 'POST', + headers: { 'x-api-key': 'key', 'content-type': 'application/json' }, + body: JSON.stringify({ files: source.files }), + } + ), + { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) } + ) const limitedAt = await writesUntilLimited(plan) expect(limitedAt).not.toBeNull() expect(limitedAt).toBeLessThan(GENERIC_BUDGET) expect((await POST(applyRequest(applyBody, '?dryRun=true'), context)).status).toBe(429) - expect((await POST(applyRequest(applyBody), context)).status).toBe(200) + expect((await create('?dryRun=true')).status).toBe(429) + expect((await POST(applyRequest(applyBody), context)).status).not.toBe(429) + expect((await create('')).status).not.toBe(429) }) it('answers 429 with Retry-After to a plan past the plans this server runs at once', async () => { diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts index c393b80afc0..dde28ae3ea6 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts @@ -47,11 +47,11 @@ export const GET = defineV2JsonRoute({ * all-or-nothing write. Error diagnostics (and a `base` read from another workflow) answer 400, a * stale fingerprint 409, a locked workflow 423; a dry run answers 200 with its diagnostics in the * body. Answers 403 while the `workflow-code` flag is off. Analytics are recorded by the use case. - * Each compiles and diffs a body of up to `SOURCE_REQUEST_MAX_BYTES`, so neither draws on the - * generic budget: a real apply spends the source-write budget and takes an apply slot, and a dry - * run, which writes nothing, the source-plan budget and a plan slot, as the plan route does - * (`v2RateLimits.sourceApply`). A server already running as many as it allows answers 429 with - * `Retry-After`. + * Applies and dry runs each compile and diff a body of up to `SOURCE_REQUEST_MAX_BYTES`, so neither + * draws on the generic budget: a real apply spends the source-write budget and takes an apply slot, + * and a dry run, which writes nothing, the source-plan budget and a plan slot, as the plan route + * does (`v2RateLimits.sourceApply`). A server already running as many as it allows answers 429 + * with `Retry-After`. */ export const POST = defineV2JsonRoute({ contract: v2ApplyWorkflowSourceContract, diff --git a/apps/sim/lib/workflows/api/source-slots.ts b/apps/sim/lib/workflows/api/source-slots.ts index 74c7886370c..7b095a467dc 100644 --- a/apps/sim/lib/workflows/api/source-slots.ts +++ b/apps/sim/lib/workflows/api/source-slots.ts @@ -33,8 +33,8 @@ class SourceSlotBusyError extends Error { * `useCase`, run in one of its lane's slots (`laneOf`, or the lane it picks for the input): a get, * plan or apply (each holds a workflow's or a directory's worth of text, stored state and * canonical forms in memory) waits for nothing, and is refused with a `429` (see - * {@link renderSourceSlotBusy}) when the process already runs - * {@link MAX_CONCURRENT_SOURCE_REQUESTS} of them, so a burst cannot run the process out of memory. + * {@link renderSourceSlotBusy}) when the process already runs {@link MAX_CONCURRENT_SOURCE_REQUESTS} + * of them, so a burst cannot run the process out of memory. */ export function withSourceSlot( useCase: AuthorizingUseCase, diff --git a/apps/sim/lib/workspace-source/application/stage-blobs.ts b/apps/sim/lib/workspace-source/application/stage-blobs.ts index 433c209460c..e65b5bbc89b 100644 --- a/apps/sim/lib/workspace-source/application/stage-blobs.ts +++ b/apps/sim/lib/workspace-source/application/stage-blobs.ts @@ -72,10 +72,9 @@ export interface StageSourceBlobsResult { /** * Stages a batch of blobs: refuses one over `maxBlobBytes`, a batch over the request caps (a single - * blob may fill its request alone), and any - * blob whose bytes do not hash to the SHA-256 it was named by (nothing of the batch is staged), - * then stores the rest within the scope's caps and the payer's storage quota. Staging a blob already - * staged only renews it. + * blob may fill its request alone), and any blob whose bytes do not hash to the SHA-256 it was + * named by (nothing of the batch is staged), then stores the rest within the scope's caps and the + * payer's storage quota. Staging a blob already staged only renews it. */ export const stageSourceBlobs = defineAuthorizedWorkspaceUseCase({ operation: workspaceSourceOperations.stageBlobs, diff --git a/packages/workflow-persistence/src/save.ts b/packages/workflow-persistence/src/save.ts index dccd63f97ab..f5005bf951f 100644 --- a/packages/workflow-persistence/src/save.ts +++ b/packages/workflow-persistence/src/save.ts @@ -213,8 +213,8 @@ function inCreationOrder( * difference is written for blocks and subflows: rows whose stored columns already match are * untouched (keeping their timestamps), changed rows are rewritten, and missing or extra rows are * inserted or deleted, so an edit costs its size rather than the graph's. Edges, which nothing - * references, are left alone when unchanged and in order, and otherwise rewritten whole in the - * state's order. Rows inserted together are stamped in the state's order (see `creationOrder`). + * references, are left alone when unchanged and in order, and otherwise rewritten whole. Rows + * inserted together are stamped in the state's order (see `creationOrder`). * * The stored rows are read `FOR UPDATE`, the rows a delete-all would lock. Writes run in * foreign-key order: an edge is retargeted before the block it left is deleted, so that block's From 2fba0c0566531e768a605ceeafa9a73033c558a2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:54:19 -0800 Subject: [PATCH 39/85] chore(sim-cli): keep the run failure site reader private to its module --- packages/sim-cli/src/commands/protocol/run-source-location.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/run-source-location.ts b/packages/sim-cli/src/commands/protocol/run-source-location.ts index bc0e72a021b..b91668f5640 100644 --- a/packages/sim-cli/src/commands/protocol/run-source-location.ts +++ b/packages/sim-cli/src/commands/protocol/run-source-location.ts @@ -13,7 +13,7 @@ import { blockLabel } from './deployed-urls' import { readPreviousLock, readSourceJson, readSourceText } from './source-dir' /** A failed block, as the source directory names it. */ -export interface RunFailureSite { +interface RunFailureSite { /** The file to open (relative to the working directory): the block's function file, else the entry. */ file: string line: number | null @@ -40,7 +40,7 @@ function declarationLine(entry: string, ident: string): number | null { * Where the run's failure sits in the workflow source directory `dir`: `null` when the error names * no block, the directory holds another workflow's source, or its lock does not bind the block. */ -export async function runFailureSite( +async function runFailureSite( dir: string, workflowId: string, error: unknown From 26b1294c0edccd2f0ff30ba70ed175c0e61f31f3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 03:56:35 -0800 Subject: [PATCH 40/85] chore: regenerate MCP operations and shrink the test-patterns baseline --- apps/sim/lib/api/mcp/generated/v2-operations.ts | 2 +- scripts/test-patterns-baseline.json | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/apps/sim/lib/api/mcp/generated/v2-operations.ts b/apps/sim/lib/api/mcp/generated/v2-operations.ts index 2a032a31641..493e89cac81 100644 --- a/apps/sim/lib/api/mcp/generated/v2-operations.ts +++ b/apps/sim/lib/api/mcp/generated/v2-operations.ts @@ -1379,7 +1379,7 @@ export const V2_MCP_OPERATIONS = { contract: v2FindMissingWorkspaceSourceBlobsContract, summary: 'Find missing workspace source blobs', description: - 'List which binary files of a workspace source directory the caller has not staged in this workspace, by SHA-256, so a client stages only those; an interrupted upload resumes without resending what is already staged. The staged ones are renewed: staged bytes expire a day after they were last staged, checked for, or planned with. Staging is per caller (a person, or one workspace API key). Requires workspace write access. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:write`.', + 'List which binary files of a workspace source directory the caller has not staged in this workspace, by SHA-256, so a client stages only those; an interrupted upload resumes without resending what is already staged. Asking renews nothing: staged bytes expire a day after they were last staged, and one that expires within the hour is listed as missing, so the client stages it again before applying. Staging is per caller (a person, or one workspace API key). Requires workspace write access. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:write`.', handler: () => import('@/app/api/v2/workspaces/[workspaceId]/source/blobs/missing/route').then( (route) => route.POST diff --git a/scripts/test-patterns-baseline.json b/scripts/test-patterns-baseline.json index 5856fb99cf6..1c47a4926af 100644 --- a/scripts/test-patterns-baseline.json +++ b/scripts/test-patterns-baseline.json @@ -143,8 +143,6 @@ "real-wait\tapps/sim/hooks/queries/mothership-chats.test.ts\tsleep() #2", "real-wait\tapps/sim/hooks/queries/organization-accounts.test.tsx\tsleep() #1", "real-wait\tapps/sim/hooks/queries/workflow-mcp-servers.test.tsx\tsleep() #1", - "real-wait\tapps/sim/hooks/queries/workspace-files.test.tsx\tsleep() #1", - "real-wait\tapps/sim/hooks/queries/workspace-files.test.tsx\tsleep() #2", "real-wait\tapps/sim/hooks/queries/workspace.test.tsx\tsleep() #1", "real-wait\tapps/sim/lib/billing/core/reporting-usage-cache.test.ts\tsleep() #1", "real-wait\tapps/sim/lib/billing/core/reporting-usage-cache.test.ts\tsleep() #2", From 4608a7ba51d387352d937dd19e125aa00d787cd1 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:11:27 -0800 Subject: [PATCH 41/85] fix(workflow-code): a source create refused for want of a slot answers 429 with Retry-After, not 500 --- .../workflows/source/route.test.ts | 26 +++++++++++++++++++ apps/sim/lib/workflows/api/route-policies.ts | 5 +++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.test.ts index c527917f2f1..d7b65348312 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.test.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.test.ts @@ -159,6 +159,32 @@ describe('POST /api/v2/workspaces/{workspaceId}/workflows/source', () => { expect(mocks.create).not.toHaveBeenCalled() }) + it('answers 429 with Retry-After once the plans this server runs at once are taken, and still creates for real', async () => { + const finish: Array<() => void> = [] + mocks.create.mockImplementation(({ input }: { input: { dryRun?: boolean } }) => + input.dryRun + ? new Promise((resolve) => + finish.push(() => resolve({ ...created, dryRun: true, applied: false })) + ) + : Promise.resolve(created) + ) + const running = Array.from({ length: 4 }, () => + POST(createRequest({ files }, '?dryRun=true'), context) + ) + await vi.waitFor(() => expect(finish).toHaveLength(4)) + + const refused = await POST(createRequest({ files }, '?dryRun=true'), context) + expect(refused.status).toBe(429) + expect(refused.headers.get('Retry-After')).toBe('5') + expect((await refused.json()).error.code).toBe('RATE_LIMITED') + expect((await POST(createRequest({ files }), context)).status).toBe(200) + + for (const done of finish) done() + expect((await Promise.all(running)).map((response) => response.status)).toEqual([ + 200, 200, 200, 200, + ]) + }) + it('passes dryRun through', async () => { mocks.create.mockResolvedValue({ ...created, dryRun: true, applied: false }) diff --git a/apps/sim/lib/workflows/api/route-policies.ts b/apps/sim/lib/workflows/api/route-policies.ts index 1fd0ca4f39c..6ba5bbaf78a 100644 --- a/apps/sim/lib/workflows/api/route-policies.ts +++ b/apps/sim/lib/workflows/api/route-policies.ts @@ -135,11 +135,14 @@ export const v2WorkflowErrorPolicies = { * Creating a workflow from source: an unreachable workspace is concealed as absent, refused * source answers `400` (`413` for a size limit) with its line-pinned diagnostics, as an apply * does, and a name already taken in the folder answers `409` with `details.code` - * `SOURCE_NAME_TAKEN`, which a client tells apart from a stale apply's `SOURCE_STALE`. + * `SOURCE_NAME_TAKEN`, which a client tells apart from a stale apply's `SOURCE_STALE`. A create + * or dry run refused for want of a slot answers `429` with `Retry-After`, as an apply does. */ concealWorkspaceSourceCreate: createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workspace not found', render(error) { + const busy = renderSourceSlotBusy(error) + if (busy) return busy if (error instanceof WorkflowSourceRejectedError) { return v2ErrorForOrchestration(error.code, error.message, { code: 'SOURCE_REJECTED', From 649b895aba29fecdde4a1e35cd1d3c692ec44a62 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:17:05 -0800 Subject: [PATCH 42/85] fix(workspace-source): a staged blob an apply wrote stops counting toward the storage quota, and an unreadable quota is a 503 --- apps/sim/lib/billing/storage/limits.test.ts | 1 + apps/sim/lib/billing/storage/limits.ts | 3 + .../application/apply-workspace-source.ts | 62 +- .../application/staging.integration.ts | 87 +- .../sim/lib/workspace-source/staging/store.ts | 55 +- .../0469_staged_blob_consumed_at.sql | 4 + .../db/migrations/meta/0469_snapshot.json | 33842 ++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/schema.ts | 5 + .../src/mocks/schema-tables.generated.ts | 1 + 10 files changed, 34039 insertions(+), 28 deletions(-) create mode 100644 packages/db/migrations/0469_staged_blob_consumed_at.sql create mode 100644 packages/db/migrations/meta/0469_snapshot.json diff --git a/apps/sim/lib/billing/storage/limits.test.ts b/apps/sim/lib/billing/storage/limits.test.ts index fe6fbf5f298..905d81fc147 100644 --- a/apps/sim/lib/billing/storage/limits.test.ts +++ b/apps/sim/lib/billing/storage/limits.test.ts @@ -84,6 +84,7 @@ describe('storage limits and quota', () => { currentUsage: 0, error: 'Failed to check storage quota', limit: 0, + unavailable: true, } mockGetHighestPrioritySubscription.mockRejectedValueOnce(new Error('subscription unavailable')) diff --git a/apps/sim/lib/billing/storage/limits.ts b/apps/sim/lib/billing/storage/limits.ts index 2218be61434..4f0625cc7f5 100644 --- a/apps/sim/lib/billing/storage/limits.ts +++ b/apps/sim/lib/billing/storage/limits.ts @@ -57,6 +57,8 @@ interface StorageQuotaSnapshot { interface StorageQuotaResult extends StorageQuotaSnapshot { allowed: boolean error?: string + /** The usage or limit could not be read, so the quota refuses without having been checked. */ + unavailable?: true } type SubscriptionErrorBehavior = 'return-null' | 'throw' @@ -167,6 +169,7 @@ function evaluateStorageQuota( currentUsage: 0, limit: 0, error: 'Failed to check storage quota', + unavailable: true, } } diff --git a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts index ae8924f956d..468c7053b10 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -28,6 +28,7 @@ import { type WorkspaceSourceSubmission, } from '@/lib/workspace-source/application/plan' import { adapterOf } from '@/lib/workspace-source/application/registry' +import { stagingScopeOf } from '@/lib/workspace-source/application/stage-blobs' import type { AppliedResource, ApplyContext, @@ -41,7 +42,12 @@ import { isApplyLeaseLost, WorkspaceSourceBusyError, } from '@/lib/workspace-source/lease/store' -import { readStagedBlob } from '@/lib/workspace-source/staging/store' +import { + markStagedBlobsConsumed, + readStagedBlob, + type StagedBlob, + type StagingScope, +} from '@/lib/workspace-source/staging/store' import { resolveActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' import { ResourceKeyTakenError } from '@/lib/workspaces/resource-keys' @@ -330,16 +336,6 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ } const result = planned(plan, context.workspaceId, false) Object.assign(result.files, plan.reprint) - const writeCtx: ApplyContext = { - ...ctx, - blobs: { - read(path) { - const staged = plan.staged.get(path) - if (!staged) throw new Error('A blob write ran without its staged bytes') - return readStagedBlob(staged) - }, - }, - } const base: WorkspaceBaseV1 = { ...plan.base, resources: { ...plan.base.resources } } for (const change of plan.changes) { if (change.action === 'noop' && change.base) { @@ -348,9 +344,10 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ } const applyId = generateId() result.applyId = applyId - await withAuditCorrelation(applyId, () => - writeAll(plan.changes, writeCtx, lease, base, result) + const consumed = await withAuditCorrelation(applyId, () => + writeAll(plan.changes, ctx, plan.staged, lease, base, result) ) + await consumeStagedBlobs(stagingScopeOf(principal, context.workspaceId), consumed) result.base = base recordWorkspaceSourceApplied(facts, plan.changes, result) logger.info('Applied workspace source', { @@ -385,26 +382,58 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ : [], }) +/** + * Marks the staged blobs the apply wrote as consumed, so the payer's quota stops counting bytes + * the workspace now stores. The writes are already committed, so a failure here is only logged: + * those blobs keep counting until they expire, as they did before an apply consumed any. + */ +async function consumeStagedBlobs(target: StagingScope, consumed: StagedBlob[]): Promise { + try { + await markStagedBlobsConsumed(target, consumed) + } catch (error) { + logger.warn('Could not mark staged blobs consumed', { + workspaceId: target.workspaceId, + error: getErrorMessage(error), + }) + } +} + /** * Writes the plan's changes in write order under `lease`, recording each into `base` and - * `result`; the first failure stops it and is reported as `result.failed`. + * `result`; the first failure stops it and is reported as `result.failed`. Each write reads its + * binary files from `staged`; returns the staged blobs of the writes that succeeded. */ async function writeAll( changes: PlannedChange[], - writeCtx: ApplyContext, + ctx: ApplyContext, + staged: ReadonlyMap, lease: Pick, base: WorkspaceBaseV1, result: ApplyWorkspaceSourceResult -): Promise { +): Promise { // A write re-reports what its plan already found: each finding is listed once, with the ids // the write gave it. const reported = new Map( result.diagnostics.map((diagnostic, at) => [findingIdentity(diagnostic), at]) ) + const consumed: StagedBlob[] = [] for (const change of writeOrder(changes)) { + const read: StagedBlob[] = [] + const writeCtx: ApplyContext = { + ...ctx, + blobs: { + read(path) { + const blob = staged.get(path) + if (!blob) throw new Error('A blob write ran without its staged bytes') + read.push(blob) + return readStagedBlob(blob) + }, + }, + } try { await lease.confirm() const written = await write(change, writeCtx) + consumed.push(...read) Object.assign(result.files, written.text) for (const diagnostic of written.diagnostics ?? []) { const at = reported.get(findingIdentity(diagnostic)) @@ -434,4 +463,5 @@ async function writeAll( break } } + return consumed } diff --git a/apps/sim/lib/workspace-source/application/staging.integration.ts b/apps/sim/lib/workspace-source/application/staging.integration.ts index 0ca806ea8a8..e9df54dd9f2 100644 --- a/apps/sim/lib/workspace-source/application/staging.integration.ts +++ b/apps/sim/lib/workspace-source/application/staging.integration.ts @@ -31,6 +31,29 @@ vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock) vi.mock('@/lib/realtime/notify', () => realtimeNotifyMock) vi.mock('@/lib/posthog/server', () => posthogServerMock) vi.mock('@/lib/uploads/core/setup.server', () => uploadsSetupMock) +/** While `fail` is set, the payer quota check reads its counter through a connection that errors. */ +const quotaReads = vi.hoisted(() => ({ fail: false })) +vi.mock('@/lib/billing/storage/limits', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + checkStorageQuotaForBillingContext: ( + ...[context, bytes, executor]: Parameters + ) => + actual.checkStorageQuotaForBillingContext( + context, + bytes, + quotaReads.fail && executor + ? new Proxy(executor, { + get(target, property) { + if (property === 'select') throw new Error('Connection terminated unexpectedly') + return Reflect.get(target, property) + }, + }) + : executor + ), + } +}) import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server' import { @@ -38,7 +61,9 @@ import { stageSourceBlobs, } from '@/lib/workspace-source/application/stage-blobs' import { + blobManifest, sourceChecks, + sourceRunner, sourceWorkspaces, } from '@/lib/workspace-source/application/workspace-source.test-helpers' import { sweepExpiredStagedBlobs } from '@/lib/workspace-source/staging/store' @@ -53,6 +78,9 @@ const reader = createSessionPrincipal({ userId: readerId, sessionId: generateId( /** A payer of its own, so no other check's staged bytes count toward its storage quota. */ const payerId = generateId() const payer = createSessionPrincipal({ userId: payerId, sessionId: generateId() }) +/** A second payer of its own, whose stored bytes an apply changes. */ +const applierId = generateId() +const applier = createSessionPrincipal({ userId: applierId, sessionId: generateId() }) const { check, writeReport } = sourceChecks( 'WORKSPACE_SOURCE_STAGING_REPORT_PATH', 'workspace-source-staging.json' @@ -143,7 +171,7 @@ beforeAll(async () => { ) const now = new Date() await db.insert(user).values( - [ownerId, writerId, readerId, payerId].map((id) => ({ + [ownerId, writerId, readerId, payerId, applierId].map((id) => ({ id, name: 'Workspace source staging fixture', email: `${id}@workspace-source.invalid`, @@ -158,7 +186,7 @@ afterAll(async () => { await writeReport() resetUploadsSetupMock() await workspaces.cleanup() - await db.delete(user).where(inArray(user.id, [ownerId, writerId, readerId, payerId])) + await db.delete(user).where(inArray(user.id, [ownerId, writerId, readerId, payerId, applierId])) await rm(storageRoot, { recursive: true, force: true }) }) @@ -237,6 +265,61 @@ describe('workspace source staging', () => { } ) + check( + 'a blob an apply wrote stops counting toward the quota, since the workspace now stores it; staging it again counts it again', + async () => { + const quota = 1024 ** 3 + await db + .insert(userStats) + .values({ id: generateId(), userId: applierId, storageUsedBytes: quota - 20 }) + const workspaceId = await workspaces.create({ name: 'Staging consumed', ownerId: applierId }) + const notes = Buffer.from('twelve bytes') + vi.stubEnv('FREE_STORAGE_LIMIT_GB', '1') + try { + const applied = await sourceRunner(['file'], applier).apply(workspaceId, { + files: {}, + blobs: blobManifest({ 'files/notes.txt': notes }, () => true), + }) + expect(applied.failed).toBeUndefined() + const [usage] = await db + .select({ storageUsedBytes: userStats.storageUsedBytes }) + .from(userStats) + .where(eq(userStats.userId, applierId)) + expect(usage.storageUsedBytes).toBe(quota - 20 + notes.byteLength) + + // Stored 8 short of the quota: 6 more fit, unless the 12 applied bytes count twice. + await stage(applier, workspaceId, [blob('six b3')]) + + await stage(applier, workspaceId, [ + { sha256: sha256Hex(notes), size: notes.byteLength, content: notes }, + ]) + const refused = await failure(stage(applier, workspaceId, [blob('1')])) + expect(refused).toMatchObject({ name: 'SourceStagingFullError' }) + } finally { + vi.unstubAllEnvs() + } + } + ) + + check( + 'a quota that cannot be read refuses staging as unavailable, never as a full staging area', + async () => { + const workspaceId = await workspaces.create({ name: 'Staging quota down', ownerId: payerId }) + vi.stubEnv('FREE_STORAGE_LIMIT_GB', '1') + quotaReads.fail = true + try { + const refused = await failure(stage(payer, workspaceId, [blob('quota down')])) + expect(refused).toMatchObject({ code: 'unavailable' }) + expect(refused).not.toMatchObject({ name: 'SourceStagingFullError' }) + expect(await rows(workspaceId)).toEqual([]) + expect(objectsUnder(workspaceId)).toEqual([]) + } finally { + quotaReads.fail = false + vi.unstubAllEnvs() + } + } + ) + check('bytes that do not hash to their name refuse the whole batch, nothing stored', async () => { const workspaceId = await newWorkspace() const good = blob('good bytes') diff --git a/apps/sim/lib/workspace-source/staging/store.ts b/apps/sim/lib/workspace-source/staging/store.ts index 9cd88cd570f..1e4e979f3a2 100644 --- a/apps/sim/lib/workspace-source/staging/store.ts +++ b/apps/sim/lib/workspace-source/staging/store.ts @@ -5,7 +5,9 @@ * size, storage key and expiry; the bytes live in object storage under the workspace's prefix. * Only staging (sending the bytes) sets the expiry: looking blobs up or planning with them never * extends it. While held, staged bytes count against the workspace payer's storage quota, on top - * of what the payer already stores, so staging can never hold more than the quota leaves. + * of what the payer already stores, so staging can never hold more than the quota leaves; once an + * apply writes a blob into the workspace (which then stores and charges for it), it is consumed and + * stops counting, though it stays staged until it expires, so applying it again uploads nothing. * Callers pass canonical ids and a scope string, never a principal: the use cases in * `application/stage-blobs.ts` authorize first. */ @@ -15,7 +17,7 @@ import { createLogger } from '@sim/logger' import { sha256Hex } from '@sim/security/hash' import { generateId, generateShortId } from '@sim/utils/id' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' -import { and, asc, eq, gt, inArray, lt, lte, notInArray, sql } from 'drizzle-orm' +import { and, asc, eq, gt, inArray, isNull, lt, lte, notInArray, sql } from 'drizzle-orm' import { workspacesPaidBy } from '@/lib/billing/core/payer-context' import type { BillingEntity } from '@/lib/billing/core/usage-log' import { @@ -121,8 +123,8 @@ export async function stagedUsage( } /** - * The bytes staged (unexpired) in every workspace `payer` pays for, across callers: what staging - * holds against the payer's storage quota. + * The bytes staged (unexpired, and not yet written by an apply) in every workspace `payer` pays + * for, across callers: what staging holds against the payer's storage quota. */ async function payerStagedBytes(tx: DbTransaction, payer: BillingEntity): Promise { const [usage] = await tx @@ -131,7 +133,13 @@ async function payerStagedBytes(tx: DbTransaction, payer: BillingEntity): Promis }) .from(workspaceSourceStagedBlob) .innerJoin(workspace, eq(workspace.id, workspaceSourceStagedBlob.workspaceId)) - .where(and(gt(workspaceSourceStagedBlob.expiresAt, new Date()), workspacesPaidBy(payer))) + .where( + and( + gt(workspaceSourceStagedBlob.expiresAt, new Date()), + isNull(workspaceSourceStagedBlob.consumedAt), + workspacesPaidBy(payer) + ) + ) return Number(usage?.bytes ?? 0) } @@ -139,7 +147,8 @@ async function payerStagedBytes(tx: DbTransaction, payer: BillingEntity): Promis * Refuses staging `bytes` more in `billing`'s workspace when the bytes its payer stores, plus those * staged in any of the payer's workspaces, plus these would pass the payer's storage quota. Holds the * payer's staging lock until `tx` ends, so concurrent staging in another workspace of the same - * payer cannot pass the check together. + * payer cannot pass the check together. A quota that could not be read is a `503`, never + * {@link SourceStagingFullError}, which a client takes as permanent. */ async function assertStagingWithinQuota( tx: DbTransaction, @@ -157,9 +166,15 @@ async function assertStagingWithinQuota( (await payerStagedBytes(tx, billing.billingEntity)) + bytes, tx ) + if (quota.unavailable) { + throw new OrchestrationError( + 'unavailable', + 'Could not check the storage quota for staging; retry shortly.' + ) + } if (!quota.allowed) { throw new SourceStagingFullError( - `${quota.error ?? 'Storage limit exceeded'}. Staged files count toward storage until they expire, a day after they were last staged.` + `${quota.error ?? 'Storage limit exceeded'}. Staged files count toward storage until an apply writes them or they expire, a day after they were last staged.` ) } } @@ -198,7 +213,7 @@ export function assertStagingFits( * Stages `blobs` (bytes the caller already hashed): writes each one not yet staged to storage, * then records them under one lock on the scope, refusing a batch that would pass the caps or the * payer's storage quota (and removing the objects it wrote). A blob already staged is not written - * again: sending its bytes renews it. + * again: sending its bytes renews it, and counts it toward the quota again if an apply consumed it. */ export async function stageBlobs( target: StagingScope, @@ -238,7 +253,7 @@ export async function stageBlobs( if (known.size > 0) { await tx .update(workspaceSourceStagedBlob) - .set({ expiresAt: expiry() }) + .set({ expiresAt: expiry(), consumedAt: null }) .where( and( inScope(target), @@ -287,7 +302,7 @@ export async function stageBlobs( workspaceSourceStagedBlob.scope, workspaceSourceStagedBlob.sha256, ], - set: { expiresAt: expiry() }, + set: { expiresAt: expiry(), consumedAt: null }, }) .returning({ sha256: workspaceSourceStagedBlob.sha256, @@ -306,6 +321,26 @@ export async function stageBlobs( }) } +/** + * Marks `blobs` consumed: an apply wrote their bytes into the workspace, which now charges for + * them, so they no longer count toward the payer's quota. They stay staged until they expire. + */ +export async function markStagedBlobsConsumed( + target: StagingScope, + blobs: readonly StagedBlob[] +): Promise { + if (blobs.length === 0) return + await db + .update(workspaceSourceStagedBlob) + .set({ consumedAt: new Date() }) + .where( + and( + inScope(target), + inArray(workspaceSourceStagedBlob.storageKey, [...new Set(blobs.map((b) => b.storageKey))]) + ) + ) +} + async function removeObjects(keys: string[]): Promise { if (keys.length === 0) return const { failed } = await deleteFiles(keys, STORAGE_CONTEXT) diff --git a/packages/db/migrations/0469_staged_blob_consumed_at.sql b/packages/db/migrations/0469_staged_blob_consumed_at.sql new file mode 100644 index 00000000000..92085519d49 --- /dev/null +++ b/packages/db/migrations/0469_staged_blob_consumed_at.sql @@ -0,0 +1,4 @@ +-- Marks a staged workspace source blob an apply has written into the workspace, so its bytes stop +-- counting toward the payer's storage quota a second time. Nullable with no default: adding it +-- rewrites no rows, and the app version already deployed neither reads nor writes it. +ALTER TABLE "workspace_source_staged_blob" ADD COLUMN "consumed_at" timestamp; diff --git a/packages/db/migrations/meta/0469_snapshot.json b/packages/db/migrations/meta/0469_snapshot.json new file mode 100644 index 00000000000..e92186cf2f8 --- /dev/null +++ b/packages/db/migrations/meta/0469_snapshot.json @@ -0,0 +1,33842 @@ +{ + "id": "8ec189d5-1621-46b4-aca4-fb233e6c0ee4", + "prevId": "a1b3663b-3dfd-49e3-827c-0fd434224001", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config": { + "name": "oauth_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_at": { + "name": "refresh_revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_code": { + "name": "refresh_revoked_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_token_hash": { + "name": "refresh_revoked_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "account_user_id_idx": { + "name": "account_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_account_on_account_id_provider_id": { + "name": "idx_account_on_account_id_provider_id", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_blocked": { + "name": "activity_rollup_blocked", + "schema": "", + "columns": { + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": true, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "retry_at": { + "name": "retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_dirty": { + "name": "activity_rollup_dirty", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "due_at": { + "name": "due_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "activity_rollup_dirty_due_at_idx": { + "name": "activity_rollup_dirty_due_at_idx", + "columns": [ + { + "expression": "due_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "activity_rollup_dirty_workspace_id_bucket_start_pk": { + "name": "activity_rollup_dirty_workspace_id_bucket_start_pk", + "columns": ["workspace_id", "bucket_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_inflight": { + "name": "activity_rollup_inflight", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "next_check_at": { + "name": "next_check_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "activity_rollup_inflight_next_check_at_idx": { + "name": "activity_rollup_inflight_next_check_at_idx", + "columns": [ + { + "expression": "next_check_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "activity_rollup_inflight_workspace_id_bucket_start_pk": { + "name": "activity_rollup_inflight_workspace_id_bucket_start_pk", + "columns": ["workspace_id", "bucket_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_state": { + "name": "activity_rollup_state", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "coverage_start": { + "name": "coverage_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "fresh_through": { + "name": "fresh_through", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "backfill_completed_at": { + "name": "backfill_completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_end_scan": { + "name": "last_end_scan", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "lease_owner": { + "name": "lease_owner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "housekeeping_at": { + "name": "housekeeping_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "maintained_at": { + "name": "maintained_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "failed_passes": { + "name": "failed_passes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "corrections_at": { + "name": "corrections_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_memory_turn": { + "name": "agent_memory_turn", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_order": { + "name": "execution_order", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "encrypted_state": { + "name": "encrypted_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "agent_memory_turn_invocation_unique": { + "name": "agent_memory_turn_invocation_unique", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "node_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_memory_turn_workflow_idx": { + "name": "agent_memory_turn_workflow_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "agent_memory_turn_memory_id_memory_id_fk": { + "name": "agent_memory_turn_memory_id_memory_id_fk", + "tableFrom": "agent_memory_turn", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "agent_memory_turn_workflow_id_workflow_id_fk": { + "name": "agent_memory_turn_workflow_id_workflow_id_fk", + "tableFrom": "agent_memory_turn", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.api_key": { + "name": "api_key", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key_hash": { + "name": "key_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'personal'" + }, + "access": { + "name": "access", + "type": "api_key_access", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'write'" + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "api_key_workspace_type_idx": { + "name": "api_key_workspace_type_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "api_key_user_type_idx": { + "name": "api_key_user_type_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "api_key_key_hash_idx": { + "name": "api_key_key_hash_idx", + "columns": [ + { + "expression": "key_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "api_key_user_id_user_id_fk": { + "name": "api_key_user_id_user_id_fk", + "tableFrom": "api_key", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "api_key_workspace_id_workspace_id_fk": { + "name": "api_key_workspace_id_workspace_id_fk", + "tableFrom": "api_key", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "api_key_created_by_user_id_fk": { + "name": "api_key_created_by_user_id_fk", + "tableFrom": "api_key", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "api_key_key_unique": { + "name": "api_key_key_unique", + "nullsNotDistinct": false, + "columns": ["key"] + } + }, + "policies": {}, + "checkConstraints": { + "workspace_type_check": { + "name": "workspace_type_check", + "value": "(type = 'workspace' AND workspace_id IS NOT NULL) OR (type = 'personal' AND workspace_id IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.assistant_tool_permission": { + "name": "assistant_tool_permission", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "read_policy": { + "name": "read_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'allow'" + }, + "write_policy": { + "name": "write_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'ask'" + }, + "overrides": { + "name": "overrides", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "assistant_tool_permission_credential_idx": { + "name": "assistant_tool_permission_credential_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "assistant_tool_permission_user_idx": { + "name": "assistant_tool_permission_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assistant_tool_permission_organization_id_organization_id_fk": { + "name": "assistant_tool_permission_organization_id_organization_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_tool_permission_user_id_user_id_fk": { + "name": "assistant_tool_permission_user_id_user_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_tool_permission_credential_id_credential_id_fk": { + "name": "assistant_tool_permission_credential_id_credential_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "assistant_tool_permission_organization_id_user_id_credential_id_pk": { + "name": "assistant_tool_permission_organization_id_user_id_credential_id_pk", + "columns": ["organization_id", "user_id", "credential_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "assistant_tool_permission_policy_check": { + "name": "assistant_tool_permission_policy_check", + "value": "\"assistant_tool_permission\".\"read_policy\" IN ('allow', 'ask', 'block') AND \"assistant_tool_permission\".\"write_policy\" IN ('allow', 'ask', 'block')" + }, + "assistant_tool_permission_revision_check": { + "name": "assistant_tool_permission_revision_check", + "value": "\"assistant_tool_permission\".\"revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.async_jobs": { + "name": "async_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_at": { + "name": "run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 3 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "async_jobs_status_started_at_idx": { + "name": "async_jobs_status_started_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_status_completed_at_idx": { + "name": "async_jobs_status_completed_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "completed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_pending_run_at_idx": { + "name": "async_jobs_schedule_pending_run_at_idx", + "columns": [ + { + "expression": "run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_processing_started_at_idx": { + "name": "async_jobs_schedule_processing_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" = 'processing'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_unreconciled_terminal_idx": { + "name": "async_jobs_schedule_unreconciled_terminal_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" IN ('completed', 'failed', 'cancelled') AND COALESCE(\"async_jobs\".\"metadata\" ->> 'scheduleReconciled', 'false') <> 'true'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.audit_log": { + "name": "audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_email": { + "name": "actor_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_name": { + "name": "resource_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "audit_log_workspace_created_idx": { + "name": "audit_log_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_workspace_created_at_id_idx": { + "name": "audit_log_workspace_created_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_actor_created_idx": { + "name": "audit_log_actor_created_idx", + "columns": [ + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_org_level_created_at_id_idx": { + "name": "audit_log_org_level_created_at_id_idx", + "columns": [ + { + "expression": "(\"metadata\"->>'organizationId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"audit_log\".\"workspace_id\" IS NULL AND (\"audit_log\".\"metadata\"->>'organizationId') IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "audit_log_resource_idx": { + "name": "audit_log_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_action_idx": { + "name": "audit_log_action_idx", + "columns": [ + { + "expression": "action", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "audit_log_workspace_id_workspace_id_fk": { + "name": "audit_log_workspace_id_workspace_id_fk", + "tableFrom": "audit_log", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "audit_log_actor_id_user_id_fk": { + "name": "audit_log_actor_id_user_id_fk", + "tableFrom": "audit_log", + "tableTo": "user", + "columnsFrom": ["actor_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_license": { + "name": "aws_marketplace_license", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "license_arn": { + "name": "license_arn", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "product_code": { + "name": "product_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "customer_aws_account_id": { + "name": "customer_aws_account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agreement_id": { + "name": "agreement_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agreement_seen_at": { + "name": "agreement_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "renewed_agreement_id": { + "name": "renewed_agreement_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "aws_marketplace_license_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_verified_at": { + "name": "last_verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "last_verification_attempt_at": { + "name": "last_verification_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "license_event_received_at": { + "name": "license_event_received_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "claim_token_hash": { + "name": "claim_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_expires_at": { + "name": "claim_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "linked_by_user_id": { + "name": "linked_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_linked_at": { + "name": "organization_linked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "contact_email": { + "name": "contact_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "company_name": { + "name": "company_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "aws_marketplace_license_arn_unique": { + "name": "aws_marketplace_license_arn_unique", + "columns": [ + { + "expression": "license_arn", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_claim_token_hash_unique": { + "name": "aws_marketplace_license_claim_token_hash_unique", + "columns": [ + { + "expression": "claim_token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_agreement_id_idx": { + "name": "aws_marketplace_license_agreement_id_idx", + "columns": [ + { + "expression": "agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_renewed_agreement_id_idx": { + "name": "aws_marketplace_license_renewed_agreement_id_idx", + "columns": [ + { + "expression": "renewed_agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_account_product_idx": { + "name": "aws_marketplace_license_account_product_idx", + "columns": [ + { + "expression": "customer_aws_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "product_code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_last_attempt_idx": { + "name": "aws_marketplace_license_last_attempt_idx", + "columns": [ + { + "expression": "last_verification_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_organization_id_idx": { + "name": "aws_marketplace_license_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_linked_by_user_id_idx": { + "name": "aws_marketplace_license_linked_by_user_id_idx", + "columns": [ + { + "expression": "linked_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "aws_marketplace_license_organization_id_organization_id_fk": { + "name": "aws_marketplace_license_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_license", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "aws_marketplace_license_linked_by_user_id_user_id_fk": { + "name": "aws_marketplace_license_linked_by_user_id_user_id_fk", + "tableFrom": "aws_marketplace_license", + "tableTo": "user", + "columnsFrom": ["linked_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_usage_report": { + "name": "aws_marketplace_usage_report", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "license_id": { + "name": "license_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hour_start": { + "name": "hour_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "aws_marketplace_usage_report_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "metering_record_id": { + "name": "metering_record_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reported_at": { + "name": "reported_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "aws_marketplace_usage_report_license_dimension_hour_unique": { + "name": "aws_marketplace_usage_report_license_dimension_hour_unique", + "columns": [ + { + "expression": "license_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dimension", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "hour_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_usage_report_status_hour_idx": { + "name": "aws_marketplace_usage_report_status_hour_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "hour_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_usage_report_organization_id_idx": { + "name": "aws_marketplace_usage_report_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "aws_marketplace_usage_report_organization_id_organization_id_fk": { + "name": "aws_marketplace_usage_report_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_usage_report", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "aws_marketplace_usage_report_license_id_aws_marketplace_license_id_fk": { + "name": "aws_marketplace_usage_report_license_id_aws_marketplace_license_id_fk", + "tableFrom": "aws_marketplace_usage_report", + "tableTo": "aws_marketplace_license", + "columnsFrom": ["license_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_usage_tally": { + "name": "aws_marketplace_usage_tally", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "period_start": { + "name": "period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "counted_from": { + "name": "counted_from", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "cost_usd": { + "name": "cost_usd", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "units": { + "name": "units", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "aws_marketplace_usage_tally_organization_id_organization_id_fk": { + "name": "aws_marketplace_usage_tally_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_usage_tally", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "aws_marketplace_usage_tally_organization_id_dimension_period_start_pk": { + "name": "aws_marketplace_usage_tally_organization_id_dimension_period_start_pk", + "columns": ["organization_id", "dimension", "period_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.background_work_status": { + "name": "background_work_status", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "background_work_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "background_work_status_value", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "background_work_status_workspace_status_idx": { + "name": "background_work_status_workspace_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_workflow_status_idx": { + "name": "background_work_status_workflow_status_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_meta_child_ws_idx": { + "name": "background_work_status_meta_child_ws_idx", + "columns": [ + { + "expression": "(\"metadata\" ->> 'childWorkspaceId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_meta_other_ws_idx": { + "name": "background_work_status_meta_other_ws_idx", + "columns": [ + { + "expression": "(\"metadata\" ->> 'otherWorkspaceId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "background_work_status_workspace_id_workspace_id_fk": { + "name": "background_work_status_workspace_id_workspace_id_fk", + "tableFrom": "background_work_status", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "background_work_status_workflow_id_workflow_id_fk": { + "name": "background_work_status_workflow_id_workflow_id_fk", + "tableFrom": "background_work_status", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.changelog_change": { + "name": "changelog_change", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "release_id": { + "name": "release_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "changelog_change_release_position_unique": { + "name": "changelog_change_release_position_unique", + "columns": [ + { + "expression": "release_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "changelog_change_release_id_changelog_release_id_fk": { + "name": "changelog_change_release_id_changelog_release_id_fk", + "tableFrom": "changelog_change", + "tableTo": "changelog_release", + "columnsFrom": ["release_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "changelog_change_workflow_id_workflow_id_fk": { + "name": "changelog_change_workflow_id_workflow_id_fk", + "tableFrom": "changelog_change", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_change_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "changelog_change_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "changelog_change", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_change_chat_id_copilot_chats_id_fk": { + "name": "changelog_change_chat_id_copilot_chats_id_fk", + "tableFrom": "changelog_change", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.changelog_release": { + "name": "changelog_release", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version_major": { + "name": "version_major", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version_minor": { + "name": "version_minor", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version_patch": { + "name": "version_patch", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "bump_reason": { + "name": "bump_reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body_file_id": { + "name": "body_file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "published_at": { + "name": "published_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "changelog_release_workspace_version_unique": { + "name": "changelog_release_workspace_version_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_major", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_minor", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_patch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "changelog_release_body_file_unique": { + "name": "changelog_release_body_file_unique", + "columns": [ + { + "expression": "body_file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "changelog_release_workspace_published_idx": { + "name": "changelog_release_workspace_published_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "published_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "changelog_release_workspace_id_workspace_id_fk": { + "name": "changelog_release_workspace_id_workspace_id_fk", + "tableFrom": "changelog_release", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "changelog_release_body_file_id_workspace_files_id_fk": { + "name": "changelog_release_body_file_id_workspace_files_id_fk", + "tableFrom": "changelog_release", + "tableTo": "workspace_files", + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "changelog_release_created_by_user_id_fk": { + "name": "changelog_release_created_by_user_id_fk", + "tableFrom": "changelog_release", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_release_updated_by_user_id_fk": { + "name": "changelog_release_updated_by_user_id_fk", + "tableFrom": "changelog_release", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "changelog_release_version_check": { + "name": "changelog_release_version_check", + "value": "\"changelog_release\".\"version_major\" >= 0 AND \"changelog_release\".\"version_minor\" >= 0 AND \"changelog_release\".\"version_patch\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.chat": { + "name": "chat", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "customizations": { + "name": "customizations", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_emails": { + "name": "allowed_emails", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "output_configs": { + "name": "output_configs", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "include_thinking": { + "name": "include_thinking", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "include_tool_calls": { + "name": "include_tool_calls", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "identifier_idx": { + "name": "identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"chat\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_archived_at_partial_idx": { + "name": "chat_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_chat_on_workflow_id_archived_at": { + "name": "idx_chat_on_workflow_id_archived_at", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_user_id_idx": { + "name": "chat_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_workflow_id_workflow_id_fk": { + "name": "chat_workflow_id_workflow_id_fk", + "tableFrom": "chat", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_user_id_user_id_fk": { + "name": "chat_user_id_user_id_fk", + "tableFrom": "chat", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.client_credential_token": { + "name": "client_credential_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "encrypted_value": { + "name": "encrypted_value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token_digest": { + "name": "access_token_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "client_credential_token_expires_at_idx": { + "name": "client_credential_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"client_credential_token\".\"access_token_digest\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "client_credential_token_access_token_digest_idx": { + "name": "client_credential_token_access_token_digest_idx", + "columns": [ + { + "expression": "access_token_digest", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"client_credential_token\".\"access_token_digest\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_async_tool_calls": { + "name": "copilot_async_tool_calls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "checkpoint_id": { + "name": "checkpoint_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "tool_call_id": { + "name": "tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "args": { + "name": "args", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "executable_name": { + "name": "executable_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_workspace_id": { + "name": "target_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_args": { + "name": "approved_args", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "assistant_action": { + "name": "assistant_action", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "execution_retryable": { + "name": "execution_retryable", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "status": { + "name": "status", + "type": "copilot_async_tool_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "result": { + "name": "result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_decision": { + "name": "permission_decision", + "type": "copilot_tool_permission_decision", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "permission_decided_at": { + "name": "permission_decided_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_requested_at": { + "name": "permission_requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "pickup_deadline_at": { + "name": "pickup_deadline_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "persist_seq": { + "name": "persist_seq", + "type": "bigint", + "primaryKey": false, + "notNull": false, + "default": "nextval('copilot_async_tool_calls_persist_seq')" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "claimed_by": { + "name": "claimed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "browser_download_started_at": { + "name": "browser_download_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_started_at": { + "name": "execution_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_settled_at": { + "name": "execution_settled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_owner_token": { + "name": "execution_owner_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_lease_expires_at": { + "name": "execution_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execution_revoked_at": { + "name": "execution_revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execution_attempts": { + "name": "execution_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "execution_deadline_at": { + "name": "execution_deadline_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "client_workflow_execution_id": { + "name": "client_workflow_execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sandbox_processes": { + "name": "sandbox_processes", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_async_tool_calls_checkpoint_id_idx": { + "name": "copilot_async_tool_calls_checkpoint_id_idx", + "columns": [ + { + "expression": "checkpoint_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_status_idx": { + "name": "copilot_async_tool_calls_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_run_status_idx": { + "name": "copilot_async_tool_calls_run_status_idx", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_tool_call_id_unique": { + "name": "copilot_async_tool_calls_tool_call_id_unique", + "columns": [ + { + "expression": "tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_async_tool_calls_run_id_copilot_runs_id_fk": { + "name": "copilot_async_tool_calls_run_id_copilot_runs_id_fk", + "tableFrom": "copilot_async_tool_calls", + "tableTo": "copilot_runs", + "columnsFrom": ["run_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_async_tool_calls_checkpoint_id_copilot_run_checkpoints_id_fk": { + "name": "copilot_async_tool_calls_checkpoint_id_copilot_run_checkpoints_id_fk", + "tableFrom": "copilot_async_tool_calls", + "tableTo": "copilot_run_checkpoints", + "columnsFrom": ["checkpoint_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_chats": { + "name": "copilot_chats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "memory_space_id": { + "name": "memory_space_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "chat_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'copilot'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude-3-7-sonnet-latest'" + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_conversation_key": { + "name": "external_conversation_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_conversation_metadata": { + "name": "external_conversation_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "preview_yaml": { + "name": "preview_yaml", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "resources": { + "name": "resources", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "auto_allowed_tools": { + "name": "auto_allowed_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "pinned": { + "name": "pinned", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_chats_organization_id_idx": { + "name": "copilot_chats_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_external_conversation_unique": { + "name": "copilot_chats_external_conversation_unique", + "columns": [ + { + "expression": "external_conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"copilot_chats\".\"external_conversation_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_org_created_idx": { + "name": "copilot_chats_user_org_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_workflow_id_idx": { + "name": "copilot_chats_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workflow_idx": { + "name": "copilot_chats_user_workflow_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workspace_idx": { + "name": "copilot_chats_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_created_at_idx": { + "name": "copilot_chats_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_updated_at_idx": { + "name": "copilot_chats_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_workspace_created_at_id_idx": { + "name": "copilot_chats_workspace_created_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workspace_deleted_partial_idx": { + "name": "copilot_chats_user_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_chats\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_chats_user_id_user_id_fk": { + "name": "copilot_chats_user_id_user_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_workflow_id_workflow_id_fk": { + "name": "copilot_chats_workflow_id_workflow_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_workspace_id_workspace_id_fk": { + "name": "copilot_chats_workspace_id_workspace_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_organization_id_organization_id_fk": { + "name": "copilot_chats_organization_id_organization_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "copilot_chats_owner_check": { + "name": "copilot_chats_owner_check", + "value": "num_nonnulls(\"copilot_chats\".\"workspace_id\", \"copilot_chats\".\"organization_id\") <= 1" + }, + "copilot_chats_organization_workflow_check": { + "name": "copilot_chats_organization_workflow_check", + "value": "\"copilot_chats\".\"organization_id\" IS NULL OR \"copilot_chats\".\"workflow_id\" IS NULL" + } + }, + "isRLSEnabled": false + }, + "public.copilot_feedback": { + "name": "copilot_feedback", + "schema": "", + "columns": { + "feedback_id": { + "name": "feedback_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_query": { + "name": "user_query", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent_response": { + "name": "agent_response", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_positive": { + "name": "is_positive", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "feedback": { + "name": "feedback", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_yaml": { + "name": "workflow_yaml", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_feedback_user_id_idx": { + "name": "copilot_feedback_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_chat_id_idx": { + "name": "copilot_feedback_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_user_chat_idx": { + "name": "copilot_feedback_user_chat_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_is_positive_idx": { + "name": "copilot_feedback_is_positive_idx", + "columns": [ + { + "expression": "is_positive", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_created_at_idx": { + "name": "copilot_feedback_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_feedback_user_id_user_id_fk": { + "name": "copilot_feedback_user_id_user_id_fk", + "tableFrom": "copilot_feedback", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_feedback_chat_id_copilot_chats_id_fk": { + "name": "copilot_feedback_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_feedback", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_messages": { + "name": "copilot_messages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "display_content": { + "name": "display_content", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_messages_chat_message_unique": { + "name": "copilot_messages_chat_message_unique", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_created_at_idx": { + "name": "copilot_messages_chat_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_seq_idx": { + "name": "copilot_messages_chat_seq_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_stream_idx": { + "name": "copilot_messages_chat_stream_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "stream_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"stream_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_user_created_at_idx": { + "name": "copilot_messages_user_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user' AND \"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_messages_chat_id_copilot_chats_id_fk": { + "name": "copilot_messages_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_messages", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_organization_request_stops": { + "name": "copilot_organization_request_stops", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stopped_at": { + "name": "stopped_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "copilot_organization_request_stops_user_id_user_id_fk": { + "name": "copilot_organization_request_stops_user_id_user_id_fk", + "tableFrom": "copilot_organization_request_stops", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_organization_request_stops_organization_id_organization_id_fk": { + "name": "copilot_organization_request_stops_organization_id_organization_id_fk", + "tableFrom": "copilot_organization_request_stops", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "copilot_organization_request_stops_user_id_organization_id_stream_id_pk": { + "name": "copilot_organization_request_stops_user_id_organization_id_stream_id_pk", + "columns": ["user_id", "organization_id", "stream_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_request_stops": { + "name": "copilot_request_stops", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stopped_at": { + "name": "stopped_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "copilot_request_stops_user_id_user_id_fk": { + "name": "copilot_request_stops_user_id_user_id_fk", + "tableFrom": "copilot_request_stops", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_request_stops_workspace_id_workspace_id_fk": { + "name": "copilot_request_stops_workspace_id_workspace_id_fk", + "tableFrom": "copilot_request_stops", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "copilot_request_stops_user_id_workspace_id_stream_id_pk": { + "name": "copilot_request_stops_user_id_workspace_id_stream_id_pk", + "columns": ["user_id", "workspace_id", "stream_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_run_checkpoints": { + "name": "copilot_run_checkpoints", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "pending_tool_call_id": { + "name": "pending_tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "conversation_snapshot": { + "name": "conversation_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "agent_state": { + "name": "agent_state", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "provider_request": { + "name": "provider_request", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_run_checkpoints_pending_tool_call_id_idx": { + "name": "copilot_run_checkpoints_pending_tool_call_id_idx", + "columns": [ + { + "expression": "pending_tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_run_checkpoints_run_pending_tool_unique": { + "name": "copilot_run_checkpoints_run_pending_tool_unique", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "pending_tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_run_checkpoints_run_id_copilot_runs_id_fk": { + "name": "copilot_run_checkpoints_run_id_copilot_runs_id_fk", + "tableFrom": "copilot_run_checkpoints", + "tableTo": "copilot_runs", + "columnsFrom": ["run_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_runs": { + "name": "copilot_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_execution_version": { + "name": "tool_execution_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tool_admission_closed_at": { + "name": "tool_admission_closed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "parent_run_id": { + "name": "parent_run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agent": { + "name": "agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "copilot_run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "request_context": { + "name": "request_context", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "desktop_device_id": { + "name": "desktop_device_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "copilot_runs_parent_run_id_idx": { + "name": "copilot_runs_parent_run_id_idx", + "columns": [ + { + "expression": "parent_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_chat_started_at_idx": { + "name": "copilot_runs_chat_started_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_user_id_idx": { + "name": "copilot_runs_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_workflow_id_idx": { + "name": "copilot_runs_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_status_idx": { + "name": "copilot_runs_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_chat_execution_idx": { + "name": "copilot_runs_chat_execution_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_execution_started_at_idx": { + "name": "copilot_runs_execution_started_at_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_workspace_completed_at_id_idx": { + "name": "copilot_runs_workspace_completed_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"completed_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_stream_id_unique": { + "name": "copilot_runs_stream_id_unique", + "columns": [ + { + "expression": "stream_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_desktop_device_started_at_idx": { + "name": "copilot_runs_desktop_device_started_at_idx", + "columns": [ + { + "expression": "desktop_device_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_runs\".\"desktop_device_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_runs_chat_id_copilot_chats_id_fk": { + "name": "copilot_runs_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_user_id_user_id_fk": { + "name": "copilot_runs_user_id_user_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_workflow_id_workflow_id_fk": { + "name": "copilot_runs_workflow_id_workflow_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_workspace_id_workspace_id_fk": { + "name": "copilot_runs_workspace_id_workspace_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_organization_id_organization_id_fk": { + "name": "copilot_runs_organization_id_organization_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_desktop_device_id_desktop_devices_id_fk": { + "name": "copilot_runs_desktop_device_id_desktop_devices_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "desktop_devices", + "columnsFrom": ["desktop_device_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_service_usage": { + "name": "copilot_service_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tool_call_id": { + "name": "tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "service": { + "name": "service", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cost_usd": { + "name": "cost_usd", + "type": "numeric(12, 8)", + "primaryKey": false, + "notNull": false + }, + "worker_origin": { + "name": "worker_origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "delivered_at": { + "name": "delivered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "copilot_service_usage_pending_idx": { + "name": "copilot_service_usage_pending_idx", + "columns": [ + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "delivered_at IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.credential": { + "name": "credential", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "slack_app_id": { + "name": "slack_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "credential_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "unredacted": { + "name": "unredacted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_key": { + "name": "env_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_owner_user_id": { + "name": "env_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_service_account_key": { + "name": "encrypted_service_account_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_personal_token": { + "name": "encrypted_personal_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "authorization_app_id": { + "name": "authorization_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_enrollment_id": { + "name": "credential_group_enrollment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_option_id": { + "name": "credential_group_option_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_server_id": { + "name": "mcp_server_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_oauth_config_version": { + "name": "mcp_oauth_config_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "managed_oauth_scope_version": { + "name": "managed_oauth_scope_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "provider_subject_id": { + "name": "provider_subject_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_tenant_id": { + "name": "provider_tenant_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "managed_oauth_status": { + "name": "managed_oauth_status", + "type": "managed_oauth_credential_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "granted_scopes": { + "name": "granted_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "provider_metadata": { + "name": "provider_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "encrypted_oauth_token_set": { + "name": "encrypted_oauth_token_set", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_tools": { + "name": "mcp_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "mcp_tools_refreshed_at": { + "name": "mcp_tools_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_refreshed_at": { + "name": "last_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_organization_id_idx": { + "name": "credential_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_organization_account_unique": { + "name": "credential_organization_account_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"account_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_org_personal_token_unique": { + "name": "credential_org_personal_token_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'personal_token'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_id_idx": { + "name": "credential_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_type_idx": { + "name": "credential_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_provider_id_idx": { + "name": "credential_provider_id_idx", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_account_id_idx": { + "name": "credential_account_id_idx", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_env_owner_user_id_idx": { + "name": "credential_env_owner_user_id_idx", + "columns": [ + { + "expression": "env_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_idx": { + "name": "credential_group_enrollment_idx", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_mcp_server_idx": { + "name": "credential_mcp_server_idx", + "columns": [ + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_option_identity_unique": { + "name": "credential_group_option_identity_unique", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "credential_group_option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_tenant_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'managed_oauth'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_managed_mcp_enrollment_server_identity_unique": { + "name": "credential_managed_mcp_enrollment_server_identity_unique", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_subject_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_tenant_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'managed_mcp'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_account_unique": { + "name": "credential_workspace_account_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "account_id IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_env_unique": { + "name": "credential_workspace_env_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "type = 'env_workspace'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_personal_env_unique": { + "name": "credential_workspace_personal_env_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "type = 'env_personal'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_workspace_id_workspace_id_fk": { + "name": "credential_workspace_id_workspace_id_fk", + "tableFrom": "credential", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_organization_id_organization_id_fk": { + "name": "credential_organization_id_organization_id_fk", + "tableFrom": "credential", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_slack_app_id_slack_app_id_fk": { + "name": "credential_slack_app_id_slack_app_id_fk", + "tableFrom": "credential", + "tableTo": "slack_app", + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "credential_account_id_account_id_fk": { + "name": "credential_account_id_account_id_fk", + "tableFrom": "credential", + "tableTo": "account", + "columnsFrom": ["account_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_env_owner_user_id_user_id_fk": { + "name": "credential_env_owner_user_id_user_id_fk", + "tableFrom": "credential", + "tableTo": "user", + "columnsFrom": ["env_owner_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_credential_group_enrollment_id_credential_group_enrollment_id_fk": { + "name": "credential_credential_group_enrollment_id_credential_group_enrollment_id_fk", + "tableFrom": "credential", + "tableTo": "credential_group_enrollment", + "columnsFrom": ["credential_group_enrollment_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_mcp_server_id_mcp_servers_id_fk": { + "name": "credential_mcp_server_id_mcp_servers_id_fk", + "tableFrom": "credential", + "tableTo": "mcp_servers", + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_created_by_user_id_fk": { + "name": "credential_created_by_user_id_fk", + "tableFrom": "credential", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_owner_check": { + "name": "credential_owner_check", + "value": "num_nonnulls(\"credential\".\"workspace_id\", \"credential\".\"organization_id\") = 1" + }, + "credential_organization_type_check": { + "name": "credential_organization_type_check", + "value": "\"credential\".\"organization_id\" IS NULL OR \"credential\".\"type\" IN ('oauth', 'managed_oauth', 'managed_mcp', 'service_account', 'personal_token')" + }, + "credential_personal_token_source_check": { + "name": "credential_personal_token_source_check", + "value": "(type::text <> 'personal_token') OR (\n created_by IS NOT NULL\n AND provider_id IS NOT NULL\n AND provider_id = 'gitlab'\n AND provider_subject_id IS NOT NULL\n AND provider_tenant_id IS NOT NULL\n AND encrypted_personal_token IS NOT NULL\n AND granted_scopes IS NOT NULL\n AND cardinality(granted_scopes) > 0\n AND account_id IS NULL\n AND env_key IS NULL\n AND env_owner_user_id IS NULL\n AND authorization_app_id IS NULL\n AND encrypted_oauth_token_set IS NULL\n AND encrypted_service_account_key IS NULL\n AND unredacted = false\n )" + }, + "credential_oauth_source_check": { + "name": "credential_oauth_source_check", + "value": "(type <> 'oauth') OR (account_id IS NOT NULL AND provider_id IS NOT NULL)" + }, + "credential_managed_oauth_source_check": { + "name": "credential_managed_oauth_source_check", + "value": "(type::text <> 'managed_oauth') OR (\n account_id IS NULL\n AND provider_id IS NOT NULL\n AND authorization_app_id IS NOT NULL\n AND provider_subject_id IS NOT NULL\n AND managed_oauth_status IS NOT NULL\n AND granted_scopes IS NOT NULL\n AND encrypted_oauth_token_set IS NOT NULL\n AND granted_at IS NOT NULL\n )" + }, + "credential_managed_oauth_group_binding_check": { + "name": "credential_managed_oauth_group_binding_check", + "value": "(type::text <> 'managed_oauth') OR (\n credential_group_enrollment_id IS NOT NULL\n AND credential_group_option_id IS NOT NULL\n AND managed_oauth_scope_version IS NOT NULL\n AND managed_oauth_scope_version > 0\n )" + }, + "credential_managed_mcp_source_check": { + "name": "credential_managed_mcp_source_check", + "value": "(type::text <> 'managed_mcp') OR (\n id LIKE 'mcp-cg-%'\n AND account_id IS NULL\n AND provider_id IS NULL\n AND authorization_app_id IS NULL\n AND credential_group_enrollment_id IS NOT NULL\n AND credential_group_option_id IS NULL\n AND mcp_server_id IS NOT NULL\n AND managed_oauth_status IS NOT NULL\n AND (managed_oauth_status <> 'active' OR (\n encrypted_oauth_token_set IS NOT NULL\n AND mcp_tools IS NOT NULL\n ))\n AND granted_at IS NOT NULL\n AND managed_oauth_scope_version IS NULL\n AND granted_scopes IS NULL\n AND provider_metadata IS NULL\n AND created_by IS NULL\n AND env_key IS NULL\n AND env_owner_user_id IS NULL\n AND encrypted_service_account_key IS NULL\n AND unredacted = false\n )" + }, + "credential_creator_source_check": { + "name": "credential_creator_source_check", + "value": "(type::text = 'managed_mcp') OR created_by IS NOT NULL" + }, + "credential_workspace_env_source_check": { + "name": "credential_workspace_env_source_check", + "value": "(type <> 'env_workspace') OR (env_key IS NOT NULL AND env_owner_user_id IS NULL)" + }, + "credential_personal_env_source_check": { + "name": "credential_personal_env_source_check", + "value": "(type <> 'env_personal') OR (env_key IS NOT NULL AND env_owner_user_id IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.credential_group": { + "name": "credential_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "public_id": { + "name": "public_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "encrypted_provider_configuration": { + "name": "encrypted_provider_configuration", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "credential_group_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_organization_unique": { + "name": "credential_group_organization_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_public_id_unique": { + "name": "credential_group_public_id_unique", + "columns": [ + { + "expression": "public_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_workspace_unique": { + "name": "credential_group_workspace_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_workspace_id_workspace_id_fk": { + "name": "credential_group_workspace_id_workspace_id_fk", + "tableFrom": "credential_group", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_organization_id_organization_id_fk": { + "name": "credential_group_organization_id_organization_id_fk", + "tableFrom": "credential_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_created_by_user_id_fk": { + "name": "credential_group_created_by_user_id_fk", + "tableFrom": "credential_group", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_owner_check": { + "name": "credential_group_owner_check", + "value": "num_nonnulls(\"credential_group\".\"workspace_id\", \"credential_group\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.credential_group_enrollment": { + "name": "credential_group_enrollment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "credential_group_enrollment_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'invited'" + }, + "invitation_token_hash": { + "name": "invitation_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invitation_expires_at": { + "name": "invitation_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "invited_at": { + "name": "invited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_delivery_error": { + "name": "last_delivery_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_enrollment_group_user_unique": { + "name": "credential_group_enrollment_group_user_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential_group_enrollment\".\"user_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_user_id_idx": { + "name": "credential_group_enrollment_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_email_unique": { + "name": "credential_group_enrollment_group_email_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_invitation_token_hash_unique": { + "name": "credential_group_enrollment_invitation_token_hash_unique", + "columns": [ + { + "expression": "invitation_token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_status_idx": { + "name": "credential_group_enrollment_group_status_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_invited_at_id_idx": { + "name": "credential_group_enrollment_group_invited_at_id_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "invited_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_enrollment_credential_group_id_credential_group_id_fk": { + "name": "credential_group_enrollment_credential_group_id_credential_group_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_enrollment_user_id_user_id_fk": { + "name": "credential_group_enrollment_user_id_user_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_enrollment_created_by_user_id_fk": { + "name": "credential_group_enrollment_created_by_user_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_enrollment_normalized_email_check": { + "name": "credential_group_enrollment_normalized_email_check", + "value": "\"credential_group_enrollment\".\"email\" = lower(btrim(\"credential_group_enrollment\".\"email\")) AND length(\"credential_group_enrollment\".\"email\") BETWEEN 3 AND 320" + }, + "credential_group_enrollment_invitation_token_hash_length_check": { + "name": "credential_group_enrollment_invitation_token_hash_length_check", + "value": "length(\"credential_group_enrollment\".\"invitation_token_hash\") = 64" + } + }, + "isRLSEnabled": false + }, + "public.credential_member": { + "name": "credential_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "credential_member_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "status": { + "name": "status", + "type": "credential_member_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "joined_at": { + "name": "joined_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_member_user_id_idx": { + "name": "credential_member_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_role_idx": { + "name": "credential_member_role_idx", + "columns": [ + { + "expression": "role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_status_idx": { + "name": "credential_member_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_unique": { + "name": "credential_member_unique", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_member_credential_id_credential_id_fk": { + "name": "credential_member_credential_id_credential_id_fk", + "tableFrom": "credential_member", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_member_user_id_user_id_fk": { + "name": "credential_member_user_id_user_id_fk", + "tableFrom": "credential_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_member_invited_by_user_id_fk": { + "name": "credential_member_invited_by_user_id_fk", + "tableFrom": "credential_member", + "tableTo": "user", + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_block": { + "name": "custom_block", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "icon_url": { + "name": "icon_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inputs": { + "name": "inputs", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "outputs": { + "name": "outputs", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "trace_child_runs": { + "name": "trace_child_runs", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "custom_block_workflow_id_idx": { + "name": "custom_block_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "custom_block_organization_type_unique": { + "name": "custom_block_organization_type_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "custom_block_organization_id_organization_id_fk": { + "name": "custom_block_organization_id_organization_id_fk", + "tableFrom": "custom_block", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_block_workflow_id_workflow_id_fk": { + "name": "custom_block_workflow_id_workflow_id_fk", + "tableFrom": "custom_block", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_block_created_by_user_id_fk": { + "name": "custom_block_created_by_user_id_fk", + "tableFrom": "custom_block", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_tools": { + "name": "custom_tools", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schema": { + "name": "schema", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "custom_tools_workspace_title_unique": { + "name": "custom_tools_workspace_title_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "custom_tools_workspace_id_workspace_id_fk": { + "name": "custom_tools_workspace_id_workspace_id_fk", + "tableFrom": "custom_tools", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_tools_user_id_user_id_fk": { + "name": "custom_tools_user_id_user_id_fk", + "tableFrom": "custom_tools", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.dashboard": { + "name": "dashboard", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "dashboard_workspace_id_unique": { + "name": "dashboard_workspace_id_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "dashboard_workspace_id_workspace_id_fk": { + "name": "dashboard_workspace_id_workspace_id_fk", + "tableFrom": "dashboard", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "dashboard_created_by_user_id_fk": { + "name": "dashboard_created_by_user_id_fk", + "tableFrom": "dashboard", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "dashboard_updated_by_user_id_fk": { + "name": "dashboard_updated_by_user_id_fk", + "tableFrom": "dashboard", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.data_drain_runs": { + "name": "data_drain_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "drain_id": { + "name": "drain_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "data_drain_run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "data_drain_run_trigger", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "rows_exported": { + "name": "rows_exported", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "bytes_written": { + "name": "bytes_written", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cursor_before": { + "name": "cursor_before", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cursor_after": { + "name": "cursor_after", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locators": { + "name": "locators", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": { + "data_drain_runs_drain_started_idx": { + "name": "data_drain_runs_drain_started_idx", + "columns": [ + { + "expression": "drain_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "data_drain_runs_drain_id_data_drains_id_fk": { + "name": "data_drain_runs_drain_id_data_drains_id_fk", + "tableFrom": "data_drain_runs", + "tableTo": "data_drains", + "columnsFrom": ["drain_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.data_drains": { + "name": "data_drains", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "data_drain_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "destination_type": { + "name": "destination_type", + "type": "data_drain_destination", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "destination_config": { + "name": "destination_config", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "destination_credentials": { + "name": "destination_credentials", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schedule_cadence": { + "name": "schedule_cadence", + "type": "data_drain_cadence", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_success_at": { + "name": "last_success_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "data_drains_due_idx": { + "name": "data_drains_due_idx", + "columns": [ + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "data_drains_org_name_unique": { + "name": "data_drains_org_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "data_drains_organization_id_organization_id_fk": { + "name": "data_drains_organization_id_organization_id_fk", + "tableFrom": "data_drains", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "data_drains_created_by_user_id_fk": { + "name": "data_drains_created_by_user_id_fk", + "tableFrom": "data_drains", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deleted_account_identity": { + "name": "deleted_account_identity", + "schema": "", + "columns": { + "identity_hash": { + "name": "identity_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "deleted_account_identity_expires_at_idx": { + "name": "deleted_account_identity_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.desktop_devices": { + "name": "desktop_devices", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_version": { + "name": "app_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "capabilities": { + "name": "capabilities", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "desktop_devices_user_id_idx": { + "name": "desktop_devices_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "desktop_devices_session_id_idx": { + "name": "desktop_devices_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "desktop_devices_user_id_user_id_fk": { + "name": "desktop_devices_user_id_user_id_fk", + "tableFrom": "desktop_devices", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "desktop_devices_session_id_session_id_fk": { + "name": "desktop_devices_session_id_session_id_fk", + "tableFrom": "desktop_devices", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.docs_embeddings": { + "name": "docs_embeddings", + "schema": "", + "columns": { + "chunk_id": { + "name": "chunk_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chunk_text": { + "name": "chunk_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_document": { + "name": "source_document", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_link": { + "name": "source_link", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "header_text": { + "name": "header_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "header_level": { + "name": "header_level", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": true + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "chunk_text_tsv": { + "name": "chunk_text_tsv", + "type": "tsvector", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "to_tsvector('english', \"docs_embeddings\".\"chunk_text\")", + "type": "stored" + } + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "docs_emb_source_document_idx": { + "name": "docs_emb_source_document_idx", + "columns": [ + { + "expression": "source_document", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_header_level_idx": { + "name": "docs_emb_header_level_idx", + "columns": [ + { + "expression": "header_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_source_header_idx": { + "name": "docs_emb_source_header_idx", + "columns": [ + { + "expression": "source_document", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "header_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_model_idx": { + "name": "docs_emb_model_idx", + "columns": [ + { + "expression": "embedding_model", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_created_at_idx": { + "name": "docs_emb_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_embedding_vector_hnsw_idx": { + "name": "docs_embedding_vector_hnsw_idx", + "columns": [ + { + "expression": "embedding", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "vector_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "docs_emb_metadata_gin_idx": { + "name": "docs_emb_metadata_gin_idx", + "columns": [ + { + "expression": "metadata", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "docs_emb_chunk_text_fts_idx": { + "name": "docs_emb_chunk_text_fts_idx", + "columns": [ + { + "expression": "chunk_text_tsv", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "docs_embedding_not_null_check": { + "name": "docs_embedding_not_null_check", + "value": "\"embedding\" IS NOT NULL" + }, + "docs_header_level_check": { + "name": "docs_header_level_check", + "value": "\"header_level\" >= 1 AND \"header_level\" <= 6" + } + }, + "isRLSEnabled": false + }, + "public.document": { + "name": "document", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_url": { + "name": "file_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file_size": { + "name": "file_size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "file_sha256": { + "name": "file_sha256", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "character_count": { + "name": "character_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "processing_status": { + "name": "processing_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "processing_attempts": { + "name": "processing_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "processing_queued_at": { + "name": "processing_queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_queue_token": { + "name": "processing_queue_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_started_at": { + "name": "processing_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_deferred_until": { + "name": "processing_deferred_until", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_completed_at": { + "name": "processing_completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_error": { + "name": "processing_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_recovery_after": { + "name": "processing_recovery_after", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "user_excluded": { + "name": "user_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "tag1": { + "name": "tag1", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag2": { + "name": "tag2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag3": { + "name": "tag3", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag4": { + "name": "tag4", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag5": { + "name": "tag5", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag6": { + "name": "tag6", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag7": { + "name": "tag7", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "number1": { + "name": "number1", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number2": { + "name": "number2", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number3": { + "name": "number3", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number4": { + "name": "number4", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number5": { + "name": "number5", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "date1": { + "name": "date1", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "date2": { + "name": "date2", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "boolean1": { + "name": "boolean1", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean2": { + "name": "boolean2", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean3": { + "name": "boolean3", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_url": { + "name": "source_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "acl": { + "name": "acl", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{ws}'::text[]" + }, + "acl_requirements": { + "name": "acl_requirements", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "acl_verified_at": { + "name": "acl_verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_modified_at": { + "name": "source_modified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_seen_at": { + "name": "source_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "doc_uploaded_by_idx": { + "name": "doc_uploaded_by_idx", + "columns": [ + { + "expression": "uploaded_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"uploaded_by\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_kb_source_modified_idx": { + "name": "doc_kb_source_modified_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_modified_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_acl_gin_idx": { + "name": "doc_acl_gin_idx", + "columns": [ + { + "expression": "acl", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "array_ops" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "gin", + "with": {} + }, + "doc_filename_idx": { + "name": "doc_filename_idx", + "columns": [ + { + "expression": "filename", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_processing_status_idx": { + "name": "doc_processing_status_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "processing_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_processing_recovery_idx": { + "name": "doc_connector_processing_recovery_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"processing_status\" IN ('pending', 'processing', 'failed') AND \"document\".\"connector_id\" IS NOT NULL AND \"document\".\"content_hash\" IS NOT NULL AND \"document\".\"storage_key\" IS NOT NULL AND \"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_connector_processing_status_idx": { + "name": "doc_connector_processing_status_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "processing_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"processing_status\" IN ('pending', 'processing', 'failed') AND \"document\".\"connector_id\" IS NOT NULL AND \"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_external_id_idx": { + "name": "doc_connector_external_id_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_source_lookup_idx": { + "name": "doc_connector_source_lookup_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_reconciliation_v2_idx": { + "name": "doc_connector_reconciliation_v2_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_active_kb_token_count_idx": { + "name": "doc_active_kb_token_count_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "token_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_storage_key_idx": { + "name": "doc_storage_key_idx", + "columns": [ + { + "expression": "storage_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"storage_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_archived_at_partial_idx": { + "name": "doc_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_deleted_at_partial_idx": { + "name": "doc_deleted_at_partial_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_tombstone_idx": { + "name": "doc_connector_tombstone_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"archived_at\" IS NULL AND (\"document\".\"deleted_at\" IS NOT NULL OR \"document\".\"content_hash\" IS NULL)", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_live_idx": { + "name": "doc_connector_live_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag1_lower_idx": { + "name": "doc_kb_tag1_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag1\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag2_lower_idx": { + "name": "doc_kb_tag2_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag2\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag3_lower_idx": { + "name": "doc_kb_tag3_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag3\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag4_lower_idx": { + "name": "doc_kb_tag4_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag4\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag5_lower_idx": { + "name": "doc_kb_tag5_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag5\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag6_lower_idx": { + "name": "doc_kb_tag6_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag6\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag7_lower_idx": { + "name": "doc_kb_tag7_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag7\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number1_idx": { + "name": "doc_number1_idx", + "columns": [ + { + "expression": "number1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number2_idx": { + "name": "doc_number2_idx", + "columns": [ + { + "expression": "number2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number3_idx": { + "name": "doc_number3_idx", + "columns": [ + { + "expression": "number3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number4_idx": { + "name": "doc_number4_idx", + "columns": [ + { + "expression": "number4", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number5_idx": { + "name": "doc_number5_idx", + "columns": [ + { + "expression": "number5", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_date1_idx": { + "name": "doc_date1_idx", + "columns": [ + { + "expression": "date1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_date2_idx": { + "name": "doc_date2_idx", + "columns": [ + { + "expression": "date2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_boolean1_idx": { + "name": "doc_boolean1_idx", + "columns": [ + { + "expression": "boolean1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_boolean2_idx": { + "name": "doc_boolean2_idx", + "columns": [ + { + "expression": "boolean2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_boolean3_idx": { + "name": "doc_boolean3_idx", + "columns": [ + { + "expression": "boolean3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "document_knowledge_base_id_knowledge_base_id_fk": { + "name": "document_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "document", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "document_connector_id_knowledge_connector_id_fk": { + "name": "document_connector_id_knowledge_connector_id_fk", + "tableFrom": "document", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "document_uploaded_by_user_id_fk": { + "name": "document_uploaded_by_user_id_fk", + "tableFrom": "document", + "tableTo": "user", + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "doc_acl_token_shape_check": { + "name": "doc_acl_token_shape_check", + "value": "array_position(\"document\".\"acl\", NULL) IS NULL AND (cardinality(\"document\".\"acl\") = 0 OR (cardinality(\"document\".\"acl\") = array_length(string_to_array(array_to_string(\"document\".\"acl\", E'\\n'), E'\\n'), 1) AND array_to_string(\"document\".\"acl\", E'\\n') ~ '^((ws|pub|link|u:[^\\nA-Z]+@[^\\nA-Z]+|[gs]:[^\\n:]+:[^\\n:]+:[^\\n]+)(\\n(ws|pub|link|u:[^\\nA-Z]+@[^\\nA-Z]+|[gs]:[^\\n:]+:[^\\n:]+:[^\\n]+))*)$'))" + } + }, + "isRLSEnabled": false + }, + "public.document_secret_provenance": { + "name": "document_secret_provenance", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "document_secret_provenance_document_id_document_id_fk": { + "name": "document_secret_provenance_document_id_document_id_fk", + "tableFrom": "document_secret_provenance", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "document_secret_provenance_status_check": { + "name": "document_secret_provenance_status_check", + "value": "\"document_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.embedding": { + "name": "embedding", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chunk_index": { + "name": "chunk_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "chunk_hash": { + "name": "chunk_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "content_length": { + "name": "content_length", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "embedding_384": { + "name": "embedding_384", + "type": "vector(384)", + "primaryKey": false, + "notNull": false + }, + "embedding_768": { + "name": "embedding_768", + "type": "vector(768)", + "primaryKey": false, + "notNull": false + }, + "embedding_1024": { + "name": "embedding_1024", + "type": "vector(1024)", + "primaryKey": false, + "notNull": false + }, + "embedding_3072": { + "name": "embedding_3072", + "type": "vector(3072)", + "primaryKey": false, + "notNull": false + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "start_offset": { + "name": "start_offset", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "end_offset": { + "name": "end_offset", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "tag1": { + "name": "tag1", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag2": { + "name": "tag2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag3": { + "name": "tag3", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag4": { + "name": "tag4", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag5": { + "name": "tag5", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag6": { + "name": "tag6", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag7": { + "name": "tag7", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "number1": { + "name": "number1", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number2": { + "name": "number2", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number3": { + "name": "number3", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number4": { + "name": "number4", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number5": { + "name": "number5", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "date1": { + "name": "date1", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "date2": { + "name": "date2", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "boolean1": { + "name": "boolean1", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean2": { + "name": "boolean2", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean3": { + "name": "boolean3", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "content_tsv": { + "name": "content_tsv", + "type": "tsvector", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "to_tsvector('english', \"embedding\".\"content\")", + "type": "stored" + } + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "emb_doc_chunk_idx": { + "name": "emb_doc_chunk_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chunk_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_model_idx": { + "name": "emb_kb_model_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "embedding_model", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_enabled_idx": { + "name": "emb_kb_enabled_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_doc_enabled_idx": { + "name": "emb_doc_enabled_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag1_lower_idx": { + "name": "emb_kb_tag1_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag1\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag2_lower_idx": { + "name": "emb_kb_tag2_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag2\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag3_lower_idx": { + "name": "emb_kb_tag3_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag3\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag4_lower_idx": { + "name": "emb_kb_tag4_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag4\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag5_lower_idx": { + "name": "emb_kb_tag5_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag5\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag6_lower_idx": { + "name": "emb_kb_tag6_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag6\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag7_lower_idx": { + "name": "emb_kb_tag7_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag7\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number1_idx": { + "name": "emb_number1_idx", + "columns": [ + { + "expression": "number1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number2_idx": { + "name": "emb_number2_idx", + "columns": [ + { + "expression": "number2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number3_idx": { + "name": "emb_number3_idx", + "columns": [ + { + "expression": "number3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number4_idx": { + "name": "emb_number4_idx", + "columns": [ + { + "expression": "number4", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number5_idx": { + "name": "emb_number5_idx", + "columns": [ + { + "expression": "number5", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_date1_idx": { + "name": "emb_date1_idx", + "columns": [ + { + "expression": "date1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "emb_date2_idx": { + "name": "emb_date2_idx", + "columns": [ + { + "expression": "date2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "emb_boolean1_idx": { + "name": "emb_boolean1_idx", + "columns": [ + { + "expression": "boolean1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_boolean2_idx": { + "name": "emb_boolean2_idx", + "columns": [ + { + "expression": "boolean2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_boolean3_idx": { + "name": "emb_boolean3_idx", + "columns": [ + { + "expression": "boolean3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_content_fts_idx": { + "name": "emb_content_fts_idx", + "columns": [ + { + "expression": "content_tsv", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": { + "fastupdate": "off" + } + } + }, + "foreignKeys": { + "embedding_knowledge_base_id_knowledge_base_id_fk": { + "name": "embedding_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "embedding", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "embedding_document_id_document_id_fk": { + "name": "embedding_document_id_document_id_fk", + "tableFrom": "embedding", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_width_check": { + "name": "embedding_width_check", + "value": "num_nonnulls(\"embedding\", \"embedding_384\", \"embedding_768\", \"embedding_1024\", \"embedding_3072\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.embedding_search": { + "name": "embedding_search", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "acl": { + "name": "acl", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "binary": { + "name": "binary", + "type": "bit(1536)", + "primaryKey": false, + "notNull": false + }, + "binary_384": { + "name": "binary_384", + "type": "bit(384)", + "primaryKey": false, + "notNull": false + }, + "binary_768": { + "name": "binary_768", + "type": "bit(768)", + "primaryKey": false, + "notNull": false + }, + "binary_1024": { + "name": "binary_1024", + "type": "bit(1024)", + "primaryKey": false, + "notNull": false + }, + "binary_3072": { + "name": "binary_3072", + "type": "bit(3072)", + "primaryKey": false, + "notNull": false + }, + "vector": { + "name": "vector", + "type": "halfvec(1536)", + "primaryKey": false, + "notNull": false + }, + "vector_384": { + "name": "vector_384", + "type": "halfvec(384)", + "primaryKey": false, + "notNull": false + }, + "vector_512": { + "name": "vector_512", + "type": "halfvec(512)", + "primaryKey": false, + "notNull": false + }, + "vector_768": { + "name": "vector_768", + "type": "halfvec(768)", + "primaryKey": false, + "notNull": false + }, + "vector_1024": { + "name": "vector_1024", + "type": "halfvec(1024)", + "primaryKey": false, + "notNull": false + }, + "vector_3072": { + "name": "vector_3072", + "type": "halfvec(3072)", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "embedding_search_kb_idx": { + "name": "embedding_search_kb_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "embedding_search_document_lookup_idx": { + "name": "embedding_search_document_lookup_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"embedding_search\".\"enabled\"", + "concurrently": true, + "method": "btree", + "with": {} + }, + "embedding_search_cosine_hnsw_idx": { + "name": "embedding_search_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_512_cosine_hnsw_idx": { + "name": "embedding_search_512_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_512", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_384_cosine_hnsw_idx": { + "name": "embedding_search_384_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_384", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_768_cosine_hnsw_idx": { + "name": "embedding_search_768_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_768", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_1024_cosine_hnsw_idx": { + "name": "embedding_search_1024_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_1024", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_3072_cosine_hnsw_idx": { + "name": "embedding_search_3072_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_3072", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + } + }, + "foreignKeys": { + "embedding_search_id_embedding_id_fk": { + "name": "embedding_search_id_embedding_id_fk", + "tableFrom": "embedding_search", + "tableTo": "embedding", + "columnsFrom": ["id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_search_width_check": { + "name": "embedding_search_width_check", + "value": "num_nonnulls(\"binary\", \"binary_384\", \"binary_768\", \"binary_1024\", \"binary_3072\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.embedding_secret_provenance": { + "name": "embedding_secret_provenance", + "schema": "", + "columns": { + "embedding_id": { + "name": "embedding_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "embedding_secret_provenance_embedding_id_embedding_id_fk": { + "name": "embedding_secret_provenance_embedding_id_embedding_id_fk", + "tableFrom": "embedding_secret_provenance", + "tableTo": "embedding", + "columnsFrom": ["embedding_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_secret_provenance_status_check": { + "name": "embedding_secret_provenance_status_check", + "value": "\"embedding_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.environment": { + "name": "environment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "environment_user_id_user_id_fk": { + "name": "environment_user_id_user_id_fk", + "tableFrom": "environment", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "environment_user_id_unique": { + "name": "environment_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_value_dependencies": { + "name": "execution_large_value_dependencies", + "schema": "", + "columns": { + "parent_key": { + "name": "parent_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_key": { + "name": "child_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "execution_large_value_dependencies_workspace_parent_key_idx": { + "name": "execution_large_value_dependencies_workspace_parent_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_value_dependencies_workspace_child_key_idx": { + "name": "execution_large_value_dependencies_workspace_child_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_value_dependencies_workspace_id_workspace_id_fk": { + "name": "execution_large_value_dependencies_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_value_dependencies", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "execution_large_value_dependencies_parent_key_child_key_pk": { + "name": "execution_large_value_dependencies_parent_key_child_key_pk", + "columns": ["parent_key", "child_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_value_references": { + "name": "execution_large_value_references", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "execution_large_value_reference_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "execution_large_value_references_workspace_execution_source_idx": { + "name": "execution_large_value_references_workspace_execution_source_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_value_references_workflow_id_idx": { + "name": "execution_large_value_references_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_value_references_workspace_id_workspace_id_fk": { + "name": "execution_large_value_references_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_value_references", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_large_value_references_workflow_id_workflow_id_fk": { + "name": "execution_large_value_references_workflow_id_workflow_id_fk", + "tableFrom": "execution_large_value_references", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "execution_large_value_references_key_execution_id_source_pk": { + "name": "execution_large_value_references_key_execution_id_source_pk", + "columns": ["key", "execution_id", "source"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_values": { + "name": "execution_large_values", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_execution_id": { + "name": "owner_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "execution_large_values_owner_execution_id_idx": { + "name": "execution_large_values_owner_execution_id_idx", + "columns": [ + { + "expression": "owner_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_cleanup_idx": { + "name": "execution_large_values_cleanup_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"execution_large_values\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_tombstone_cleanup_idx": { + "name": "execution_large_values_tombstone_cleanup_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"execution_large_values\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_workflow_id_idx": { + "name": "execution_large_values_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_workspace_id_idx": { + "name": "execution_large_values_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_values_workspace_id_workspace_id_fk": { + "name": "execution_large_values_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_values", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_large_values_workflow_id_workflow_id_fk": { + "name": "execution_large_values_workflow_id_workflow_id_fk", + "tableFrom": "execution_large_values", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.file_search_dependency": { + "name": "file_search_dependency", + "schema": "", + "columns": { + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "file_search_dependency_file_idx": { + "name": "file_search_dependency_file_idx", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "file_search_dependency_owner_idx": { + "name": "file_search_dependency_owner_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "file_search_dependency_build_id_workspace_file_search_build_id_fk": { + "name": "file_search_dependency_build_id_workspace_file_search_build_id_fk", + "tableFrom": "file_search_dependency", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "file_search_dependency_build_id_file_id_pk": { + "name": "file_search_dependency_build_id_file_id_pk", + "columns": ["build_id", "file_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.file_search_dispatch_queue": { + "name": "file_search_dispatch_queue", + "schema": "", + "columns": { + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enqueued_at": { + "name": "enqueued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_dispatched_at": { + "name": "last_dispatched_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "file_search_dispatch_schedule_idx": { + "name": "file_search_dispatch_schedule_idx", + "columns": [ + { + "expression": "last_dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "first" + }, + { + "expression": "enqueued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "file_search_dispatch_queue_entity_type_entity_id_pk": { + "name": "file_search_dispatch_queue_entity_type_entity_id_pk", + "columns": ["entity_type", "entity_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_dispatch_owner_check": { + "name": "file_search_dispatch_owner_check", + "value": "\"file_search_dispatch_queue\".\"entity_type\" IN ('workspace', 'project') AND length(\"file_search_dispatch_queue\".\"entity_id\") > 0" + } + }, + "isRLSEnabled": false + }, + "public.folder": { + "name": "folder", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_type": { + "name": "resource_type", + "type": "folder_resource_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parent_id": { + "name": "parent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "folder_project_id_idx": { + "name": "folder_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "folder_project_resource_parent_name_active_unique": { + "name": "folder_project_resource_parent_name_active_unique", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"parent_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"folder\".\"deleted_at\" IS NULL AND \"folder\".\"project_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "folder_user_idx": { + "name": "folder_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_resource_parent_idx": { + "name": "folder_workspace_resource_parent_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_parent_sort_idx": { + "name": "folder_parent_sort_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_deleted_at_idx": { + "name": "folder_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_deleted_partial_idx": { + "name": "folder_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"folder\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_resource_parent_name_active_unique": { + "name": "folder_workspace_resource_parent_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"parent_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"folder\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "folder_project_id_project_id_fk": { + "name": "folder_project_id_project_id_fk", + "tableFrom": "folder", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "folder_user_id_user_id_fk": { + "name": "folder_user_id_user_id_fk", + "tableFrom": "folder", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "folder_workspace_id_workspace_id_fk": { + "name": "folder_workspace_id_workspace_id_fk", + "tableFrom": "folder", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "folder_parent_id_folder_id_fk": { + "name": "folder_parent_id_folder_id_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "folder_workspace_parent_owner_fk": { + "name": "folder_workspace_parent_owner_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id", "workspace_id", "resource_type"], + "columnsTo": ["id", "workspace_id", "resource_type"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "folder_project_parent_owner_fk": { + "name": "folder_project_parent_owner_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id", "project_id", "resource_type"], + "columnsTo": ["id", "project_id", "resource_type"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "folder_workspace_owner_type_unique": { + "name": "folder_workspace_owner_type_unique", + "nullsNotDistinct": false, + "columns": ["id", "workspace_id", "resource_type"] + }, + "folder_project_owner_type_unique": { + "name": "folder_project_owner_type_unique", + "nullsNotDistinct": false, + "columns": ["id", "project_id", "resource_type"] + } + }, + "policies": {}, + "checkConstraints": { + "folder_owner_check": { + "name": "folder_owner_check", + "value": "num_nonnulls(\"folder\".\"workspace_id\", \"folder\".\"project_id\") = 1 AND (\"folder\".\"project_id\" IS NULL OR \"folder\".\"resource_type\" = 'file')" + } + }, + "isRLSEnabled": false + }, + "public.idempotency_key": { + "name": "idempotency_key", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "result": { + "name": "result", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idempotency_key_created_at_idx": { + "name": "idempotency_key_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitation": { + "name": "invitation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "invitation_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'organization'" + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "inviter_id": { + "name": "inviter_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "membership_intent": { + "name": "membership_intent", + "type": "invitation_membership_intent", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'internal'" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "invitation_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "invitation_email_idx": { + "name": "invitation_email_idx", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_organization_id_idx": { + "name": "invitation_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_status_idx": { + "name": "invitation_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_pending_email_org_unique": { + "name": "invitation_pending_email_org_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"invitation\".\"status\" = 'pending' AND \"invitation\".\"organization_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitation_inviter_id_user_id_fk": { + "name": "invitation_inviter_id_user_id_fk", + "tableFrom": "invitation", + "tableTo": "user", + "columnsFrom": ["inviter_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_organization_id_organization_id_fk": { + "name": "invitation_organization_id_organization_id_fk", + "tableFrom": "invitation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "invitation_token_unique": { + "name": "invitation_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitation_workspace_grant": { + "name": "invitation_workspace_grant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "invitation_id": { + "name": "invitation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "invitation_workspace_grant_unique": { + "name": "invitation_workspace_grant_unique", + "columns": [ + { + "expression": "invitation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_workspace_grant_workspace_id_idx": { + "name": "invitation_workspace_grant_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitation_workspace_grant_invitation_id_invitation_id_fk": { + "name": "invitation_workspace_grant_invitation_id_invitation_id_fk", + "tableFrom": "invitation_workspace_grant", + "tableTo": "invitation", + "columnsFrom": ["invitation_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_workspace_grant_workspace_id_workspace_id_fk": { + "name": "invitation_workspace_grant_workspace_id_workspace_id_fk", + "tableFrom": "invitation_workspace_grant", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.job_execution_logs": { + "name": "job_execution_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "schedule_id": { + "name": "schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_duration_ms": { + "name": "total_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "execution_data": { + "name": "execution_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "cost": { + "name": "cost", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "occurrence_at": { + "name": "occurrence_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_request_id": { + "name": "billing_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "job_execution_logs_schedule_occurrence_unique": { + "name": "job_execution_logs_schedule_occurrence_unique", + "columns": [ + { + "expression": "schedule_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "occurrence_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_billing_request_unique": { + "name": "job_execution_logs_billing_request_unique", + "columns": [ + { + "expression": "billing_request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"job_execution_logs\".\"billing_request_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_open_idx": { + "name": "job_execution_logs_open_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"job_execution_logs\".\"status\" IN ('queued', 'running')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_workspace_started_at_idx": { + "name": "job_execution_logs_workspace_started_at_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_workspace_ended_at_id_idx": { + "name": "job_execution_logs_workspace_ended_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"ended_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_execution_id_unique": { + "name": "job_execution_logs_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_trigger_idx": { + "name": "job_execution_logs_trigger_idx", + "columns": [ + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "job_execution_logs_schedule_id_workflow_schedule_id_fk": { + "name": "job_execution_logs_schedule_id_workflow_schedule_id_fk", + "tableFrom": "job_execution_logs", + "tableTo": "workflow_schedule", + "columnsFrom": ["schedule_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "job_execution_logs_workspace_id_workspace_id_fk": { + "name": "job_execution_logs_workspace_id_workspace_id_fk", + "tableFrom": "job_execution_logs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_base": { + "name": "knowledge_base", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_search_index": { + "name": "is_search_index", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "embedding_dimension": { + "name": "embedding_dimension", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1536 + }, + "chunking_config": { + "name": "chunking_config", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{\"maxSize\": 1024, \"minSize\": 1, \"overlap\": 200}'" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kb_organization_id_idx": { + "name": "kb_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_organization_search_index_unique": { + "name": "kb_organization_search_index_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"is_search_index\" = true AND \"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_organization_name_active_unique": { + "name": "kb_organization_name_active_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_id_idx": { + "name": "kb_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_user_workspace_idx": { + "name": "kb_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_folder_id_idx": { + "name": "kb_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_deleted_at_idx": { + "name": "kb_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_deleted_partial_idx": { + "name": "kb_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_base\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_name_active_unique": { + "name": "kb_workspace_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_search_index_unique": { + "name": "kb_workspace_search_index_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"is_search_index\" = true AND \"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_user_id_user_id_fk": { + "name": "knowledge_base_user_id_user_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_workspace_id_workspace_id_fk": { + "name": "knowledge_base_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_organization_id_organization_id_fk": { + "name": "knowledge_base_organization_id_organization_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_folder_id_folder_id_fk": { + "name": "knowledge_base_folder_id_folder_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kb_owner_check": { + "name": "kb_owner_check", + "value": "num_nonnulls(\"knowledge_base\".\"workspace_id\", \"knowledge_base\".\"organization_id\") = 1" + }, + "kb_organization_search_index_check": { + "name": "kb_organization_search_index_check", + "value": "\"knowledge_base\".\"organization_id\" IS NULL OR \"knowledge_base\".\"is_search_index\"" + }, + "kb_organization_folder_check": { + "name": "kb_organization_folder_check", + "value": "\"knowledge_base\".\"organization_id\" IS NULL OR \"knowledge_base\".\"folder_id\" IS NULL" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_base_import": { + "name": "knowledge_base_import", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_key": { + "name": "source_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "documents_total": { + "name": "documents_total", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "documents_imported": { + "name": "documents_imported", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "documents_failed": { + "name": "documents_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "vectors_reused": { + "name": "vectors_reused", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "failures": { + "name": "failures", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "knowledge_base_import_watchdog_idx": { + "name": "knowledge_base_import_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "knowledge_base_import_knowledge_base_id_idx": { + "name": "knowledge_base_import_knowledge_base_id_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_import_workspace_id_workspace_id_fk": { + "name": "knowledge_base_import_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_base_import", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_import_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_base_import_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_base_import", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_base_tag_definitions": { + "name": "knowledge_base_tag_definitions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tag_slot": { + "name": "tag_slot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "field_type": { + "name": "field_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kb_tag_definitions_kb_slot_idx": { + "name": "kb_tag_definitions_kb_slot_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tag_slot", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_tag_definitions_kb_display_name_idx": { + "name": "kb_tag_definitions_kb_display_name_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_tag_definitions_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_base_tag_definitions_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_base_tag_definitions", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector": { + "name": "knowledge_connector", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_config": { + "name": "source_config", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "sync_mode": { + "name": "sync_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'full'" + }, + "sync_interval_minutes": { + "name": "sync_interval_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1440 + }, + "access_mode": { + "name": "access_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'workspace'" + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_option_id": { + "name": "credential_group_option_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_status": { + "name": "member_sync_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'idle'" + }, + "member_sync_lock_token": { + "name": "member_sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_lock_lease_at": { + "name": "member_sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "next_member_sync_at": { + "name": "next_member_sync_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": false + }, + "last_member_sync_at": { + "name": "last_member_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_member_sync_error": { + "name": "last_member_sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_consecutive_failures": { + "name": "member_sync_consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "access_rewrite_pending": { + "name": "access_rewrite_pending", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image_removal_pending": { + "name": "image_removal_pending", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "member_tombstone_cursor": { + "name": "member_tombstone_cursor", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "member_resurrection_cursor": { + "name": "member_resurrection_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "last_sync_at": { + "name": "last_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_sync_error": { + "name": "last_sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_sync_doc_count": { + "name": "last_sync_doc_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "listing_checkpoint": { + "name": "listing_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "directory_checkpoint": { + "name": "directory_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "next_sync_at": { + "name": "next_sync_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": false + }, + "next_directory_sync_at": { + "name": "next_directory_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "sync_lock_token": { + "name": "sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_lock_lease_at": { + "name": "sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "detached_at": { + "name": "detached_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "detach_reserved_bytes": { + "name": "detach_reserved_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "kc_knowledge_base_id_idx": { + "name": "kc_knowledge_base_id_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_status_next_sync_idx": { + "name": "kc_status_next_sync_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_archived_at_partial_idx": { + "name": "kc_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_deleted_at_partial_idx": { + "name": "kc_deleted_at_partial_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_member_sync_due_idx": { + "name": "kc_member_sync_due_idx", + "columns": [ + { + "expression": "member_sync_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_member_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"access_mode\" = 'members' AND \"knowledge_connector\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_directory_sync_due_idx": { + "name": "kc_directory_sync_due_idx", + "columns": [ + { + "expression": "next_directory_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"access_mode\" = 'admin' AND \"knowledge_connector\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_connector_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_connector", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_credential_group_id_credential_group_id_fk": { + "name": "knowledge_connector_credential_group_id_credential_group_id_fk", + "tableFrom": "knowledge_connector", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kc_access_mode_check": { + "name": "kc_access_mode_check", + "value": "\"knowledge_connector\".\"access_mode\" IN ('workspace', 'members', 'admin')" + }, + "kc_member_sync_status_check": { + "name": "kc_member_sync_status_check", + "value": "\"knowledge_connector\".\"member_sync_status\" IN ('idle', 'pending', 'running', 'error', 'disabled')" + }, + "kc_sync_lock_exclusive_check": { + "name": "kc_sync_lock_exclusive_check", + "value": "NOT (\"knowledge_connector\".\"sync_lock_token\" IS NOT NULL AND \"knowledge_connector\".\"member_sync_lock_token\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_member": { + "name": "knowledge_connector_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_started_at": { + "name": "last_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_complete_listing_at": { + "name": "last_complete_listing_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_listed_count": { + "name": "last_listed_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_synced_through": { + "name": "member_synced_through", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope_renewed_at": { + "name": "scope_renewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope_renewal_cursor": { + "name": "scope_renewal_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope_renewal_started_at": { + "name": "scope_renewal_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "change_cursor": { + "name": "change_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "listing_checkpoint": { + "name": "listing_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kcm_organization_id_idx": { + "name": "kcm_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_connector_credential_unique": { + "name": "kcm_connector_credential_unique", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_connector_queue_idx": { + "name": "kcm_connector_queue_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "first" + }, + { + "expression": "last_started_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_credential_idx": { + "name": "kcm_credential_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_member_workspace_id_workspace_id_fk": { + "name": "knowledge_connector_member_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_organization_id_organization_id_fk": { + "name": "knowledge_connector_member_organization_id_organization_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_member_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_credential_id_credential_id_fk": { + "name": "knowledge_connector_member_credential_id_credential_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcm_owner_check": { + "name": "kcm_owner_check", + "value": "num_nonnulls(\"knowledge_connector_member\".\"workspace_id\", \"knowledge_connector_member\".\"organization_id\") = 1" + }, + "kcm_status_check": { + "name": "kcm_status_check", + "value": "\"knowledge_connector_member\".\"status\" IN ('active', 'suspended', 'disabled')" + }, + "kcm_subject_token_shape_check": { + "name": "kcm_subject_token_shape_check", + "value": "\"knowledge_connector_member\".\"subject_token\" ~ '^s:[^:]+:[^:]+:.+$'" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_member_sync_log": { + "name": "knowledge_connector_member_sync_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "members_claimed": { + "name": "members_claimed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_completed": { + "name": "members_completed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_incomplete": { + "name": "members_incomplete", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_failed": { + "name": "members_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_failed": { + "name": "docs_failed", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "processing_dispatch_failed": { + "name": "processing_dispatch_failed", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "docs_listed": { + "name": "docs_listed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_added": { + "name": "docs_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_updated": { + "name": "docs_updated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_unchanged": { + "name": "docs_unchanged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_hydrated_once": { + "name": "docs_hydrated_once", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_added": { + "name": "observations_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_renewed": { + "name": "observations_renewed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_removed": { + "name": "observations_removed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_tombstoned": { + "name": "docs_tombstoned", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_resurrected": { + "name": "docs_resurrected", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_purged": { + "name": "docs_purged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "credentials_audited": { + "name": "credentials_audited", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "database_failure_class": { + "name": "database_failure_class", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcmsl_connector_started_at_idx": { + "name": "kcmsl_connector_started_at_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcmsl_started_at_partial_idx": { + "name": "kcmsl_started_at_partial_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_member_sync_log\".\"status\" = 'started'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_member_sync_log_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_member_sync_log_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_member_sync_log", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcmsl_status_check": { + "name": "kcmsl_status_check", + "value": "\"knowledge_connector_member_sync_log\".\"status\" IN ('started', 'partial', 'completed', 'failed')" + }, + "kcmsl_database_failure_class_check": { + "name": "kcmsl_database_failure_class_check", + "value": "\"knowledge_connector_member_sync_log\".\"database_failure_class\" IN ('capacity', 'conflict', 'connection')" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_partition": { + "name": "knowledge_connector_partition", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "partition_key": { + "name": "partition_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation_id": { + "name": "generation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context": { + "name": "context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "retry_at": { + "name": "retry_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "permission_cursor": { + "name": "permission_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_attempts": { + "name": "permission_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "permission_retry_at": { + "name": "permission_retry_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "permission_last_served_at": { + "name": "permission_last_served_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_started_at": { + "name": "permission_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_failure": { + "name": "permission_failure", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcp_content_due_idx": { + "name": "kcp_content_due_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "retry_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_served_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcp_permission_due_idx": { + "name": "kcp_permission_due_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_retry_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_last_served_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_partition_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_partition_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_partition", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcp_pk": { + "name": "kcp_pk", + "columns": ["connector_id", "partition_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcp_partition_key_check": { + "name": "kcp_partition_key_check", + "value": "octet_length(\"knowledge_connector_partition\".\"partition_key\") BETWEEN 1 AND 1024" + }, + "kcp_context_check": { + "name": "kcp_context_check", + "value": "jsonb_typeof(\"knowledge_connector_partition\".\"context\") = 'object' AND octet_length(\"knowledge_connector_partition\".\"context\"::text) <= 16384" + }, + "kcp_status_check": { + "name": "kcp_status_check", + "value": "\"knowledge_connector_partition\".\"status\" IN ('pending', 'complete', 'blocked')" + }, + "kcp_cursor_check": { + "name": "kcp_cursor_check", + "value": "(\"knowledge_connector_partition\".\"cursor\" IS NULL OR octet_length(\"knowledge_connector_partition\".\"cursor\") <= 393216) AND (\"knowledge_connector_partition\".\"permission_cursor\" IS NULL OR octet_length(\"knowledge_connector_partition\".\"permission_cursor\") <= 393216)" + }, + "kcp_attempts_check": { + "name": "kcp_attempts_check", + "value": "\"knowledge_connector_partition\".\"attempts\" >= 0 AND \"knowledge_connector_partition\".\"permission_attempts\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_grant": { + "name": "knowledge_connector_permission_grant", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_key": { + "name": "group_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpg_subject_idx": { + "name": "kcpg_subject_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "kcpg_snapshot_fk": { + "name": "kcpg_snapshot_fk", + "tableFrom": "knowledge_connector_permission_grant", + "tableTo": "knowledge_connector_permission_snapshot", + "columnsFrom": ["connector_id"], + "columnsTo": ["connector_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpg_pk": { + "name": "kcpg_pk", + "columns": ["connector_id", "group_key", "subject_token"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcpg_group_check": { + "name": "kcpg_group_check", + "value": "length(\"knowledge_connector_permission_grant\".\"group_key\") BETWEEN 1 AND 255" + }, + "kcpg_subject_check": { + "name": "kcpg_subject_check", + "value": "\"knowledge_connector_permission_grant\".\"subject_token\" ~ '^u:[^[:space:]A-Z]+@[^[:space:]A-Z]+$'" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import": { + "name": "knowledge_connector_permission_import", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_binding": { + "name": "credential_binding", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expected_revision": { + "name": "expected_revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "manifest": { + "name": "manifest", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "part_digests": { + "name": "part_digests", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "user_rows": { + "name": "user_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "project_rows": { + "name": "project_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "completed_revision": { + "name": "completed_revision", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpi_connector_idx": { + "name": "kcpi_connector_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcpi_expires_idx": { + "name": "kcpi_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_permission_import_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_permission_import", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcpi_revision_check": { + "name": "kcpi_revision_check", + "value": "\"knowledge_connector_permission_import\".\"expected_revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import_grant": { + "name": "knowledge_connector_permission_import_grant", + "schema": "", + "columns": { + "import_id": { + "name": "import_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_path": { + "name": "project_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_key": { + "name": "group_key", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcpig_subject_idx": { + "name": "kcpig_subject_idx", + "columns": [ + { + "expression": "import_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_grant_import_id_knowledge_connector_permission_import_id_fk": { + "name": "knowledge_connector_permission_import_grant_import_id_knowledge_connector_permission_import_id_fk", + "tableFrom": "knowledge_connector_permission_import_grant", + "tableTo": "knowledge_connector_permission_import", + "columnsFrom": ["import_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpig_pk": { + "name": "kcpig_pk", + "columns": ["import_id", "project_path", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import_identity": { + "name": "knowledge_connector_permission_import_identity", + "schema": "", + "columns": { + "import_id": { + "name": "import_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpii_subject_import_idx": { + "name": "kcpii_subject_import_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "import_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_identity_import_id_knowledge_connector_permission_import_id_fk": { + "name": "knowledge_connector_permission_import_identity_import_id_knowledge_connector_permission_import_id_fk", + "tableFrom": "knowledge_connector_permission_import_identity", + "tableTo": "knowledge_connector_permission_import", + "columnsFrom": ["import_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpii_pk": { + "name": "kcpii_pk", + "columns": ["import_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_snapshot": { + "name": "knowledge_connector_permission_snapshot", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "kcps_connector_fk": { + "name": "kcps_connector_fk", + "tableFrom": "knowledge_connector_permission_snapshot", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcps_revision_check": { + "name": "kcps_revision_check", + "value": "\"knowledge_connector_permission_snapshot\".\"revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_sync_log": { + "name": "knowledge_connector_sync_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "docs_added": { + "name": "docs_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_updated": { + "name": "docs_updated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_deleted": { + "name": "docs_deleted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_unchanged": { + "name": "docs_unchanged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_skipped": { + "name": "docs_skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_failed": { + "name": "docs_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "listed_count": { + "name": "listed_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "database_failure_class": { + "name": "database_failure_class", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcsl_connector_started_at_idx": { + "name": "kcsl_connector_started_at_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcsl_started_at_partial_idx": { + "name": "kcsl_started_at_partial_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_sync_log\".\"status\" = 'started'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcsl_terminal_started_at_idx": { + "name": "kcsl_terminal_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_sync_log\".\"status\" IN ('completed', 'failed')", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_sync_log_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_sync_log_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_sync_log", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcsl_database_failure_class_check": { + "name": "kcsl_database_failure_class_check", + "value": "\"knowledge_connector_sync_log\".\"database_failure_class\" IN ('capacity', 'conflict', 'connection')" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_document_observation": { + "name": "knowledge_document_observation", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kdo_member_idx": { + "name": "kdo_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_document_observation_document_id_document_id_fk": { + "name": "knowledge_document_observation_document_id_document_id_fk", + "tableFrom": "knowledge_document_observation", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_document_observation_member_id_knowledge_connector_member_id_fk": { + "name": "knowledge_document_observation_member_id_knowledge_connector_member_id_fk", + "tableFrom": "knowledge_document_observation", + "tableTo": "knowledge_connector_member", + "columnsFrom": ["member_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "knowledge_document_observation_document_id_member_id_pk": { + "name": "knowledge_document_observation_document_id_member_id_pk", + "columns": ["document_id", "member_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_external_directory": { + "name": "knowledge_external_directory", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sync_lock_token": { + "name": "sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_lock_lease_at": { + "name": "sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_started_at": { + "name": "last_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_complete_sync_at": { + "name": "last_complete_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "ked_workspace_identity_unique": { + "name": "ked_workspace_identity_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "ked_organization_identity_unique": { + "name": "ked_organization_identity_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_external_directory_workspace_id_workspace_id_fk": { + "name": "knowledge_external_directory_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_external_directory", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_external_directory_organization_id_organization_id_fk": { + "name": "knowledge_external_directory_organization_id_organization_id_fk", + "tableFrom": "knowledge_external_directory", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ked_owner_check": { + "name": "ked_owner_check", + "value": "num_nonnulls(\"knowledge_external_directory\".\"workspace_id\", \"knowledge_external_directory\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_external_group": { + "name": "knowledge_external_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_group_id": { + "name": "external_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "keg_organization_identity_unique": { + "name": "keg_organization_identity_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_organization_synced_idx": { + "name": "keg_organization_synced_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_synced_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_identity_unique": { + "name": "keg_identity_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_workspace_synced_idx": { + "name": "keg_workspace_synced_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_synced_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_external_group_organization_id_organization_id_fk": { + "name": "knowledge_external_group_organization_id_organization_id_fk", + "tableFrom": "knowledge_external_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "keg_workspace_fk": { + "name": "keg_workspace_fk", + "tableFrom": "knowledge_external_group", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "keg_owner_check": { + "name": "keg_owner_check", + "value": "num_nonnulls(\"knowledge_external_group\".\"workspace_id\", \"knowledge_external_group\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_external_group_member": { + "name": "knowledge_external_group_member", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kegm_subject_token_idx": { + "name": "kegm_subject_token_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "kegm_group_fk": { + "name": "kegm_group_fk", + "tableFrom": "knowledge_external_group_member", + "tableTo": "knowledge_external_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "knowledge_external_group_member_group_id_subject_token_pk": { + "name": "knowledge_external_group_member_group_id_subject_token_pk", + "columns": ["group_id", "subject_token"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_projection_dirty": { + "name": "knowledge_projection_dirty", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "content": { + "name": "content", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "marked_at": { + "name": "marked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "knowledge_projection_dirty_marked_at_idx": { + "name": "knowledge_projection_dirty_marked_at_idx", + "columns": [ + { + "expression": "marked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_projection_dirty_document_id_document_id_fk": { + "name": "knowledge_projection_dirty_document_id_document_id_fk", + "tableFrom": "knowledge_projection_dirty", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mcp_server_oauth": { + "name": "mcp_server_oauth", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "mcp_server_id": { + "name": "mcp_server_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_information": { + "name": "client_information", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tokens": { + "name": "tokens", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_verifier": { + "name": "code_verifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state_created_at": { + "name": "state_created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_refreshed_at": { + "name": "last_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mcp_server_oauth_server_unique": { + "name": "mcp_server_oauth_server_unique", + "columns": [ + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_server_oauth_state_idx": { + "name": "mcp_server_oauth_state_idx", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mcp_server_oauth_mcp_server_id_mcp_servers_id_fk": { + "name": "mcp_server_oauth_mcp_server_id_mcp_servers_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "mcp_servers", + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_server_oauth_user_id_user_id_fk": { + "name": "mcp_server_oauth_user_id_user_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "mcp_server_oauth_workspace_id_workspace_id_fk": { + "name": "mcp_server_oauth_workspace_id_workspace_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_server_oauth_organization_id_organization_id_fk": { + "name": "mcp_server_oauth_organization_id_organization_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_server_oauth_owner_check": { + "name": "mcp_server_oauth_owner_check", + "value": "num_nonnulls(\"mcp_server_oauth\".\"workspace_id\", \"mcp_server_oauth\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.mcp_servers": { + "name": "mcp_servers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "managed_connector_id": { + "name": "managed_connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config_version": { + "name": "oauth_config_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "transport": { + "name": "transport", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'headers'" + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_client_secret": { + "name": "oauth_client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "headers": { + "name": "headers", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "timeout": { + "name": "timeout", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 30000 + }, + "retries": { + "name": "retries", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 3 + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "last_connected": { + "name": "last_connected", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "connection_status": { + "name": "connection_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'disconnected'" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status_config": { + "name": "status_config", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "tool_count": { + "name": "tool_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_tools_refresh": { + "name": "last_tools_refresh", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_requests": { + "name": "total_requests", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mcp_servers_organization_id_idx": { + "name": "mcp_servers_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_workspace_enabled_idx": { + "name": "mcp_servers_workspace_enabled_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_credential_group_idx": { + "name": "mcp_servers_credential_group_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_credential_group_managed_connector_unique": { + "name": "mcp_servers_credential_group_managed_connector_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "managed_connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"mcp_servers\".\"credential_group_id\" IS NOT NULL AND \"mcp_servers\".\"managed_connector_id\" IS NOT NULL AND \"mcp_servers\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_workspace_deleted_partial_idx": { + "name": "mcp_servers_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"mcp_servers\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mcp_servers_workspace_id_workspace_id_fk": { + "name": "mcp_servers_workspace_id_workspace_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_servers_organization_id_organization_id_fk": { + "name": "mcp_servers_organization_id_organization_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_servers_credential_group_id_credential_group_id_fk": { + "name": "mcp_servers_credential_group_id_credential_group_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "mcp_servers_created_by_user_id_fk": { + "name": "mcp_servers_created_by_user_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_servers_owner_check": { + "name": "mcp_servers_owner_check", + "value": "num_nonnulls(\"mcp_servers\".\"workspace_id\", \"mcp_servers\".\"organization_id\") = 1" + }, + "mcp_servers_organization_managed_check": { + "name": "mcp_servers_organization_managed_check", + "value": "\"mcp_servers\".\"organization_id\" IS NULL OR \"mcp_servers\".\"credential_group_id\" IS NOT NULL" + }, + "mcp_servers_credential_group_managed_connector_check": { + "name": "mcp_servers_credential_group_managed_connector_check", + "value": "\"mcp_servers\".\"credential_group_id\" IS NULL OR \"mcp_servers\".\"managed_connector_id\" IS NOT NULL" + }, + "mcp_servers_managed_connector_oauth_check": { + "name": "mcp_servers_managed_connector_oauth_check", + "value": "\"mcp_servers\".\"managed_connector_id\" IS NULL OR \"mcp_servers\".\"auth_type\" = 'oauth'" + } + }, + "isRLSEnabled": false + }, + "public.member": { + "name": "member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "member_user_id_unique": { + "name": "member_user_id_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_organization_id_idx": { + "name": "member_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "member_user_id_user_id_fk": { + "name": "member_user_id_user_id_fk", + "tableFrom": "member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_organization_id_organization_id_fk": { + "name": "member_organization_id_organization_id_fk", + "tableFrom": "member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.member_profile": { + "name": "member_profile", + "schema": "", + "columns": { + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "manager_member_id": { + "name": "manager_member_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "member_profile_manager_member_id_idx": { + "name": "member_profile_manager_member_id_idx", + "columns": [ + { + "expression": "manager_member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_profile_updated_by_idx": { + "name": "member_profile_updated_by_idx", + "columns": [ + { + "expression": "updated_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "member_profile_member_id_member_id_fk": { + "name": "member_profile_member_id_member_id_fk", + "tableFrom": "member_profile", + "tableTo": "member", + "columnsFrom": ["member_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_profile_manager_member_id_member_id_fk": { + "name": "member_profile_manager_member_id_member_id_fk", + "tableFrom": "member_profile", + "tableTo": "member", + "columnsFrom": ["manager_member_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "member_profile_updated_by_user_id_fk": { + "name": "member_profile_updated_by_user_id_fk", + "tableFrom": "member_profile", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "member_profile_not_own_manager": { + "name": "member_profile_not_own_manager", + "value": "\"member_profile\".\"manager_member_id\" <> \"member_profile\".\"member_id\"" + } + }, + "isRLSEnabled": false + }, + "public.memory": { + "name": "memory", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "storage_version": { + "name": "storage_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "encrypted_context_summary": { + "name": "encrypted_context_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "memory_key_idx": { + "name": "memory_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_workspace_key_idx": { + "name": "memory_workspace_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_workspace_deleted_partial_idx": { + "name": "memory_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"memory\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_workspace_id_workspace_id_fk": { + "name": "memory_workspace_id_workspace_id_fk", + "tableFrom": "memory", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_artifact": { + "name": "memory_artifact", + "schema": "", + "columns": { + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "memory_artifact_key_idx": { + "name": "memory_artifact_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_artifact_memory_id_memory_id_fk": { + "name": "memory_artifact_memory_id_memory_id_fk", + "tableFrom": "memory_artifact", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "memory_artifact_key_execution_large_values_key_fk": { + "name": "memory_artifact_key_execution_large_values_key_fk", + "tableFrom": "memory_artifact", + "tableTo": "execution_large_values", + "columnsFrom": ["key"], + "columnsTo": ["key"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "memory_artifact_memory_id_key_pk": { + "name": "memory_artifact_memory_id_key_pk", + "columns": ["memory_id", "key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_item": { + "name": "memory_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sequence": { + "name": "sequence", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "memory_item_sequence_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "append_key": { + "name": "append_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "turn_id": { + "name": "turn_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provenance_status": { + "name": "provenance_status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provenance_entries": { + "name": "provenance_entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "memory_item_append_unique": { + "name": "memory_item_append_unique", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "append_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_item_sequence_idx": { + "name": "memory_item_sequence_idx", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sequence", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_item_memory_id_memory_id_fk": { + "name": "memory_item_memory_id_memory_id_fk", + "tableFrom": "memory_item", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "memory_item_kind_check": { + "name": "memory_item_kind_check", + "value": "\"memory_item\".\"kind\" IN ('message', 'exchange')" + }, + "memory_item_provenance_status_check": { + "name": "memory_item_provenance_status_check", + "value": "\"memory_item\".\"provenance_status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.memory_secret_provenance": { + "name": "memory_secret_provenance", + "schema": "", + "columns": { + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "memory_secret_provenance_memory_id_memory_id_fk": { + "name": "memory_secret_provenance_memory_id_memory_id_fk", + "tableFrom": "memory_secret_provenance", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "memory_secret_provenance_status_check": { + "name": "memory_secret_provenance_status_check", + "value": "\"memory_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.mothership_benchmark_runs": { + "name": "mothership_benchmark_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "benchmark_id": { + "name": "benchmark_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "evaluation_key": { + "name": "evaluation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reviews": { + "name": "reviews", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "correct": { + "name": "correct", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "automatic_correct": { + "name": "automatic_correct", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "total": { + "name": "total", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "artifacts": { + "name": "artifacts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_benchmark_runs_benchmark_created_idx": { + "name": "mothership_benchmark_runs_benchmark_created_idx", + "columns": [ + { + "expression": "benchmark_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_benchmark_runs_benchmark_id_mothership_benchmarks_id_fk": { + "name": "mothership_benchmark_runs_benchmark_id_mothership_benchmarks_id_fk", + "tableFrom": "mothership_benchmark_runs", + "tableTo": "mothership_benchmarks", + "columnsFrom": ["benchmark_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mothership_benchmark_runs_score_check": { + "name": "mothership_benchmark_runs_score_check", + "value": "\"mothership_benchmark_runs\".\"total\" > 0 AND \"mothership_benchmark_runs\".\"correct\" >= 0 AND \"mothership_benchmark_runs\".\"correct\" <= \"mothership_benchmark_runs\".\"total\"" + }, + "mothership_benchmark_runs_version_check": { + "name": "mothership_benchmark_runs_version_check", + "value": "\"mothership_benchmark_runs\".\"version\" > 0" + }, + "mothership_benchmark_runs_automatic_score_check": { + "name": "mothership_benchmark_runs_automatic_score_check", + "value": "\"mothership_benchmark_runs\".\"automatic_correct\" >= 0 AND \"mothership_benchmark_runs\".\"automatic_correct\" <= \"mothership_benchmark_runs\".\"total\"" + } + }, + "isRLSEnabled": false + }, + "public.mothership_benchmarks": { + "name": "mothership_benchmarks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_as_user_id": { + "name": "run_as_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "artifacts": { + "name": "artifacts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "running_stage": { + "name": "running_stage", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attempt_id": { + "name": "attempt_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "planner_chat_id": { + "name": "planner_chat_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_benchmarks_owner_created_idx": { + "name": "mothership_benchmarks_owner_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mothership_benchmarks_workspace_idx": { + "name": "mothership_benchmarks_workspace_idx", + "columns": [ + { + "expression": "source_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_benchmarks_organization_id_organization_id_fk": { + "name": "mothership_benchmarks_organization_id_organization_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_user_id_user_id_fk": { + "name": "mothership_benchmarks_user_id_user_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_run_as_user_id_user_id_fk": { + "name": "mothership_benchmarks_run_as_user_id_user_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "user", + "columnsFrom": ["run_as_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_source_workspace_id_workspace_id_fk": { + "name": "mothership_benchmarks_source_workspace_id_workspace_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "workspace", + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mothership_benchmarks_version_check": { + "name": "mothership_benchmarks_version_check", + "value": "\"mothership_benchmarks\".\"version\" > 0" + }, + "mothership_benchmarks_attempt_check": { + "name": "mothership_benchmarks_attempt_check", + "value": "(\"mothership_benchmarks\".\"running_stage\" IS NULL AND \"mothership_benchmarks\".\"attempt_id\" IS NULL AND \"mothership_benchmarks\".\"lease_expires_at\" IS NULL) OR (\"mothership_benchmarks\".\"running_stage\" IS NOT NULL AND \"mothership_benchmarks\".\"running_stage\" IN ('distill', 'redact', 'plan', 'reconstruct', 'grade') AND \"mothership_benchmarks\".\"attempt_id\" IS NOT NULL AND \"mothership_benchmarks\".\"lease_expires_at\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.mothership_inbox_allowed_sender": { + "name": "mothership_inbox_allowed_sender", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "added_by": { + "name": "added_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "inbox_sender_ws_email_idx": { + "name": "inbox_sender_ws_email_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_inbox_allowed_sender_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_allowed_sender_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_allowed_sender", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_inbox_allowed_sender_added_by_user_id_fk": { + "name": "mothership_inbox_allowed_sender_added_by_user_id_fk", + "tableFrom": "mothership_inbox_allowed_sender", + "tableTo": "user", + "columnsFrom": ["added_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_inbox_task": { + "name": "mothership_inbox_task", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_email": { + "name": "from_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sender_authenticated": { + "name": "sender_authenticated", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "from_name": { + "name": "from_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body_preview": { + "name": "body_preview", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_text": { + "name": "body_text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_html": { + "name": "body_html", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_message_id": { + "name": "email_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "in_reply_to": { + "name": "in_reply_to", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "response_message_id": { + "name": "response_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agentmail_message_id": { + "name": "agentmail_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'received'" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "trigger_job_id": { + "name": "trigger_job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "result_summary": { + "name": "result_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rejection_reason": { + "name": "rejection_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "has_attachments": { + "name": "has_attachments", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "cc_recipients": { + "name": "cc_recipients", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "processing_started_at": { + "name": "processing_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "inbox_task_ws_created_at_idx": { + "name": "inbox_task_ws_created_at_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_ws_status_idx": { + "name": "inbox_task_ws_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_response_msg_id_idx": { + "name": "inbox_task_response_msg_id_idx", + "columns": [ + { + "expression": "response_message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_email_msg_id_idx": { + "name": "inbox_task_email_msg_id_idx", + "columns": [ + { + "expression": "email_message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_inbox_task_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_task_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_task", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_inbox_task_chat_id_copilot_chats_id_fk": { + "name": "mothership_inbox_task_chat_id_copilot_chats_id_fk", + "tableFrom": "mothership_inbox_task", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_inbox_webhook": { + "name": "mothership_inbox_webhook", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "webhook_id": { + "name": "webhook_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_inbox_webhook_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_webhook_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_webhook", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "mothership_inbox_webhook_workspace_id_unique": { + "name": "mothership_inbox_webhook_workspace_id_unique", + "nullsNotDistinct": false, + "columns": ["workspace_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_memory_selections": { + "name": "mothership_memory_selections", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "space_id": { + "name": "space_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_memory_selections_user_id_user_id_fk": { + "name": "mothership_memory_selections_user_id_user_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_selections_organization_id_organization_id_fk": { + "name": "mothership_memory_selections_organization_id_organization_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_selections_space_id_mothership_memory_spaces_id_fk": { + "name": "mothership_memory_selections_space_id_mothership_memory_spaces_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "mothership_memory_spaces", + "columnsFrom": ["space_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "mothership_memory_selections_user_id_organization_id_pk": { + "name": "mothership_memory_selections_user_id_organization_id_pk", + "columns": ["user_id", "organization_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_memory_spaces": { + "name": "mothership_memory_spaces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_memory_spaces_owner_idx": { + "name": "mothership_memory_spaces_owner_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_memory_spaces_user_id_user_id_fk": { + "name": "mothership_memory_spaces_user_id_user_id_fk", + "tableFrom": "mothership_memory_spaces", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_spaces_organization_id_organization_id_fk": { + "name": "mothership_memory_spaces_organization_id_organization_id_fk", + "tableFrom": "mothership_memory_spaces", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_resource_effects": { + "name": "mothership_resource_effects", + "schema": "", + "columns": { + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "effect_id": { + "name": "effect_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_resource_effects_chat_id_copilot_chats_id_fk": { + "name": "mothership_resource_effects_chat_id_copilot_chats_id_fk", + "tableFrom": "mothership_resource_effects", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "mothership_resource_effects_chat_id_effect_id_pk": { + "name": "mothership_resource_effects_chat_id_effect_id_pk", + "columns": ["chat_id", "effect_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_access_token": { + "name": "oauth_access_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_id": { + "name": "refresh_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "oauth_access_token_client_id_idx": { + "name": "oauth_access_token_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_session_id_idx": { + "name": "oauth_access_token_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_refresh_id_idx": { + "name": "oauth_access_token_refresh_id_idx", + "columns": [ + { + "expression": "refresh_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_user_client_idx": { + "name": "oauth_access_token_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_expires_at_idx": { + "name": "oauth_access_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_access_token_client_id_oauth_client_client_id_fk": { + "name": "oauth_access_token_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_token_session_id_session_id_fk": { + "name": "oauth_access_token_session_id_session_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_access_token_user_id_user_id_fk": { + "name": "oauth_access_token_user_id_user_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_token_refresh_id_oauth_refresh_token_id_fk": { + "name": "oauth_access_token_refresh_id_oauth_refresh_token_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "oauth_refresh_token", + "columnsFrom": ["refresh_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_access_token_token_unique": { + "name": "oauth_access_token_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": { + "oauth_access_token_search_resource_check": { + "name": "oauth_access_token_search_resource_check", + "value": "NOT ('search:read' = ANY(\"oauth_access_token\".\"scopes\")) OR \"oauth_access_token\".\"resource\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.oauth_client": { + "name": "oauth_client", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_secret": { + "name": "client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "disabled": { + "name": "disabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "skip_consent": { + "name": "skip_consent", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "enable_end_session": { + "name": "enable_end_session", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "subject_type": { + "name": "subject_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "uri": { + "name": "uri", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "contacts": { + "name": "contacts", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "tos": { + "name": "tos", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_id": { + "name": "software_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_version": { + "name": "software_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_statement": { + "name": "software_statement", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "post_logout_redirect_uris": { + "name": "post_logout_redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "token_endpoint_auth_method": { + "name": "token_endpoint_auth_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "grant_types": { + "name": "grant_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "response_types": { + "name": "response_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "require_pkce": { + "name": "require_pkce", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "oauth_client_user_id_idx": { + "name": "oauth_client_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_client_user_id_user_id_fk": { + "name": "oauth_client_user_id_user_id_fk", + "tableFrom": "oauth_client", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_client_client_id_unique": { + "name": "oauth_client_client_id_unique", + "nullsNotDistinct": false, + "columns": ["client_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_consent": { + "name": "oauth_consent", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_consent_client_id_idx": { + "name": "oauth_consent_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_consent_client_id_oauth_client_client_id_fk": { + "name": "oauth_consent_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_consent", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_consent_user_id_user_id_fk": { + "name": "oauth_consent_user_id_user_id_fk", + "tableFrom": "oauth_consent", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_consent_user_client_reference_unique": { + "name": "oauth_consent_user_client_reference_unique", + "nullsNotDistinct": true, + "columns": ["user_id", "client_id", "reference_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_refresh_token": { + "name": "oauth_refresh_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "revoked": { + "name": "revoked", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "auth_time": { + "name": "auth_time", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "family_id": { + "name": "family_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_refresh_token_client_id_idx": { + "name": "oauth_refresh_token_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_session_id_idx": { + "name": "oauth_refresh_token_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_user_client_idx": { + "name": "oauth_refresh_token_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_expires_at_idx": { + "name": "oauth_refresh_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_refresh_token_client_id_oauth_client_client_id_fk": { + "name": "oauth_refresh_token_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_refresh_token_session_id_session_id_fk": { + "name": "oauth_refresh_token_session_id_session_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_refresh_token_user_id_user_id_fk": { + "name": "oauth_refresh_token_user_id_user_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_refresh_token_family_id_oauth_token_family_id_fk": { + "name": "oauth_refresh_token_family_id_oauth_token_family_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "oauth_token_family", + "columnsFrom": ["family_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_refresh_token_token_unique": { + "name": "oauth_refresh_token_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + }, + "oauth_refresh_token_family_generation_unique": { + "name": "oauth_refresh_token_family_generation_unique", + "nullsNotDistinct": false, + "columns": ["family_id", "generation"] + } + }, + "policies": {}, + "checkConstraints": { + "oauth_refresh_token_generation_check": { + "name": "oauth_refresh_token_generation_check", + "value": "\"oauth_refresh_token\".\"generation\" BETWEEN 0 AND 1000" + }, + "oauth_refresh_token_search_resource_check": { + "name": "oauth_refresh_token_search_resource_check", + "value": "NOT ('search:read' = ANY(\"oauth_refresh_token\".\"scopes\")) OR \"oauth_refresh_token\".\"resource\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.oauth_token_family": { + "name": "oauth_token_family", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "consent_id": { + "name": "consent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "current_generation": { + "name": "current_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_token_family_client_id_idx": { + "name": "oauth_token_family_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_session_id_idx": { + "name": "oauth_token_family_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_user_client_idx": { + "name": "oauth_token_family_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_consent_id_idx": { + "name": "oauth_token_family_consent_id_idx", + "columns": [ + { + "expression": "consent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_expires_at_idx": { + "name": "oauth_token_family_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_token_family_client_id_oauth_client_client_id_fk": { + "name": "oauth_token_family_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_token_family_session_id_session_id_fk": { + "name": "oauth_token_family_session_id_session_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_token_family_user_id_user_id_fk": { + "name": "oauth_token_family_user_id_user_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_token_family_consent_id_oauth_consent_id_fk": { + "name": "oauth_token_family_consent_id_oauth_consent_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "oauth_consent", + "columnsFrom": ["consent_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "oauth_token_family_generation_check": { + "name": "oauth_token_family_generation_check", + "value": "\"oauth_token_family\".\"current_generation\" BETWEEN 0 AND 1000" + } + }, + "isRLSEnabled": false + }, + "public.organization": { + "name": "organization", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "session_policy_settings": { + "name": "session_policy_settings", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "security_policy_version": { + "name": "security_policy_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "require_sso": { + "name": "require_sso", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "data_retention_settings": { + "name": "data_retention_settings", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "org_usage_limit": { + "name": "org_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit_notifications": { + "name": "limit_notifications", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "credit_balance": { + "name": "credit_balance", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_access_request_settings": { + "name": "organization_access_request_settings", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "allow_requests": { + "name": "allow_requests", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "organization_access_request_settings_organization_id_organization_id_fk": { + "name": "organization_access_request_settings_organization_id_organization_id_fk", + "tableFrom": "organization_access_request_settings", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_access_request_settings_updated_by_user_id_fk": { + "name": "organization_access_request_settings_updated_by_user_id_fk", + "tableFrom": "organization_access_request_settings", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_byok_keys": { + "name": "organization_byok_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_byok_organization_provider_idx": { + "name": "organization_byok_organization_provider_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_byok_keys_organization_id_organization_id_fk": { + "name": "organization_byok_keys_organization_id_organization_id_fk", + "tableFrom": "organization_byok_keys", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_byok_keys_created_by_user_id_fk": { + "name": "organization_byok_keys_created_by_user_id_fk", + "tableFrom": "organization_byok_keys", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_member_usage_limit": { + "name": "organization_member_usage_limit", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "usage_limit": { + "name": "usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "set_by": { + "name": "set_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "org_member_usage_limit_org_user_unique": { + "name": "org_member_usage_limit_org_user_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "org_member_usage_limit_organization_id_idx": { + "name": "org_member_usage_limit_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_member_usage_limit_organization_id_organization_id_fk": { + "name": "organization_member_usage_limit_organization_id_organization_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_usage_limit_user_id_user_id_fk": { + "name": "organization_member_usage_limit_user_id_user_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_usage_limit_set_by_user_id_fk": { + "name": "organization_member_usage_limit_set_by_user_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "user", + "columnsFrom": ["set_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_history": { + "name": "organization_search_history", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sources": { + "name": "sources", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "queries": { + "name": "queries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": { + "organization_search_history_user_idx": { + "name": "organization_search_history_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_search_history_organization_id_organization_id_fk": { + "name": "organization_search_history_organization_id_organization_id_fk", + "tableFrom": "organization_search_history", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_search_history_user_id_user_id_fk": { + "name": "organization_search_history_user_id_user_id_fk", + "tableFrom": "organization_search_history", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_history_organization_id_user_id_pk": { + "name": "organization_search_history_organization_id_user_id_pk", + "columns": ["organization_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_integration": { + "name": "organization_search_integration", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "approved": { + "name": "approved", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "organization_search_integration_organization_id_organization_id_fk": { + "name": "organization_search_integration_organization_id_organization_id_fk", + "tableFrom": "organization_search_integration", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_integration_organization_id_connector_type_pk": { + "name": "organization_search_integration_organization_id_connector_type_pk", + "columns": ["organization_id", "connector_type"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_mcp_invocation": { + "name": "organization_search_mcp_invocation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_name": { + "name": "client_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_search_mcp_invocation_org_created_idx": { + "name": "organization_search_mcp_invocation_org_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_mcp_invocation_user_idx": { + "name": "organization_search_mcp_invocation_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "org_search_mcp_invocation_org_fk": { + "name": "org_search_mcp_invocation_org_fk", + "tableFrom": "organization_search_mcp_invocation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "org_search_mcp_invocation_user_fk": { + "name": "org_search_mcp_invocation_user_fk", + "tableFrom": "organization_search_mcp_invocation", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_search_mcp_invocation_tool_check": { + "name": "organization_search_mcp_invocation_tool_check", + "value": "\"organization_search_mcp_invocation\".\"tool_name\" IN ('search', 'read_document', 'chat')" + }, + "organization_search_mcp_invocation_outcome_check": { + "name": "organization_search_mcp_invocation_outcome_check", + "value": "\"organization_search_mcp_invocation\".\"outcome\" IN ('success', 'error', 'cancelled', 'rate_limited')" + }, + "organization_search_mcp_invocation_duration_check": { + "name": "organization_search_mcp_invocation_duration_check", + "value": "\"organization_search_mcp_invocation\".\"duration_ms\" >= 0" + }, + "organization_search_mcp_invocation_client_name_check": { + "name": "organization_search_mcp_invocation_client_name_check", + "value": "length(\"organization_search_mcp_invocation\".\"client_name\") <= 256" + }, + "organization_search_mcp_invocation_auth_check": { + "name": "organization_search_mcp_invocation_auth_check", + "value": "(\"organization_search_mcp_invocation\".\"auth_kind\" = 'oauth_access_token' AND \"organization_search_mcp_invocation\".\"oauth_client_id\" IS NOT NULL)\n OR (\"organization_search_mcp_invocation\".\"auth_kind\" IN ('personal_api_key', 'workspace_api_key') AND \"organization_search_mcp_invocation\".\"oauth_client_id\" IS NULL AND \"organization_search_mcp_invocation\".\"client_name\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.organization_secret": { + "name": "organization_secret", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_value": { + "name": "encrypted_value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_secret_shared_unique": { + "name": "organization_secret_shared_unique", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organization_secret\".\"owner_user_id\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_secret_member_unique": { + "name": "organization_secret_member_unique", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organization_secret\".\"owner_user_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_secret_owner_idx": { + "name": "organization_secret_owner_idx", + "columns": [ + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_secret_source_id_organization_secret_source_id_fk": { + "name": "organization_secret_source_id_organization_secret_source_id_fk", + "tableFrom": "organization_secret", + "tableTo": "organization_secret_source", + "columnsFrom": ["source_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_secret_owner_user_id_user_id_fk": { + "name": "organization_secret_owner_user_id_user_id_fk", + "tableFrom": "organization_secret", + "tableTo": "user", + "columnsFrom": ["owner_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_secret_source": { + "name": "organization_secret_source", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_secret_source_org_unique": { + "name": "organization_secret_source_org_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_secret_source_organization_id_organization_id_fk": { + "name": "organization_secret_source_organization_id_organization_id_fk", + "tableFrom": "organization_secret_source", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_secret_source_mode_check": { + "name": "organization_secret_source_mode_check", + "value": "\"organization_secret_source\".\"mode\" IN ('organization', 'member')" + } + }, + "isRLSEnabled": false + }, + "public.outbox_event": { + "name": "outbox_event", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "available_at": { + "name": "available_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "locked_at": { + "name": "locked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "outbox_event_status_available_idx": { + "name": "outbox_event_status_available_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_pending_type_available_idx": { + "name": "outbox_event_pending_type_available_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"outbox_event\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_locked_at_idx": { + "name": "outbox_event_locked_at_idx", + "columns": [ + { + "expression": "locked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_type_created_idx": { + "name": "outbox_event_type_created_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.paused_executions": { + "name": "paused_executions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_snapshot": { + "name": "execution_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "pause_points": { + "name": "pause_points", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "total_pause_count": { + "name": "total_pause_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "resumed_count": { + "name": "resumed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "automatic_resume_retry_count": { + "name": "automatic_resume_retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'paused'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "paused_at": { + "name": "paused_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "next_resume_at": { + "name": "next_resume_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "paused_executions_workflow_id_idx": { + "name": "paused_executions_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_status_idx": { + "name": "paused_executions_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_execution_id_unique": { + "name": "paused_executions_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_next_resume_at_idx": { + "name": "paused_executions_next_resume_at_idx", + "columns": [ + { + "expression": "next_resume_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'paused' AND next_resume_at IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "paused_executions_workflow_id_workflow_id_fk": { + "name": "paused_executions_workflow_id_workflow_id_fk", + "tableFrom": "paused_executions", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pending_credential_draft": { + "name": "pending_credential_draft", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config": { + "name": "oauth_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "pending_draft_organization_id_idx": { + "name": "pending_draft_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pending_draft_user_provider_org": { + "name": "pending_draft_user_provider_org", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pending_draft_user_provider_ws": { + "name": "pending_draft_user_provider_ws", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "pending_credential_draft_user_id_user_id_fk": { + "name": "pending_credential_draft_user_id_user_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_workspace_id_workspace_id_fk": { + "name": "pending_credential_draft_workspace_id_workspace_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_organization_id_organization_id_fk": { + "name": "pending_credential_draft_organization_id_organization_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_credential_id_credential_id_fk": { + "name": "pending_credential_draft_credential_id_credential_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "pending_draft_owner_check": { + "name": "pending_draft_owner_check", + "value": "num_nonnulls(\"pending_credential_draft\".\"workspace_id\", \"pending_credential_draft\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.people_directory_entry": { + "name": "people_directory_entry", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manager_external_id": { + "name": "manager_external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "people_directory_entry_source_id_idx": { + "name": "people_directory_entry_source_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_entry_email_idx": { + "name": "people_directory_entry_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_entry_manager_idx": { + "name": "people_directory_entry_manager_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "manager_external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_entry_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_entry_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_entry", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_page": { + "name": "people_directory_page", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "page_hash": { + "name": "page_hash", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "people_directory_page_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_page_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_page", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_page_organization_id_run_id_page_hash_pk": { + "name": "people_directory_page_organization_id_run_id_page_hash_pk", + "columns": ["organization_id", "run_id", "page_hash"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_scim_change": { + "name": "people_directory_scim_change", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "changed_at": { + "name": "changed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "people_directory_scim_change_due_idx": { + "name": "people_directory_scim_change_due_idx", + "columns": [ + { + "expression": "changed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_scim_change_organization_id_organization_id_fk": { + "name": "people_directory_scim_change_organization_id_organization_id_fk", + "tableFrom": "people_directory_scim_change", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_stage": { + "name": "people_directory_stage", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "proposed_id": { + "name": "proposed_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manager_external_id": { + "name": "manager_external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reports_cursor": { + "name": "reports_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reports_complete": { + "name": "reports_complete", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "people_directory_stage_email_idx": { + "name": "people_directory_stage_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_stage_pending_idx": { + "name": "people_directory_stage_pending_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "NOT \"people_directory_stage\".\"reports_complete\"", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_stage_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_stage_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_stage", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_stage_organization_id_run_id_external_id_pk": { + "name": "people_directory_stage_organization_id_run_id_external_id_pk", + "columns": ["organization_id", "run_id", "external_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_sync": { + "name": "people_directory_sync", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_target": { + "name": "source_target", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_credential": { + "name": "encrypted_credential", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "configured_by": { + "name": "configured_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_token": { + "name": "lease_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "run_started_at": { + "name": "run_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "users_read": { + "name": "users_read", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "retry_count": { + "name": "retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_sync_at": { + "name": "next_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_attempt_at": { + "name": "last_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_success_at": { + "name": "last_success_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_directory_sync_due_idx": { + "name": "people_directory_sync_due_idx", + "columns": [ + { + "expression": "next_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_sync_organization_id_organization_id_fk": { + "name": "people_directory_sync_organization_id_organization_id_fk", + "tableFrom": "people_directory_sync", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "people_directory_sync_configured_by_user_id_fk": { + "name": "people_directory_sync_configured_by_user_id_fk", + "tableFrom": "people_directory_sync", + "tableTo": "user", + "columnsFrom": ["configured_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_access_request": { + "name": "permission_access_request", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requester_id": { + "name": "requester_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope_key": { + "name": "scope_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_key": { + "name": "target_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target": { + "name": "target", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "target_label": { + "name": "target_label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "membership_id": { + "name": "membership_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "group_name": { + "name": "group_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decision": { + "name": "decision", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "decided_at": { + "name": "decided_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "permission_access_request_pending_unique": { + "name": "permission_access_request_pending_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requester_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"permission_access_request\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_access_request_org_queue_idx": { + "name": "permission_access_request_org_queue_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_access_request_requester_idx": { + "name": "permission_access_request_requester_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requester_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_access_request_organization_id_organization_id_fk": { + "name": "permission_access_request_organization_id_organization_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_access_request_requester_id_user_id_fk": { + "name": "permission_access_request_requester_id_user_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "user", + "columnsFrom": ["requester_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_access_request_decided_by_user_id_fk": { + "name": "permission_access_request_decided_by_user_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "user", + "columnsFrom": ["decided_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "permission_access_request_status_check": { + "name": "permission_access_request_status_check", + "value": "\"permission_access_request\".\"status\" in ('pending', 'fulfilled', 'declined', 'cancelled', 'closed')" + } + }, + "isRLSEnabled": false + }, + "public.permission_group": { + "name": "permission_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "membership_mode": { + "name": "membership_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'inherit'" + } + }, + "indexes": { + "permission_group_created_by_idx": { + "name": "permission_group_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_organization_name_unique": { + "name": "permission_group_organization_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_organization_default_unique": { + "name": "permission_group_organization_default_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "is_default = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_organization_id_organization_id_fk": { + "name": "permission_group_organization_id_organization_id_fk", + "tableFrom": "permission_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_created_by_user_id_fk": { + "name": "permission_group_created_by_user_id_fk", + "tableFrom": "permission_group", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_group_member": { + "name": "permission_group_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permission_group_member_group_user_unique": { + "name": "permission_group_member_group_user_unique", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_member_organization_user_idx": { + "name": "permission_group_member_organization_user_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_member_permission_group_id_permission_group_id_fk": { + "name": "permission_group_member_permission_group_id_permission_group_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_organization_id_organization_id_fk": { + "name": "permission_group_member_organization_id_organization_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_user_id_user_id_fk": { + "name": "permission_group_member_user_id_user_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_assigned_by_user_id_fk": { + "name": "permission_group_member_assigned_by_user_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "user", + "columnsFrom": ["assigned_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_group_workspace": { + "name": "permission_group_workspace", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permission_group_workspace_workspace_id_idx": { + "name": "permission_group_workspace_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_workspace_group_workspace_unique": { + "name": "permission_group_workspace_group_workspace_unique", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_workspace_permission_group_id_permission_group_id_fk": { + "name": "permission_group_workspace_permission_group_id_permission_group_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_workspace_workspace_id_workspace_id_fk": { + "name": "permission_group_workspace_workspace_id_workspace_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_workspace_organization_id_organization_id_fk": { + "name": "permission_group_workspace_organization_id_organization_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permissions": { + "name": "permissions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permissions_entity_idx": { + "name": "permissions_entity_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permissions_user_entity_permission_idx": { + "name": "permissions_user_entity_permission_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permissions_unique_constraint": { + "name": "permissions_unique_constraint", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permissions_user_id_user_id_fk": { + "name": "permissions_user_id_user_id_fk", + "tableFrom": "permissions", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pinned_item": { + "name": "pinned_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pinned_at": { + "name": "pinned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "pinned_item_user_workspace_idx": { + "name": "pinned_item_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pinned_item_resource_idx": { + "name": "pinned_item_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pinned_item_user_resource_unique": { + "name": "pinned_item_user_resource_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "pinned_item_user_id_user_id_fk": { + "name": "pinned_item_user_id_user_id_fk", + "tableFrom": "pinned_item", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pinned_item_workspace_id_workspace_id_fk": { + "name": "pinned_item_workspace_id_workspace_id_fk", + "tableFrom": "pinned_item", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project": { + "name": "project", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_scope_key": { + "name": "organization_scope_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END", + "type": "stored" + } + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "project_organization_archive_id_idx": { + "name": "project_organization_archive_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "project_owner_archive_id_idx": { + "name": "project_owner_archive_id_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_organization_id_organization_id_fk": { + "name": "project_organization_id_organization_id_fk", + "tableFrom": "project", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "project_owner_id_user_id_fk": { + "name": "project_owner_id_user_id_fk", + "tableFrom": "project", + "tableTo": "user", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "project_id_organization_scope_unique": { + "name": "project_id_organization_scope_unique", + "nullsNotDistinct": false, + "columns": ["id", "organization_scope_key"] + } + }, + "policies": {}, + "checkConstraints": { + "project_name_length": { + "name": "project_name_length", + "value": "char_length(btrim(\"project\".\"name\")) BETWEEN 1 AND 100" + } + }, + "isRLSEnabled": false + }, + "public.public_share": { + "name": "public_share", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_emails": { + "name": "allowed_emails", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "public_share_entity_id_idx": { + "name": "public_share_entity_id_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_token_unique": { + "name": "public_share_token_unique", + "columns": [ + { + "expression": "token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_resource_unique": { + "name": "public_share_resource_unique", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_resource_id_idx": { + "name": "public_share_resource_id_idx", + "columns": [ + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_workspace_id_idx": { + "name": "public_share_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "public_share_workspace_id_workspace_id_fk": { + "name": "public_share_workspace_id_workspace_id_fk", + "tableFrom": "public_share", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "public_share_created_by_user_id_fk": { + "name": "public_share_created_by_user_id_fk", + "tableFrom": "public_share", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "public_share_entity_binding_check": { + "name": "public_share_entity_binding_check", + "value": "\n (\"public_share\".\"entity_type\" IS NULL AND \"public_share\".\"entity_id\" IS NULL AND \"public_share\".\"workspace_id\" IS NOT NULL)\n OR (\"public_share\".\"entity_type\" IS NOT NULL AND \"public_share\".\"entity_id\" IS NOT NULL AND char_length(\"public_share\".\"entity_id\") > 0\n AND ((\"public_share\".\"entity_type\" = 'workspace' AND \"public_share\".\"workspace_id\" IS NOT NULL AND \"public_share\".\"entity_id\" = \"public_share\".\"workspace_id\")\n OR (\"public_share\".\"entity_type\" = 'project' AND \"public_share\".\"workspace_id\" IS NULL AND \"public_share\".\"resource_type\" = 'file')))\n " + } + }, + "isRLSEnabled": false + }, + "public.rate_limit_bucket": { + "name": "rate_limit_bucket", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "tokens": { + "name": "tokens", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "last_refill_at": { + "name": "last_refill_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "blocked_until": { + "name": "blocked_until", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "capacity_state": { + "name": "capacity_state", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.resource_policy": { + "name": "resource_policy", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "document": { + "name": "document", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "resource_policy_organization_id_idx": { + "name": "resource_policy_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resource_policy_resource_unique": { + "name": "resource_policy_resource_unique", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resource_policy_workspace_id_idx": { + "name": "resource_policy_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resource_policy_workspace_id_workspace_id_fk": { + "name": "resource_policy_workspace_id_workspace_id_fk", + "tableFrom": "resource_policy", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "resource_policy_organization_id_organization_id_fk": { + "name": "resource_policy_organization_id_organization_id_fk", + "tableFrom": "resource_policy", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "resource_policy_created_by_user_id_fk": { + "name": "resource_policy_created_by_user_id_fk", + "tableFrom": "resource_policy", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "resource_policy_updated_by_user_id_fk": { + "name": "resource_policy_updated_by_user_id_fk", + "tableFrom": "resource_policy", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "resource_policy_owner_check": { + "name": "resource_policy_owner_check", + "value": "num_nonnulls(\"resource_policy\".\"workspace_id\", \"resource_policy\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.resume_queue": { + "name": "resume_queue", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "paused_execution_id": { + "name": "paused_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_execution_id": { + "name": "parent_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "new_execution_id": { + "name": "new_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context_id": { + "name": "context_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resume_input": { + "name": "resume_input", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "queued_at": { + "name": "queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "resume_queue_parent_status_idx": { + "name": "resume_queue_parent_status_idx", + "columns": [ + { + "expression": "parent_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resume_queue_new_execution_idx": { + "name": "resume_queue_new_execution_idx", + "columns": [ + { + "expression": "new_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resume_queue_paused_execution_id_paused_executions_id_fk": { + "name": "resume_queue_paused_execution_id_paused_executions_id_fk", + "tableFrom": "resume_queue", + "tableTo": "paused_executions", + "columnsFrom": ["paused_execution_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sandbox_image": { + "name": "sandbox_image", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "spec_hash": { + "name": "spec_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "spec": { + "name": "spec", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "sandbox_image_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "image_ref": { + "name": "image_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_image_id": { + "name": "provider_image_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "materialization_generation": { + "name": "materialization_generation", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_detail": { + "name": "error_detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sandbox_image_provider_spec_unique": { + "name": "sandbox_image_provider_spec_unique", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "spec_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sandbox_image_status_idx": { + "name": "sandbox_image_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sandbox_image_last_used_idx": { + "name": "sandbox_image_last_used_idx", + "columns": [ + { + "expression": "last_used_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_connection": { + "name": "scim_connection", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "settings": { + "name": "settings", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_request_at": { + "name": "last_request_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "reconcile_lock_token": { + "name": "reconcile_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reconcile_lease_at": { + "name": "reconcile_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "reconciled_at": { + "name": "reconciled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_connection_organization_unique": { + "name": "scim_connection_organization_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_connection_reconcile_due_idx": { + "name": "scim_connection_reconcile_due_idx", + "columns": [ + { + "expression": "reconciled_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_connection_organization_id_organization_id_fk": { + "name": "scim_connection_organization_id_organization_id_fk", + "tableFrom": "scim_connection", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_connection_created_by_user_id_fk": { + "name": "scim_connection_created_by_user_id_fk", + "tableFrom": "scim_connection", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_credential": { + "name": "scim_credential", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_by": { + "name": "revoked_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_credential_token_hash_unique": { + "name": "scim_credential_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_credential_connection_idx": { + "name": "scim_credential_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_credential_connection_id_scim_connection_id_fk": { + "name": "scim_credential_connection_id_scim_connection_id_fk", + "tableFrom": "scim_credential", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_credential_revoked_by_user_id_fk": { + "name": "scim_credential_revoked_by_user_id_fk", + "tableFrom": "scim_credential", + "tableTo": "user", + "columnsFrom": ["revoked_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "scim_credential_created_by_user_id_fk": { + "name": "scim_credential_created_by_user_id_fk", + "tableFrom": "scim_credential", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_group": { + "name": "scim_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name_key": { + "name": "display_name_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_connection_display_name_unique": { + "name": "scim_group_connection_display_name_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_connection_external_id_unique": { + "name": "scim_group_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "external_id is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_connection_order_idx": { + "name": "scim_group_connection_order_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_connection_id_scim_connection_id_fk": { + "name": "scim_group_connection_id_scim_connection_id_fk", + "tableFrom": "scim_group", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_group_mapping": { + "name": "scim_group_mapping", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_kind": { + "name": "target_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_mapping_permission_group_idx": { + "name": "scim_group_mapping_permission_group_idx", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_mapping_workspace_idx": { + "name": "scim_group_mapping_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_mapping_group_target_unique": { + "name": "scim_group_mapping_group_target_unique", + "columns": [ + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"permission_group_id\", \"workspace_id\", \"role\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_mapping_group_id_scim_group_id_fk": { + "name": "scim_group_mapping_group_id_scim_group_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "scim_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_permission_group_id_permission_group_id_fk": { + "name": "scim_group_mapping_permission_group_id_permission_group_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_workspace_id_workspace_id_fk": { + "name": "scim_group_mapping_workspace_id_workspace_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_created_by_user_id_fk": { + "name": "scim_group_mapping_created_by_user_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "scim_group_mapping_target_shape": { + "name": "scim_group_mapping_target_shape", + "value": "(\n (\"scim_group_mapping\".\"target_kind\" = 'permission_group' AND \"scim_group_mapping\".\"permission_group_id\" IS NOT NULL AND \"scim_group_mapping\".\"workspace_id\" IS NULL AND \"scim_group_mapping\".\"permission_type\" IS NULL AND \"scim_group_mapping\".\"role\" IS NULL)\n OR (\"scim_group_mapping\".\"target_kind\" = 'workspace' AND \"scim_group_mapping\".\"workspace_id\" IS NOT NULL AND \"scim_group_mapping\".\"permission_type\" IS NOT NULL AND \"scim_group_mapping\".\"permission_group_id\" IS NULL AND \"scim_group_mapping\".\"role\" IS NULL)\n OR (\"scim_group_mapping\".\"target_kind\" = 'org_role' AND \"scim_group_mapping\".\"role\" IS NOT NULL AND \"scim_group_mapping\".\"permission_group_id\" IS NULL AND \"scim_group_mapping\".\"workspace_id\" IS NULL AND \"scim_group_mapping\".\"permission_type\" IS NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.scim_group_member": { + "name": "scim_group_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scim_user_id": { + "name": "scim_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_member_group_user_unique": { + "name": "scim_group_member_group_user_unique", + "columns": [ + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_member_scim_user_idx": { + "name": "scim_group_member_scim_user_idx", + "columns": [ + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_member_group_id_scim_group_id_fk": { + "name": "scim_group_member_group_id_scim_group_id_fk", + "tableFrom": "scim_group_member", + "tableTo": "scim_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_member_scim_user_id_scim_user_id_fk": { + "name": "scim_group_member_scim_user_id_scim_user_id_fk", + "tableFrom": "scim_group_member", + "tableTo": "scim_user", + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_projection_grant": { + "name": "scim_projection_grant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scim_user_id": { + "name": "scim_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_kind": { + "name": "target_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "baseline_permission": { + "name": "baseline_permission", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'directory'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_projection_grant_user_target_unique": { + "name": "scim_projection_grant_user_target_unique", + "columns": [ + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_projection_grant_connection_idx": { + "name": "scim_projection_grant_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_projection_grant_connection_id_scim_connection_id_fk": { + "name": "scim_projection_grant_connection_id_scim_connection_id_fk", + "tableFrom": "scim_projection_grant", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_projection_grant_scim_user_id_scim_user_id_fk": { + "name": "scim_projection_grant_scim_user_id_scim_user_id_fk", + "tableFrom": "scim_projection_grant", + "tableTo": "scim_user", + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_request_log": { + "name": "scim_request_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scim_type": { + "name": "scim_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_request_log_connection_created_idx": { + "name": "scim_request_log_connection_created_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_request_log_connection_id_scim_connection_id_fk": { + "name": "scim_request_log_connection_id_scim_connection_id_fk", + "tableFrom": "scim_request_log", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_user": { + "name": "scim_user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_name": { + "name": "user_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "attributes": { + "name": "attributes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_user_connection_user_unique": { + "name": "scim_user_connection_user_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_user_name_unique": { + "name": "scim_user_connection_user_name_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_external_id_unique": { + "name": "scim_user_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "external_id is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_order_idx": { + "name": "scim_user_connection_order_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_user_idx": { + "name": "scim_user_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_user_connection_id_scim_connection_id_fk": { + "name": "scim_user_connection_id_scim_connection_id_fk", + "tableFrom": "scim_user", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_user_user_id_user_id_fk": { + "name": "scim_user_user_id_user_id_fk", + "tableFrom": "scim_user", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_user_tombstone": { + "name": "scim_user_tombstone", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_user_tombstone_connection_external_id_unique": { + "name": "scim_user_tombstone_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_tombstone_user_idx": { + "name": "scim_user_tombstone_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_user_tombstone_connection_id_scim_connection_id_fk": { + "name": "scim_user_tombstone_connection_id_scim_connection_id_fk", + "tableFrom": "scim_user_tombstone", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_user_tombstone_user_id_user_id_fk": { + "name": "scim_user_tombstone_user_id_user_id_fk", + "tableFrom": "scim_user_tombstone", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.secret_usage": { + "name": "secret_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_name": { + "name": "secret_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_scope": { + "name": "secret_scope", + "type": "secret_usage_scope", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "secret_owner_user_id": { + "name": "secret_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "source": { + "name": "source", + "type": "secret_usage_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "usage_date": { + "name": "usage_date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "use_count": { + "name": "use_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "last_execution_id": { + "name": "last_execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_trigger": { + "name": "last_trigger", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "secret_usage_bucket_unique": { + "name": "secret_usage_bucket_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_date", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "secret_usage_secret_recent_idx": { + "name": "secret_usage_secret_recent_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_used_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "secret_usage_workspace_id_workspace_id_fk": { + "name": "secret_usage_workspace_id_workspace_id_fk", + "tableFrom": "secret_usage", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "active_organization_id": { + "name": "active_organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "session_user_id_idx": { + "name": "session_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "session_active_organization_id_organization_id_fk": { + "name": "session_active_organization_id_organization_id_fk", + "tableFrom": "session", + "tableTo": "organization", + "columnsFrom": ["active_organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "theme": { + "name": "theme", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "auto_connect": { + "name": "auto_connect", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "telemetry_enabled": { + "name": "telemetry_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "email_preferences": { + "name": "email_preferences", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "billing_usage_notifications_enabled": { + "name": "billing_usage_notifications_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "super_user_mode_enabled": { + "name": "super_user_mode_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "mothership_environment": { + "name": "mothership_environment", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "error_notifications_enabled": { + "name": "error_notifications_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "snap_to_grid_size": { + "name": "snap_to_grid_size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "show_action_bar": { + "name": "show_action_bar", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "auto_focus_on_click": { + "name": "auto_focus_on_click", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "copilot_auto_allowed_tools": { + "name": "copilot_auto_allowed_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "last_active_workspace_id": { + "name": "last_active_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "settings_user_id_user_id_fk": { + "name": "settings_user_id_user_id_fk", + "tableFrom": "settings", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "settings_user_id_unique": { + "name": "settings_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sim_link": { + "name": "sim_link", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_name": { + "name": "normalized_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_url": { + "name": "default_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "unlisted": { + "name": "unlisted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "restrict_edit": { + "name": "restrict_edit", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "visit_count": { + "name": "visit_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_visited_at": { + "name": "last_visited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sim_link_organization_name_unique": { + "name": "sim_link_organization_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sim_link_created_by_idx": { + "name": "sim_link_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sim_link_organization_id_organization_id_fk": { + "name": "sim_link_organization_id_organization_id_fk", + "tableFrom": "sim_link", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sim_link_created_by_user_id_fk": { + "name": "sim_link_created_by_user_id_fk", + "tableFrom": "sim_link", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sim_trigger_state": { + "name": "sim_trigger_state", + "schema": "", + "columns": { + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope_key": { + "name": "scope_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "last_fired_at": { + "name": "last_fired_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "sim_trigger_state_workflow_id_workflow_id_fk": { + "name": "sim_trigger_state_workflow_id_workflow_id_fk", + "tableFrom": "sim_trigger_state", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "sim_trigger_state_workflow_id_block_id_scope_key_pk": { + "name": "sim_trigger_state_workflow_id_block_id_scope_key_pk", + "columns": ["workflow_id", "block_id", "scope_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill": { + "name": "skill", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_workspace_name_unique": { + "name": "skill_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_workspace_id_workspace_id_fk": { + "name": "skill_workspace_id_workspace_id_fk", + "tableFrom": "skill", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_user_id_user_id_fk": { + "name": "skill_user_id_user_id_fk", + "tableFrom": "skill", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill_member": { + "name": "skill_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_member_user_id_idx": { + "name": "skill_member_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skill_member_unique": { + "name": "skill_member_unique", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_member_skill_id_skill_id_fk": { + "name": "skill_member_skill_id_skill_id_fk", + "tableFrom": "skill_member", + "tableTo": "skill", + "columnsFrom": ["skill_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_member_user_id_user_id_fk": { + "name": "skill_member_user_id_user_id_fk", + "tableFrom": "skill_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_member_invited_by_user_id_fk": { + "name": "skill_member_invited_by_user_id_fk", + "tableFrom": "skill_member", + "tableTo": "user", + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_app": { + "name": "slack_app", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_client_secret": { + "name": "encrypted_client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_signing_secret": { + "name": "encrypted_signing_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "slack_app_organization_id_organization_id_fk": { + "name": "slack_app_organization_id_organization_id_fk", + "tableFrom": "slack_app", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "slack_app_owner_check": { + "name": "slack_app_owner_check", + "value": "(\"slack_app\".\"kind\" = 'custom' AND \"slack_app\".\"organization_id\" IS NOT NULL) OR (\"slack_app\".\"kind\" = 'shared' AND \"slack_app\".\"organization_id\" IS NULL)" + }, + "slack_app_custom_credentials_check": { + "name": "slack_app_custom_credentials_check", + "value": "\"slack_app\".\"kind\" = 'shared' OR (\"slack_app\".\"client_id\" IS NOT NULL AND \"slack_app\".\"encrypted_client_secret\" IS NOT NULL AND \"slack_app\".\"encrypted_signing_secret\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.slack_search_installation": { + "name": "slack_search_installation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_id": { + "name": "app_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_app_id": { + "name": "slack_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team_name": { + "name": "team_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bot_user_id": { + "name": "bot_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enterprise_id": { + "name": "enterprise_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "credential_version": { + "name": "credential_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_outcome": { + "name": "last_outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_event_at": { + "name": "last_event_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "slack_search_installation_organization_idx": { + "name": "slack_search_installation_organization_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_credential_unique": { + "name": "slack_search_installation_credential_unique", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_app_team_unique": { + "name": "slack_search_installation_app_team_unique", + "columns": [ + { + "expression": "app_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_active_team_unique": { + "name": "slack_search_installation_active_team_unique", + "columns": [ + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"slack_search_installation\".\"enabled\" = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_search_installation_organization_id_organization_id_fk": { + "name": "slack_search_installation_organization_id_organization_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_search_installation_credential_id_credential_id_fk": { + "name": "slack_search_installation_credential_id_credential_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_search_installation_slack_app_id_slack_app_id_fk": { + "name": "slack_search_installation_slack_app_id_slack_app_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "slack_app", + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_search_turn": { + "name": "slack_search_turn", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "slack_search_turn_ordinal_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "conversation_key": { + "name": "conversation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "lease_id": { + "name": "lease_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "slack_search_turn_event_unique": { + "name": "slack_search_turn_event_unique", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_pending_idx": { + "name": "slack_search_turn_pending_idx", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_thread_idx": { + "name": "slack_search_turn_thread_idx", + "columns": [ + { + "expression": "conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_active_thread_unique": { + "name": "slack_search_turn_active_thread_unique", + "columns": [ + { + "expression": "conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"slack_search_turn\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_search_turn_installation_id_slack_search_installation_id_fk": { + "name": "slack_search_turn_installation_id_slack_search_installation_id_fk", + "tableFrom": "slack_search_turn", + "tableTo": "slack_search_installation", + "columnsFrom": ["installation_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sso_domain": { + "name": "sso_domain", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "verification_token": { + "name": "verification_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "verified_at": { + "name": "verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "primary_provider_id": { + "name": "primary_provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sso_domain_domain_idx": { + "name": "sso_domain_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_domain_org_domain_unique": { + "name": "sso_domain_org_domain_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_domain_verified_unique": { + "name": "sso_domain_verified_unique", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "status = 'verified'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sso_domain_organization_id_organization_id_fk": { + "name": "sso_domain_organization_id_organization_id_fk", + "tableFrom": "sso_domain", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sso_domain_created_by_user_id_fk": { + "name": "sso_domain_created_by_user_id_fk", + "tableFrom": "sso_domain", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sso_provider": { + "name": "sso_provider", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oidc_config": { + "name": "oidc_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "saml_config": { + "name": "saml_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "domain_verified": { + "name": "domain_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "jit_provisioning_enabled": { + "name": "jit_provisioning_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + } + }, + "indexes": { + "sso_provider_provider_id_unique": { + "name": "sso_provider_provider_id_unique", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_domain_idx": { + "name": "sso_provider_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_user_id_idx": { + "name": "sso_provider_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_organization_id_idx": { + "name": "sso_provider_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sso_provider_user_id_user_id_fk": { + "name": "sso_provider_user_id_user_id_fk", + "tableFrom": "sso_provider", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sso_provider_organization_id_organization_id_fk": { + "name": "sso_provider_organization_id_organization_id_fk", + "tableFrom": "sso_provider", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.subscription": { + "name": "subscription", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "period_start": { + "name": "period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "period_end": { + "name": "period_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "cancel_at": { + "name": "cancel_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "canceled_at": { + "name": "canceled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "seats": { + "name": "seats", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "trial_start": { + "name": "trial_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trial_end": { + "name": "trial_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "billing_interval": { + "name": "billing_interval", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_schedule_id": { + "name": "stripe_schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "last_closed_period_start": { + "name": "last_closed_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "subscription_reference_status_idx": { + "name": "subscription_reference_status_idx", + "columns": [ + { + "expression": "reference_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "subscription_cycle_close_lagging_idx": { + "name": "subscription_cycle_close_lagging_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"subscription\".\"status\" in ('active', 'past_due') and \"subscription\".\"period_start\" is not null and (\"subscription\".\"last_closed_period_start\" is null or \"subscription\".\"last_closed_period_start\" < \"subscription\".\"period_start\")", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "check_enterprise_metadata": { + "name": "check_enterprise_metadata", + "value": "plan != 'enterprise' OR metadata IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.table_jobs": { + "name": "table_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "rows_processed": { + "name": "rows_processed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "table_jobs_one_active_per_table": { + "name": "table_jobs_one_active_per_table", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"table_jobs\".\"status\" = 'running' AND \"table_jobs\".\"type\" <> 'export'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_jobs_watchdog_idx": { + "name": "table_jobs_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_jobs_table_started_idx": { + "name": "table_jobs_table_started_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_jobs_table_id_user_table_definitions_id_fk": { + "name": "table_jobs_table_id_user_table_definitions_id_fk", + "tableFrom": "table_jobs", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_jobs_workspace_id_workspace_id_fk": { + "name": "table_jobs_workspace_id_workspace_id_fk", + "tableFrom": "table_jobs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_row_executions": { + "name": "table_row_executions", + "schema": "", + "columns": { + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "row_id": { + "name": "row_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "running_block_ids": { + "name": "running_block_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "block_errors": { + "name": "block_errors", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "capability_governed_user_id": { + "name": "capability_governed_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enrichment_details": { + "name": "enrichment_details", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "table_row_executions_table_status_idx": { + "name": "table_row_executions_table_status_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_row_executions\".\"status\" IN ('queued', 'running', 'pending')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_row_executions_execution_id_idx": { + "name": "table_row_executions_execution_id_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_row_executions\".\"execution_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_row_executions_table_group_idx": { + "name": "table_row_executions_table_group_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_row_executions_table_id_user_table_definitions_id_fk": { + "name": "table_row_executions_table_id_user_table_definitions_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_row_executions_row_id_user_table_rows_id_fk": { + "name": "table_row_executions_row_id_user_table_rows_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user_table_rows", + "columnsFrom": ["row_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_row_executions_capability_governed_user_id_user_id_fk": { + "name": "table_row_executions_capability_governed_user_id_user_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user", + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "table_row_executions_row_id_group_id_pk": { + "name": "table_row_executions_row_id_group_id_pk", + "columns": ["row_id", "group_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_run_dispatches": { + "name": "table_run_dispatches", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "cursor": { + "name": "cursor", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit": { + "name": "limit", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "processed_count": { + "name": "processed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_manual_run": { + "name": "is_manual_run", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "triggered_by_user_id": { + "name": "triggered_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capability_governed_user_id": { + "name": "capability_governed_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_at": { + "name": "requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "heartbeat_at": { + "name": "heartbeat_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "table_run_dispatches_active_idx": { + "name": "table_run_dispatches_active_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_run_dispatches_watchdog_idx": { + "name": "table_run_dispatches_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requested_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_run_dispatches_governed_active_idx": { + "name": "table_run_dispatches_governed_active_idx", + "columns": [ + { + "expression": "capability_governed_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_run_dispatches\".\"status\" IN ('pending', 'dispatching')", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_run_dispatches_table_id_user_table_definitions_id_fk": { + "name": "table_run_dispatches_table_id_user_table_definitions_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_run_dispatches_workspace_id_workspace_id_fk": { + "name": "table_run_dispatches_workspace_id_workspace_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_run_dispatches_triggered_by_user_id_user_id_fk": { + "name": "table_run_dispatches_triggered_by_user_id_user_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user", + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "table_run_dispatches_capability_governed_user_id_user_id_fk": { + "name": "table_run_dispatches_capability_governed_user_id_user_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user", + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_views": { + "name": "table_views", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "table_views_table_created_idx": { + "name": "table_views_table_created_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_views_workspace_created_idx": { + "name": "table_views_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_views_table_default_unique": { + "name": "table_views_table_default_unique", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "is_default = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_views_table_id_user_table_definitions_id_fk": { + "name": "table_views_table_id_user_table_definitions_id_fk", + "tableFrom": "table_views", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_views_workspace_id_workspace_id_fk": { + "name": "table_views_workspace_id_workspace_id_fk", + "tableFrom": "table_views", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_views_created_by_user_id_fk": { + "name": "table_views_created_by_user_id_fk", + "tableFrom": "table_views", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.upload_session": { + "name": "upload_session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "purpose": { + "name": "purpose", + "type": "upload_session_purpose", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "upload_session_method", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "storage_context": { + "name": "storage_context", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "final_key": { + "name": "final_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_provider": { + "name": "storage_provider", + "type": "upload_session_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "provider_upload_id": { + "name": "provider_upload_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_object_version": { + "name": "provider_object_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_size": { + "name": "file_size", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "part_size": { + "name": "part_size", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "part_count": { + "name": "part_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "upload_session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'uploading'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "processing_lease_id": { + "name": "processing_lease_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_lease_expires_at": { + "name": "processing_lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_file_id": { + "name": "completed_file_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "upload_session_token_hash_unique": { + "name": "upload_session_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "upload_session_final_key_unique": { + "name": "upload_session_final_key_unique", + "columns": [ + { + "expression": "final_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "upload_session_status_expires_at_idx": { + "name": "upload_session_status_expires_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.usage_log": { + "name": "usage_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category": { + "name": "category", + "type": "usage_log_category", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "usage_log_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "cost": { + "name": "cost", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "event_key": { + "name": "event_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_entity_type": { + "name": "billing_entity_type", + "type": "billing_entity_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "billing_entity_id": { + "name": "billing_entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_period_start": { + "name": "billing_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "billing_period_end": { + "name": "billing_period_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "usage_log_user_created_at_idx": { + "name": "usage_log_user_created_at_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_source_idx": { + "name": "usage_log_source_idx", + "columns": [ + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_workflow_id_idx": { + "name": "usage_log_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_event_key_unique": { + "name": "usage_log_event_key_unique", + "columns": [ + { + "expression": "event_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"usage_log\".\"event_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_billing_entity_period_cost_idx": { + "name": "usage_log_billing_entity_period_cost_idx", + "columns": [ + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_period_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_period_end", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"usage_log\".\"billing_entity_type\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_billing_entity_created_at_cost_idx": { + "name": "usage_log_billing_entity_created_at_cost_idx", + "columns": [ + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"usage_log\".\"billing_entity_type\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_workspace_created_at_cost_idx": { + "name": "usage_log_workspace_created_at_cost_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_execution_id_idx": { + "name": "usage_log_execution_id_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "usage_log_user_id_user_id_fk": { + "name": "usage_log_user_id_user_id_fk", + "tableFrom": "usage_log", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "usage_log_workspace_id_workspace_id_fk": { + "name": "usage_log_workspace_id_workspace_id_fk", + "tableFrom": "usage_log", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "usage_log_workflow_id_workflow_id_fk": { + "name": "usage_log_workflow_id_workflow_id_fk", + "tableFrom": "usage_log", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "usage_log_billing_scope_all_or_none": { + "name": "usage_log_billing_scope_all_or_none", + "value": "(\n (\"usage_log\".\"billing_entity_type\" IS NULL AND \"usage_log\".\"billing_entity_id\" IS NULL AND \"usage_log\".\"billing_period_start\" IS NULL AND \"usage_log\".\"billing_period_end\" IS NULL)\n OR\n (\"usage_log\".\"billing_entity_type\" IS NOT NULL AND \"usage_log\".\"billing_entity_id\" IS NOT NULL AND \"usage_log\".\"billing_period_start\" IS NOT NULL AND \"usage_log\".\"billing_period_end\" IS NOT NULL AND \"usage_log\".\"billing_period_start\" < \"usage_log\".\"billing_period_end\")\n )" + } + }, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_email": { + "name": "normalized_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'user'" + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "suspension_source": { + "name": "suspension_source", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_email_lower_idx": { + "name": "user_email_lower_idx", + "columns": [ + { + "expression": "lower(btrim(\"email\"))", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_gmail_mailbox_idx": { + "name": "user_gmail_mailbox_idx", + "columns": [ + { + "expression": "(CASE WHEN split_part(lower(btrim(\"email\")), '@', 2) IN ('gmail.com', 'googlemail.com') THEN replace(split_part(split_part(lower(btrim(\"email\")), '@', 1), '+', 1), '.', '') || '@gmail.com' END)", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "(CASE WHEN split_part(lower(btrim(\"user\".\"email\")), '@', 2) IN ('gmail.com', 'googlemail.com') THEN replace(split_part(split_part(lower(btrim(\"user\".\"email\")), '@', 1), '+', 1), '.', '') || '@gmail.com' END) IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": ["email"] + }, + "user_normalized_email_unique": { + "name": "user_normalized_email_unique", + "nullsNotDistinct": false, + "columns": ["normalized_email"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_stats": { + "name": "user_stats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "current_usage_limit": { + "name": "current_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'5'" + }, + "usage_limit_updated_at": { + "name": "usage_limit_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "last_period_cost": { + "name": "last_period_cost", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'0'" + }, + "billed_overage_this_period": { + "name": "billed_overage_this_period", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "credit_balance": { + "name": "credit_balance", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "last_period_copilot_cost": { + "name": "last_period_copilot_cost", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'0'" + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "free_tier_eligible": { + "name": "free_tier_eligible", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "billing_blocked": { + "name": "billing_blocked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "billing_blocked_reason": { + "name": "billing_blocked_reason", + "type": "billing_blocked_reason", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "limit_notifications": { + "name": "limit_notifications", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + } + }, + "indexes": {}, + "foreignKeys": { + "user_stats_user_id_user_id_fk": { + "name": "user_stats_user_id_user_id_fk", + "tableFrom": "user_stats", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_stats_user_id_unique": { + "name": "user_stats_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_definitions": { + "name": "user_table_definitions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "schema": { + "name": "schema", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "max_rows": { + "name": "max_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10000 + }, + "row_count": { + "name": "row_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "rows_version": { + "name": "rows_version", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "schema_locked": { + "name": "schema_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "insert_locked": { + "name": "insert_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "update_locked": { + "name": "update_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "delete_locked": { + "name": "delete_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "user_table_def_workspace_id_idx": { + "name": "user_table_def_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_folder_id_idx": { + "name": "user_table_def_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_created_by_idx": { + "name": "user_table_def_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "user_table_def_workspace_name_unique": { + "name": "user_table_def_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"user_table_definitions\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_archived_at_idx": { + "name": "user_table_def_archived_at_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_workspace_archived_partial_idx": { + "name": "user_table_def_workspace_archived_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"user_table_definitions\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_definitions_workspace_id_workspace_id_fk": { + "name": "user_table_definitions_workspace_id_workspace_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_definitions_folder_id_folder_id_fk": { + "name": "user_table_definitions_folder_id_folder_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "user_table_definitions_created_by_user_id_fk": { + "name": "user_table_definitions_created_by_user_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_row_changes": { + "name": "user_table_row_changes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "user_table_row_changes_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "row_delta": { + "name": "row_delta", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "user_table_row_changes_table_id_idx": { + "name": "user_table_row_changes_table_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_row_changes_table_id_user_table_definitions_id_fk": { + "name": "user_table_row_changes_table_id_user_table_definitions_id_fk", + "tableFrom": "user_table_row_changes", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_row_secret_provenance": { + "name": "user_table_row_secret_provenance", + "schema": "", + "columns": { + "row_id": { + "name": "row_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_table_row_secret_provenance_row_id_user_table_rows_id_fk": { + "name": "user_table_row_secret_provenance_row_id_user_table_rows_id_fk", + "tableFrom": "user_table_row_secret_provenance", + "tableTo": "user_table_rows", + "columnsFrom": ["row_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_table_row_secret_provenance_status_check": { + "name": "user_table_row_secret_provenance_status_check", + "value": "\"user_table_row_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.user_table_rows": { + "name": "user_table_rows", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_table_rows_created_by_idx": { + "name": "user_table_rows_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"user_table_rows\".\"created_by\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "user_table_rows_tenant_data_gin_idx": { + "name": "user_table_rows_tenant_data_gin_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"data\" jsonb_path_ops", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "user_table_rows_workspace_table_idx": { + "name": "user_table_rows_workspace_table_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_position_idx": { + "name": "user_table_rows_table_position_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_order_key_idx": { + "name": "user_table_rows_table_order_key_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_created_id_idx": { + "name": "user_table_rows_table_created_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_id_id_idx": { + "name": "user_table_rows_table_id_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_rows_table_id_user_table_definitions_id_fk": { + "name": "user_table_rows_table_id_user_table_definitions_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_rows_workspace_id_workspace_id_fk": { + "name": "user_table_rows_workspace_id_workspace_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_rows_created_by_user_id_fk": { + "name": "user_table_rows_created_by_user_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "verification_expires_at_idx": { + "name": "verification_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.webhook": { + "name": "webhook", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_status": { + "name": "registration_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_generation": { + "name": "registration_generation", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "config_fingerprint": { + "name": "config_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "prepared_at": { + "name": "prepared_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "routing_key": { + "name": "routing_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_config": { + "name": "provider_config", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "path_deployment_unique": { + "name": "path_deployment_unique", + "columns": [ + { + "expression": "path", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_workflow_deployment_idx": { + "name": "webhook_workflow_deployment_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_routing_key_active_idx": { + "name": "webhook_routing_key_active_idx", + "columns": [ + { + "expression": "routing_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"webhook\".\"archived_at\" IS NULL AND \"webhook\".\"routing_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_archived_at_partial_idx": { + "name": "webhook_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"webhook\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_webhook_on_provider_is_active_workflow_id_deploym_bdeed5468": { + "name": "idx_webhook_on_provider_is_active_workflow_id_deploym_bdeed5468", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_webhook_on_workflow_id_block_id_updated_at_desc": { + "name": "idx_webhook_on_workflow_id_block_id_updated_at_desc", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_active_registration_unique": { + "name": "webhook_active_registration_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"registration_status\" = 'active' AND \"webhook\".\"block_id\" IS NOT NULL AND \"webhook\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_candidate_registration_unique": { + "name": "webhook_candidate_registration_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"registration_status\" = 'candidate' AND \"webhook\".\"block_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_registration_status_generation_idx": { + "name": "webhook_registration_status_generation_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "registration_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "registration_generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "webhook_workflow_id_workflow_id_fk": { + "name": "webhook_workflow_id_workflow_id_fk", + "tableFrom": "webhook", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "webhook_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "webhook_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "webhook", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "webhook_registration_status_check": { + "name": "webhook_registration_status_check", + "value": "\"webhook\".\"registration_status\" IS NULL OR \"webhook\".\"registration_status\" IN ('active', 'candidate', 'retired', 'orphaned')" + }, + "webhook_registration_generation_check": { + "name": "webhook_registration_generation_check", + "value": "\"webhook\".\"registration_generation\" IS NULL OR \"webhook\".\"registration_generation\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.webhook_path_claim": { + "name": "webhook_path_claim", + "schema": "", + "columns": { + "path": { + "name": "path", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "webhook_path_claim_workflow_idx": { + "name": "webhook_path_claim_workflow_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "webhook_path_claim_workflow_id_workflow_id_fk": { + "name": "webhook_path_claim_workflow_id_workflow_id_fk", + "tableFrom": "webhook_path_claim", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "webhook_path_claim_generation_check": { + "name": "webhook_path_claim_generation_check", + "value": "\"webhook_path_claim\".\"generation\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.workflow": { + "name": "workflow", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_synced": { + "name": "last_synced", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "is_deployed": { + "name": "is_deployed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deployed_at": { + "name": "deployed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "is_public_api": { + "name": "is_public_api", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "fork_sync_excluded": { + "name": "fork_sync_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_workspace_id_idx": { + "name": "workflow_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_user_workspace_idx": { + "name": "workflow_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_workspace_folder_name_active_unique": { + "name": "workflow_workspace_folder_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_folder_sort_idx": { + "name": "workflow_folder_sort_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_active_workspace_sort_idx": { + "name": "workflow_active_workspace_sort_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_archived_at_idx": { + "name": "workflow_archived_at_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_workspace_archived_partial_idx": { + "name": "workflow_workspace_archived_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_user_id_user_id_fk": { + "name": "workflow_user_id_user_id_fk", + "tableFrom": "workflow", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_workspace_id_workspace_id_fk": { + "name": "workflow_workspace_id_workspace_id_fk", + "tableFrom": "workflow", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_folder_id_folder_id_fk": { + "name": "workflow_folder_id_folder_id_fk", + "tableFrom": "workflow", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_activity_hourly": { + "name": "workflow_activity_hourly", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "runs": { + "name": "runs", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "completed": { + "name": "completed", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cancelled": { + "name": "cancelled", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "in_flight": { + "name": "in_flight", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "duration_sum_ms": { + "name": "duration_sum_ms", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "duration_count": { + "name": "duration_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "computed_at": { + "name": "computed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_activity_hourly_read_idx": { + "name": "workflow_activity_hourly_read_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "bucket_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "runs", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "completed", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "failed", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cancelled", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "in_flight", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "duration_sum_ms", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "duration_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_activity_hourly_bucket_start_idx": { + "name": "workflow_activity_hourly_bucket_start_idx", + "columns": [ + { + "expression": "bucket_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "workflow_activity_hourly_pk": { + "name": "workflow_activity_hourly_pk", + "columns": ["workspace_id", "bucket_start", "workflow_id", "trigger"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_blocks": { + "name": "workflow_blocks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position_x": { + "name": "position_x", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "position_y": { + "name": "position_y", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "horizontal_handles": { + "name": "horizontal_handles", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "is_wide": { + "name": "is_wide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "advanced_mode": { + "name": "advanced_mode", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "trigger_mode": { + "name": "trigger_mode", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "error_enabled": { + "name": "error_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "retry": { + "name": "retry", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "height": { + "name": "height", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "sub_blocks": { + "name": "sub_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "outputs": { + "name": "outputs", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_blocks_workflow_id_idx": { + "name": "workflow_blocks_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_blocks_type_idx": { + "name": "workflow_blocks_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_blocks_workflow_id_workflow_id_fk": { + "name": "workflow_blocks_workflow_id_workflow_id_fk", + "tableFrom": "workflow_blocks", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_checkpoints": { + "name": "workflow_checkpoints", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_state": { + "name": "workflow_state", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_checkpoints_chat_id_idx": { + "name": "workflow_checkpoints_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_message_id_idx": { + "name": "workflow_checkpoints_message_id_idx", + "columns": [ + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_user_workflow_idx": { + "name": "workflow_checkpoints_user_workflow_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_workflow_chat_idx": { + "name": "workflow_checkpoints_workflow_chat_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_created_at_idx": { + "name": "workflow_checkpoints_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_chat_created_at_idx": { + "name": "workflow_checkpoints_chat_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_checkpoints_user_id_user_id_fk": { + "name": "workflow_checkpoints_user_id_user_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_checkpoints_workflow_id_workflow_id_fk": { + "name": "workflow_checkpoints_workflow_id_workflow_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_checkpoints_chat_id_copilot_chats_id_fk": { + "name": "workflow_checkpoints_chat_id_copilot_chats_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_deployment_operation": { + "name": "workflow_deployment_operation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "previous_active_version_id": { + "name": "previous_active_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "protocol_version": { + "name": "protocol_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'preparing'" + }, + "component_readiness": { + "name": "component_readiness", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_deployment_operation_workflow_generation_unique": { + "name": "workflow_deployment_operation_workflow_generation_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_idempotency_unique": { + "name": "workflow_deployment_operation_workflow_idempotency_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_deployment_operation\".\"idempotency_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_in_flight_unique": { + "name": "workflow_deployment_operation_workflow_in_flight_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_deployment_operation\".\"status\" IN ('preparing', 'activating')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_status_idx": { + "name": "workflow_deployment_operation_workflow_status_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_deployment_version_idx": { + "name": "workflow_deployment_operation_deployment_version_idx", + "columns": [ + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_version_generation_idx": { + "name": "workflow_deployment_operation_workflow_version_generation_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_deployment_operation_workflow_id_workflow_id_fk": { + "name": "workflow_deployment_operation_workflow_id_workflow_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_deployment_operation_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_deployment_operation_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_deployment_operation_previous_active_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_deployment_operation_previous_active_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["previous_active_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workflow_deployment_operation_action_check": { + "name": "workflow_deployment_operation_action_check", + "value": "\"workflow_deployment_operation\".\"action\" IN ('deploy', 'activate')" + }, + "workflow_deployment_operation_status_check": { + "name": "workflow_deployment_operation_status_check", + "value": "\"workflow_deployment_operation\".\"status\" IN ('preparing', 'activating', 'active', 'failed', 'superseded')" + }, + "workflow_deployment_operation_generation_check": { + "name": "workflow_deployment_operation_generation_check", + "value": "\"workflow_deployment_operation\".\"generation\" > 0" + }, + "workflow_deployment_operation_protocol_version_check": { + "name": "workflow_deployment_operation_protocol_version_check", + "value": "\"workflow_deployment_operation\".\"protocol_version\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.workflow_deployment_version": { + "name": "workflow_deployment_version", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_deployment_version_workflow_version_unique": { + "name": "workflow_deployment_version_workflow_version_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_version_workflow_active_idx": { + "name": "workflow_deployment_version_workflow_active_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_version_created_at_idx": { + "name": "workflow_deployment_version_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_deployment_version_workflow_id_workflow_id_fk": { + "name": "workflow_deployment_version_workflow_id_workflow_id_fk", + "tableFrom": "workflow_deployment_version", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_edges": { + "name": "workflow_edges", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_block_id": { + "name": "source_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_block_id": { + "name": "target_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_handle": { + "name": "source_handle", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_handle": { + "name": "target_handle", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_edges_workflow_source_idx": { + "name": "workflow_edges_workflow_source_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_workflow_target_idx": { + "name": "workflow_edges_workflow_target_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_source_block_fk_idx": { + "name": "workflow_edges_source_block_fk_idx", + "columns": [ + { + "expression": "source_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_target_block_fk_idx": { + "name": "workflow_edges_target_block_fk_idx", + "columns": [ + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_edges_workflow_id_workflow_id_fk": { + "name": "workflow_edges_workflow_id_workflow_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_edges_source_block_id_workflow_blocks_id_fk": { + "name": "workflow_edges_source_block_id_workflow_blocks_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow_blocks", + "columnsFrom": ["source_block_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_edges_target_block_id_workflow_blocks_id_fk": { + "name": "workflow_edges_target_block_id_workflow_blocks_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow_blocks", + "columnsFrom": ["target_block_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_execution_logs": { + "name": "workflow_execution_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state_snapshot_id": { + "name": "state_snapshot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "execution_deadline_at": { + "name": "execution_deadline_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_duration_ms": { + "name": "total_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "execution_data": { + "name": "execution_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "cost_total": { + "name": "cost_total", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "models_used": { + "name": "models_used", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_execution_logs_state_snapshot_id_idx": { + "name": "workflow_execution_logs_state_snapshot_id_idx", + "columns": [ + { + "expression": "state_snapshot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_deployment_version_id_idx": { + "name": "workflow_execution_logs_deployment_version_id_idx", + "columns": [ + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_trigger_idx": { + "name": "workflow_execution_logs_trigger_idx", + "columns": [ + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_level_idx": { + "name": "workflow_execution_logs_level_idx", + "columns": [ + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_started_at_idx": { + "name": "workflow_execution_logs_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_execution_id_unique": { + "name": "workflow_execution_logs_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workflow_started_at_idx": { + "name": "workflow_execution_logs_workflow_started_at_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_activity_level_idx": { + "name": "workflow_execution_logs_workspace_activity_level_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "total_duration_ms", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_started_at_id_desc_idx": { + "name": "workflow_execution_logs_workspace_started_at_id_desc_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC NULLS LAST", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "\"id\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_cost_total_idx": { + "name": "workflow_execution_logs_workspace_cost_total_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost_total", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_models_used_idx": { + "name": "workflow_execution_logs_models_used_idx", + "columns": [ + { + "expression": "models_used", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "workflow_execution_logs_workspace_ended_at_id_idx": { + "name": "workflow_execution_logs_workspace_ended_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"ended_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_running_started_at_idx": { + "name": "workflow_execution_logs_running_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_running_deadline_idx": { + "name": "workflow_execution_logs_running_deadline_idx", + "columns": [ + { + "expression": "execution_deadline_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'running' AND \"workflow_execution_logs\".\"execution_deadline_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_redacting_started_at_idx": { + "name": "workflow_execution_logs_redacting_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'redacting'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_redacting_deadline_idx": { + "name": "workflow_execution_logs_redacting_deadline_idx", + "columns": [ + { + "expression": "execution_deadline_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'redacting' AND \"workflow_execution_logs\".\"execution_deadline_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_completed_ended_at_idx": { + "name": "workflow_execution_logs_completed_ended_at_idx", + "columns": [ + { + "expression": "ended_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'completed' AND \"workflow_execution_logs\".\"level\" = 'info' AND \"workflow_execution_logs\".\"ended_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_late_end_idx": { + "name": "workflow_execution_logs_late_end_idx", + "columns": [ + { + "expression": "ended_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"ended_at\" >= \"workflow_execution_logs\".\"started_at\" + interval '2 hours'", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_execution_logs_workflow_id_workflow_id_fk": { + "name": "workflow_execution_logs_workflow_id_workflow_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workflow_execution_logs_workspace_id_workspace_id_fk": { + "name": "workflow_execution_logs_workspace_id_workspace_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_execution_logs_state_snapshot_id_workflow_execution_snapshots_id_fk": { + "name": "workflow_execution_logs_state_snapshot_id_workflow_execution_snapshots_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow_execution_snapshots", + "columnsFrom": ["state_snapshot_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workflow_execution_logs_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_execution_logs_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_execution_snapshots": { + "name": "workflow_execution_snapshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state_hash": { + "name": "state_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state_data": { + "name": "state_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_snapshots_hash_idx": { + "name": "workflow_snapshots_hash_idx", + "columns": [ + { + "expression": "state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_snapshots_workflow_hash_idx": { + "name": "workflow_snapshots_workflow_hash_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_snapshots_created_at_idx": { + "name": "workflow_snapshots_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_execution_snapshots_workflow_id_workflow_id_fk": { + "name": "workflow_execution_snapshots_workflow_id_workflow_id_fk", + "tableFrom": "workflow_execution_snapshots", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_mcp_server": { + "name": "workflow_mcp_server", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_public": { + "name": "is_public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_mcp_server_workspace_id_idx": { + "name": "workflow_mcp_server_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_created_by_idx": { + "name": "workflow_mcp_server_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_deleted_at_idx": { + "name": "workflow_mcp_server_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_workspace_deleted_partial_idx": { + "name": "workflow_mcp_server_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_mcp_server\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_mcp_server_workspace_id_workspace_id_fk": { + "name": "workflow_mcp_server_workspace_id_workspace_id_fk", + "tableFrom": "workflow_mcp_server", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_mcp_server_created_by_user_id_fk": { + "name": "workflow_mcp_server_created_by_user_id_fk", + "tableFrom": "workflow_mcp_server", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_mcp_tool": { + "name": "workflow_mcp_tool", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "server_id": { + "name": "server_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_description": { + "name": "tool_description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parameter_schema": { + "name": "parameter_schema", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "parameter_description_overrides": { + "name": "parameter_description_overrides", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'::json" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_mcp_tool_server_id_idx": { + "name": "workflow_mcp_tool_server_id_idx", + "columns": [ + { + "expression": "server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_workflow_id_idx": { + "name": "workflow_mcp_tool_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_server_workflow_unique": { + "name": "workflow_mcp_tool_server_workflow_unique", + "columns": [ + { + "expression": "server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_mcp_tool\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_archived_at_partial_idx": { + "name": "workflow_mcp_tool_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_mcp_tool\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_mcp_tool_server_id_workflow_mcp_server_id_fk": { + "name": "workflow_mcp_tool_server_id_workflow_mcp_server_id_fk", + "tableFrom": "workflow_mcp_tool", + "tableTo": "workflow_mcp_server", + "columnsFrom": ["server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_mcp_tool_workflow_id_workflow_id_fk": { + "name": "workflow_mcp_tool_workflow_id_workflow_id_fk", + "tableFrom": "workflow_mcp_tool", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_schedule": { + "name": "workflow_schedule", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_operation_id": { + "name": "deployment_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cron_expression": { + "name": "cron_expression", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_ran_at": { + "name": "last_ran_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_queued_at": { + "name": "last_queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trigger_type": { + "name": "trigger_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'UTC'" + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "infra_retry_count": { + "name": "infra_retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'workflow'" + }, + "job_title": { + "name": "job_title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'persistent'" + }, + "success_condition": { + "name": "success_condition", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "max_runs": { + "name": "max_runs", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "source_chat_id": { + "name": "source_chat_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_task_name": { + "name": "source_task_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_user_id": { + "name": "source_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_scope": { + "name": "secret_scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'all'" + }, + "mounted_secrets": { + "name": "mounted_secrets", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "job_history": { + "name": "job_history", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "contexts": { + "name": "contexts", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "excluded_dates": { + "name": "excluded_dates", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_budget_usd": { + "name": "run_budget_usd", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_schedule_workflow_block_deployment_unique": { + "name": "workflow_schedule_workflow_block_deployment_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_workflow_deployment_idx": { + "name": "workflow_schedule_workflow_deployment_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_archived_at_partial_idx": { + "name": "workflow_schedule_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_workflow_schedule_on_source_workspace_id_source_t_c07f3bba6": { + "name": "idx_workflow_schedule_on_source_workspace_id_source_t_c07f3bba6", + "columns": [ + { + "expression": "source_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_due_workflow_idx": { + "name": "workflow_schedule_due_workflow_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL AND \"workflow_schedule\".\"status\" NOT IN ('disabled', 'completed') AND (\"workflow_schedule\".\"source_type\" = 'workflow' OR \"workflow_schedule\".\"source_type\" IS NULL)", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_due_job_idx": { + "name": "workflow_schedule_due_job_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL AND \"workflow_schedule\".\"status\" NOT IN ('disabled', 'completed') AND \"workflow_schedule\".\"source_type\" = 'job'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_schedule_workflow_id_workflow_id_fk": { + "name": "workflow_schedule_workflow_id_workflow_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_schedule_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_deployment_operation_id_workflow_deployment_operation_id_fk": { + "name": "workflow_schedule_deployment_operation_id_workflow_deployment_operation_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow_deployment_operation", + "columnsFrom": ["deployment_operation_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workflow_schedule_source_user_id_user_id_fk": { + "name": "workflow_schedule_source_user_id_user_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "user", + "columnsFrom": ["source_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_source_workspace_id_workspace_id_fk": { + "name": "workflow_schedule_source_workspace_id_workspace_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workspace", + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_source_meta": { + "name": "workflow_source_meta", + "schema": "", + "columns": { + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "meta": { + "name": "meta", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workflow_source_meta_workflow_id_workflow_id_fk": { + "name": "workflow_source_meta_workflow_id_workflow_id_fk", + "tableFrom": "workflow_source_meta", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_subflows": { + "name": "workflow_subflows", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_subflows_workflow_type_idx": { + "name": "workflow_subflows_workflow_type_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_subflows_workflow_id_workflow_id_fk": { + "name": "workflow_subflows_workflow_id_workflow_id_fk", + "tableFrom": "workflow_subflows", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_test": { + "name": "workflow_test", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_file_id": { + "name": "body_file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cases": { + "name": "cases", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_test_workspace_name_unique": { + "name": "workflow_test_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_test\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_test_body_file_unique": { + "name": "workflow_test_body_file_unique", + "columns": [ + { + "expression": "body_file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_test_workspace_id_workspace_id_fk": { + "name": "workflow_test_workspace_id_workspace_id_fk", + "tableFrom": "workflow_test", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_body_file_id_workspace_files_id_fk": { + "name": "workflow_test_body_file_id_workspace_files_id_fk", + "tableFrom": "workflow_test", + "tableTo": "workspace_files", + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workflow_test_created_by_user_id_user_id_fk": { + "name": "workflow_test_created_by_user_id_user_id_fk", + "tableFrom": "workflow_test", + "tableTo": "user", + "columnsFrom": ["created_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_test_run": { + "name": "workflow_test_run", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "test_id": { + "name": "test_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "passed": { + "name": "passed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "skipped": { + "name": "skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "report": { + "name": "report", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ran_against": { + "name": "ran_against", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "progress": { + "name": "progress", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "triggered_by_actor": { + "name": "triggered_by_actor", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "triggered_by_user_id": { + "name": "triggered_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_test_run_test_version_started_idx": { + "name": "workflow_test_run_test_version_started_idx", + "columns": [ + { + "expression": "test_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_test_run_test_id_workflow_test_id_fk": { + "name": "workflow_test_run_test_id_workflow_test_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "workflow_test", + "columnsFrom": ["test_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_run_workspace_id_workspace_id_fk": { + "name": "workflow_test_run_workspace_id_workspace_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_run_triggered_by_user_id_user_id_fk": { + "name": "workflow_test_run_triggered_by_user_id_user_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "user", + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workflow_test_run_version_check": { + "name": "workflow_test_run_version_check", + "value": "\"workflow_test_run\".\"version\" IN ('draft', 'deployed')" + }, + "workflow_test_run_status_check": { + "name": "workflow_test_run_status_check", + "value": "\"workflow_test_run\".\"status\" IN ('running', 'passed', 'failed', 'error')" + }, + "workflow_test_run_completed_check": { + "name": "workflow_test_run_completed_check", + "value": "(\"workflow_test_run\".\"status\" = 'running') = (\"workflow_test_run\".\"completed_at\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workload_identity_pending_subject": { + "name": "workload_identity_pending_subject", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "workload_identity_pending_subject_subject_unique": { + "name": "workload_identity_pending_subject_subject_unique", + "columns": [ + { + "expression": "subject", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workload_identity_pending_subject_issuer_idx": { + "name": "workload_identity_pending_subject_issuer_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workload_identity_pending_subject_user_id_idx": { + "name": "workload_identity_pending_subject_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workload_identity_pending_subject_workspace_id_workspace_id_fk": { + "name": "workload_identity_pending_subject_workspace_id_workspace_id_fk", + "tableFrom": "workload_identity_pending_subject", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workload_identity_pending_subject_user_id_user_id_fk": { + "name": "workload_identity_pending_subject_user_id_user_id_fk", + "tableFrom": "workload_identity_pending_subject", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace": { + "name": "workspace", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'#33C482'" + }, + "logo_url": { + "name": "logo_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_scope_key": { + "name": "organization_scope_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END", + "type": "stored" + } + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_mode": { + "name": "workspace_mode", + "type": "workspace_mode", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'grandfathered_shared'" + }, + "billed_account_user_id": { + "name": "billed_account_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "allow_personal_api_keys": { + "name": "allow_personal_api_keys", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "inbox_enabled": { + "name": "inbox_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "inbox_address": { + "name": "inbox_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbox_provider_id": { + "name": "inbox_provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbox_secret_scope": { + "name": "inbox_secret_scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'all'" + }, + "inbox_mounted_secrets": { + "name": "inbox_mounted_secrets", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "organization_assigned_at": { + "name": "organization_assigned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "forked_from_workspace_id": { + "name": "forked_from_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fork_sync_new_workflows_excluded": { + "name": "fork_sync_new_workflows_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_owner_id_idx": { + "name": "workspace_owner_id_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_organization_id_idx": { + "name": "workspace_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_billed_account_user_id_idx": { + "name": "workspace_billed_account_user_id_idx", + "columns": [ + { + "expression": "billed_account_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_project_id_id_idx": { + "name": "workspace_project_id_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_mode_idx": { + "name": "workspace_mode_idx", + "columns": [ + { + "expression": "workspace_mode", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_forked_from_workspace_id_idx": { + "name": "workspace_forked_from_workspace_id_idx", + "columns": [ + { + "expression": "forked_from_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_inbox_provider_id_idx": { + "name": "workspace_inbox_provider_id_idx", + "columns": [ + { + "expression": "inbox_provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace\".\"inbox_provider_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_owner_id_user_id_fk": { + "name": "workspace_owner_id_user_id_fk", + "tableFrom": "workspace", + "tableTo": "user", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_organization_id_organization_id_fk": { + "name": "workspace_organization_id_organization_id_fk", + "tableFrom": "workspace", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_project_id_project_id_fk": { + "name": "workspace_project_id_project_id_fk", + "tableFrom": "workspace", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "workspace_billed_account_user_id_user_id_fk": { + "name": "workspace_billed_account_user_id_user_id_fk", + "tableFrom": "workspace", + "tableTo": "user", + "columnsFrom": ["billed_account_user_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workspace_forked_from_workspace_id_workspace_id_fk": { + "name": "workspace_forked_from_workspace_id_workspace_id_fk", + "tableFrom": "workspace", + "tableTo": "workspace", + "columnsFrom": ["forked_from_workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_project_organization_fk": { + "name": "workspace_project_organization_fk", + "tableFrom": "workspace", + "tableTo": "project", + "columnsFrom": ["project_id", "organization_scope_key"], + "columnsTo": ["id", "organization_scope_key"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workspace_fork_project_fk": { + "name": "workspace_fork_project_fk", + "tableFrom": "workspace", + "tableTo": "workspace", + "columnsFrom": ["forked_from_workspace_id", "project_id"], + "columnsTo": ["id", "project_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "workspace_id_project_unique": { + "name": "workspace_id_project_unique", + "nullsNotDistinct": false, + "columns": ["id", "project_id"] + } + }, + "policies": {}, + "checkConstraints": { + "workspace_storage_used_bytes_non_negative": { + "name": "workspace_storage_used_bytes_non_negative", + "value": "\"workspace\".\"storage_used_bytes\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.workspace_byok_keys": { + "name": "workspace_byok_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_byok_workspace_provider_idx": { + "name": "workspace_byok_workspace_provider_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_byok_keys_workspace_id_workspace_id_fk": { + "name": "workspace_byok_keys_workspace_id_workspace_id_fk", + "tableFrom": "workspace_byok_keys", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_byok_keys_created_by_user_id_fk": { + "name": "workspace_byok_keys_created_by_user_id_fk", + "tableFrom": "workspace_byok_keys", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_environment": { + "name": "workspace_environment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_environment_workspace_unique": { + "name": "workspace_environment_workspace_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_environment_workspace_id_workspace_id_fk": { + "name": "workspace_environment_workspace_id_workspace_id_fk", + "tableFrom": "workspace_environment", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file": { + "name": "workspace_file", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_file_workspace_id_idx": { + "name": "workspace_file_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_deleted_at_idx": { + "name": "workspace_file_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_workspace_deleted_partial_idx": { + "name": "workspace_file_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_uploaded_by_idx": { + "name": "workspace_file_uploaded_by_idx", + "columns": [ + { + "expression": "uploaded_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_workspace_id_workspace_id_fk": { + "name": "workspace_file_workspace_id_workspace_id_fk", + "tableFrom": "workspace_file", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_uploaded_by_user_id_fk": { + "name": "workspace_file_uploaded_by_user_id_fk", + "tableFrom": "workspace_file", + "tableTo": "user", + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "workspace_file_key_unique": { + "name": "workspace_file_key_unique", + "nullsNotDistinct": false, + "columns": ["key"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_collab_state": { + "name": "workspace_file_collab_state", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "doc_state": { + "name": "doc_state", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_file_collab_state_file_id_workspace_files_id_fk": { + "name": "workspace_file_collab_state_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_collab_state", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_search_backfill": { + "name": "workspace_file_search_backfill", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "after_workspace_id": { + "name": "after_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_entity_type": { + "name": "after_entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_entity_id": { + "name": "after_entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_file_id": { + "name": "after_file_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_search_build": { + "name": "workspace_file_search_build", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "artifact_key": { + "name": "artifact_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_file_search_build_file_idx": { + "name": "workspace_file_search_build_file_idx", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_build_cleanup_idx": { + "name": "workspace_file_search_build_cleanup_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_build\".\"expires_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_build_owner_check": { + "name": "file_search_build_owner_check", + "value": "(\"workspace_file_search_build\".\"entity_type\" IS NULL AND \"workspace_file_search_build\".\"entity_id\" IS NULL AND \"workspace_file_search_build\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_build\".\"entity_type\" = 'workspace' AND \"workspace_file_search_build\".\"entity_id\" = \"workspace_file_search_build\".\"workspace_id\") OR (\"workspace_file_search_build\".\"entity_type\" = 'project' AND length(\"workspace_file_search_build\".\"entity_id\") > 0 AND \"workspace_file_search_build\".\"workspace_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_search_chunk": { + "name": "workspace_file_search_chunk", + "schema": "", + "columns": { + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "line_start": { + "name": "line_start", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "fragment": { + "name": "fragment", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "overlap": { + "name": "overlap", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "file_search_chunk_owner_content_idx": { + "name": "file_search_chunk_owner_content_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "content", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_chunk\".\"entity_type\" = 'project'", + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "workspace_file_search_chunk_line_idx": { + "name": "workspace_file_search_chunk_line_idx", + "columns": [ + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "line_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ordinal", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_chunk_content_idx": { + "name": "workspace_file_search_chunk_content_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "content", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + } + }, + "foreignKeys": { + "workspace_file_search_chunk_build_id_workspace_file_search_build_id_fk": { + "name": "workspace_file_search_chunk_build_id_workspace_file_search_build_id_fk", + "tableFrom": "workspace_file_search_chunk", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_file_search_chunk_pk": { + "name": "workspace_file_search_chunk_pk", + "columns": ["build_id", "ordinal"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_chunk_owner_check": { + "name": "file_search_chunk_owner_check", + "value": "(\"workspace_file_search_chunk\".\"entity_type\" IS NULL AND \"workspace_file_search_chunk\".\"entity_id\" IS NULL AND \"workspace_file_search_chunk\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_chunk\".\"entity_type\" = 'workspace' AND \"workspace_file_search_chunk\".\"entity_id\" = \"workspace_file_search_chunk\".\"workspace_id\") OR (\"workspace_file_search_chunk\".\"entity_type\" = 'project' AND length(\"workspace_file_search_chunk\".\"entity_id\") > 0 AND \"workspace_file_search_chunk\".\"workspace_id\" IS NULL)" + }, + "workspace_file_search_chunk_content_size": { + "name": "workspace_file_search_chunk_content_size", + "value": "octet_length(\"workspace_file_search_chunk\".\"content\") <= 8192" + }, + "workspace_file_search_chunk_position": { + "name": "workspace_file_search_chunk_position", + "value": "\"workspace_file_search_chunk\".\"ordinal\" >= 0 AND \"workspace_file_search_chunk\".\"line_start\" > 0 AND \"workspace_file_search_chunk\".\"overlap\" BETWEEN 0 AND 2" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_search_revision": { + "name": "workspace_file_search_revision", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "workspace_file_search_index_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "line_count": { + "name": "line_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "indexed_bytes": { + "name": "indexed_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "dispatched_at": { + "name": "dispatched_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "handoff_expires_at": { + "name": "handoff_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "file_search_revision_owner_pending_idx": { + "name": "file_search_revision_owner_pending_idx", + "columns": [ + { + "expression": "coalesce(\"entity_type\", 'workspace')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"entity_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_content_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "file_search_revision_owner_status_idx": { + "name": "file_search_revision_owner_status_idx", + "columns": [ + { + "expression": "coalesce(\"entity_type\", 'workspace')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"entity_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_workspace_status_idx": { + "name": "workspace_file_search_revision_workspace_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_build_idx": { + "name": "workspace_file_search_revision_build_idx", + "columns": [ + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_pending_idx": { + "name": "workspace_file_search_revision_pending_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_content_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_active_idx": { + "name": "workspace_file_search_revision_active_idx", + "columns": [ + { + "expression": "dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_search_revision_file_id_workspace_files_id_fk": { + "name": "workspace_file_search_revision_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_search_revision", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_search_revision_build_id_workspace_file_search_build_id_fk": { + "name": "workspace_file_search_revision_build_id_workspace_file_search_build_id_fk", + "tableFrom": "workspace_file_search_revision", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_revision_owner_check": { + "name": "file_search_revision_owner_check", + "value": "(\"workspace_file_search_revision\".\"entity_type\" IS NULL AND \"workspace_file_search_revision\".\"entity_id\" IS NULL AND \"workspace_file_search_revision\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_revision\".\"entity_type\" = 'workspace' AND \"workspace_file_search_revision\".\"entity_id\" = \"workspace_file_search_revision\".\"workspace_id\") OR (\"workspace_file_search_revision\".\"entity_type\" = 'project' AND length(\"workspace_file_search_revision\".\"entity_id\") > 0 AND \"workspace_file_search_revision\".\"workspace_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_secret_provenance": { + "name": "workspace_file_secret_provenance", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_file_secret_provenance_file_id_workspace_files_id_fk": { + "name": "workspace_file_secret_provenance_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_secret_provenance", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_file_secret_provenance_status_check": { + "name": "workspace_file_secret_provenance_status_check", + "value": "\"workspace_file_secret_provenance\".\"status\" IN ('exact', 'unknown', 'unrecorded')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_version": { + "name": "workspace_file_version", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "superseded_at": { + "name": "superseded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "workspace_file_version_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "author_user_ids": { + "name": "author_user_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "restored_from_version": { + "name": "restored_from_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_status": { + "name": "secret_provenance_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_entries": { + "name": "secret_provenance_entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_file_version_file_version_unique": { + "name": "workspace_file_version_file_version_unique", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_key_unique": { + "name": "workspace_file_version_key_unique", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_workspace_id_idx": { + "name": "workspace_file_version_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_workspace_superseded_idx": { + "name": "workspace_file_version_workspace_superseded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "superseded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_version\".\"superseded_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_version_file_id_workspace_files_id_fk": { + "name": "workspace_file_version_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_version", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_version_workspace_id_workspace_id_fk": { + "name": "workspace_file_version_workspace_id_workspace_id_fk", + "tableFrom": "workspace_file_version", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_file_version_provenance_status_check": { + "name": "workspace_file_version_provenance_status_check", + "value": "\"workspace_file_version\".\"secret_provenance_status\" IS NULL OR \"workspace_file_version\".\"secret_provenance_status\" IN ('exact', 'unknown', 'unrecorded')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_files": { + "name": "workspace_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "context": { + "name": "context", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "original_name": { + "name": "original_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "date_trunc('milliseconds', now())" + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_files_project_id_idx": { + "name": "workspace_files_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_project_folder_name_active_unique": { + "name": "workspace_files_project_folder_name_active_unique", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"project_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_key_active_unique": { + "name": "workspace_files_key_active_unique", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_folder_name_active_unique": { + "name": "workspace_files_workspace_folder_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_search_owner_keyset_idx": { + "name": "workspace_files_search_owner_keyset_idx", + "columns": [ + { + "expression": "(CASE WHEN \"project_id\" IS NOT NULL THEN 'project' ELSE 'workspace' END)", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"project_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND ((\"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL) OR (\"workspace_files\".\"context\" = 'project' AND \"workspace_files\".\"project_id\" IS NOT NULL))", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_keyset_idx": { + "name": "workspace_files_workspace_active_keyset_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_uploaded_idx": { + "name": "workspace_files_workspace_active_uploaded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_updated_idx": { + "name": "workspace_files_workspace_active_updated_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_folder_uploaded_idx": { + "name": "workspace_files_workspace_folder_uploaded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_name_trgm_idx": { + "name": "workspace_files_workspace_name_trgm_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "workspace_files_workspace_display_name_idx": { + "name": "workspace_files_workspace_display_name_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "regexp_replace(regexp_replace(regexp_replace(normalize(\"original_name\", NFC), '^[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+|[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+$', '', 'g'), '[\\x01-\\x1f\\x7f]', '', 'g'), '[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+', ' ', 'g')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_chat_display_name_unique": { + "name": "workspace_files_chat_display_name_unique", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"context\" = 'mothership' AND \"workspace_files\".\"chat_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_organization_id_idx": { + "name": "workspace_files_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_key_idx": { + "name": "workspace_files_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_user_id_idx": { + "name": "workspace_files_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_id_idx": { + "name": "workspace_files_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_folder_id_idx": { + "name": "workspace_files_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_context_idx": { + "name": "workspace_files_context_idx", + "columns": [ + { + "expression": "context", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_chat_id_idx": { + "name": "workspace_files_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_deleted_at_idx": { + "name": "workspace_files_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_deleted_partial_idx": { + "name": "workspace_files_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_files_project_id_project_id_fk": { + "name": "workspace_files_project_id_project_id_fk", + "tableFrom": "workspace_files", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "workspace_files_user_id_user_id_fk": { + "name": "workspace_files_user_id_user_id_fk", + "tableFrom": "workspace_files", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_workspace_id_workspace_id_fk": { + "name": "workspace_files_workspace_id_workspace_id_fk", + "tableFrom": "workspace_files", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_organization_id_organization_id_fk": { + "name": "workspace_files_organization_id_organization_id_fk", + "tableFrom": "workspace_files", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_folder_id_folder_id_fk": { + "name": "workspace_files_folder_id_folder_id_fk", + "tableFrom": "workspace_files", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_files_chat_id_copilot_chats_id_fk": { + "name": "workspace_files_chat_id_copilot_chats_id_fk", + "tableFrom": "workspace_files", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_files_owner_check": { + "name": "workspace_files_owner_check", + "value": "num_nonnulls(\"workspace_files\".\"workspace_id\", \"workspace_files\".\"project_id\", \"workspace_files\".\"organization_id\") <= 1" + }, + "workspace_files_workspace_binding_check": { + "name": "workspace_files_workspace_binding_check", + "value": "\"workspace_files\".\"context\" NOT IN ('workspace', 'chat', 'mothership', 'execution', 'workspace-logos') OR \"workspace_files\".\"workspace_id\" IS NOT NULL" + }, + "workspace_files_project_binding_check": { + "name": "workspace_files_project_binding_check", + "value": "(\"workspace_files\".\"project_id\" IS NOT NULL) = (\"workspace_files\".\"context\" = 'project') AND (\"workspace_files\".\"project_id\" IS NULL OR \"workspace_files\".\"chat_id\" IS NULL)" + }, + "workspace_files_organization_binding_check": { + "name": "workspace_files_organization_binding_check", + "value": "\"workspace_files\".\"organization_id\" IS NULL OR (\"workspace_files\".\"workspace_id\" IS NULL AND \"workspace_files\".\"context\" = 'knowledge-base' AND \"workspace_files\".\"folder_id\" IS NULL AND \"workspace_files\".\"chat_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_fork_block_map": { + "name": "workspace_fork_block_map", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_workflow_id": { + "name": "parent_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_block_id": { + "name": "parent_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_workflow_id": { + "name": "child_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_block_id": { + "name": "child_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_block_map_child_ws_parent_unique": { + "name": "workspace_fork_block_map_child_ws_parent_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_child_unique": { + "name": "workspace_fork_block_map_child_ws_child_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_parent_wf_idx": { + "name": "workspace_fork_block_map_child_ws_parent_wf_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_child_wf_idx": { + "name": "workspace_fork_block_map_child_ws_child_wf_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_block_map_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_block_map_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_block_map", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_dependent_value": { + "name": "workspace_fork_dependent_value", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workflow_id": { + "name": "target_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_block_id": { + "name": "target_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sub_block_key": { + "name": "sub_block_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_dependent_value_field_unique": { + "name": "workspace_fork_dependent_value_field_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sub_block_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_dependent_value_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_dependent_value_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_dependent_value", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_promote_run": { + "name": "workspace_fork_promote_run", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workspace_id": { + "name": "target_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "direction": { + "name": "direction", + "type": "workspace_fork_promote_direction", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "snapshot": { + "name": "snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_promote_run_child_ws_target_unique": { + "name": "workspace_fork_promote_run_child_ws_target_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_promote_run_target_ws_idx": { + "name": "workspace_fork_promote_run_target_ws_idx", + "columns": [ + { + "expression": "target_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_promote_run_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_promote_run_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_promote_run", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_promote_run_created_by_user_id_fk": { + "name": "workspace_fork_promote_run_created_by_user_id_fk", + "tableFrom": "workspace_fork_promote_run", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_resource_map": { + "name": "workspace_fork_resource_map", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "workspace_fork_resource_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "parent_resource_id": { + "name": "parent_resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_resource_id": { + "name": "child_resource_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_resource_map_child_type_parent_unique": { + "name": "workspace_fork_resource_map_child_type_parent_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_resource_map_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_resource_map_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_resource_map", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_resource_map_created_by_user_id_fk": { + "name": "workspace_fork_resource_map_created_by_user_id_fk", + "tableFrom": "workspace_fork_resource_map", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_workflow_sync": { + "name": "workspace_fork_workflow_sync", + "schema": "", + "columns": { + "deployment_operation_id": { + "name": "deployment_operation_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_workflow_id": { + "name": "source_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workflow_id": { + "name": "target_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_deployment_version_id": { + "name": "source_deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sequence": { + "name": "sequence", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "workspace_fork_workflow_sync_sequence_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "promote_run_id": { + "name": "promote_run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "activated_at": { + "name": "activated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "rollback_operation_id": { + "name": "rollback_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rolled_back_at": { + "name": "rolled_back_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_fork_workflow_sync_baseline_idx": { + "name": "workspace_fork_workflow_sync_baseline_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sequence", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_fork_workflow_sync\".\"activated_at\" IS NOT NULL AND \"workspace_fork_workflow_sync\".\"rolled_back_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_run_idx": { + "name": "workspace_fork_workflow_sync_run_idx", + "columns": [ + { + "expression": "promote_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_rollback_idx": { + "name": "workspace_fork_workflow_sync_rollback_idx", + "columns": [ + { + "expression": "rollback_operation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_fork_workflow_sync\".\"rollback_operation_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_source_idx": { + "name": "workspace_fork_workflow_sync_source_idx", + "columns": [ + { + "expression": "source_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_target_idx": { + "name": "workspace_fork_workflow_sync_target_idx", + "columns": [ + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_child_workspace_idx": { + "name": "workspace_fork_workflow_sync_child_workspace_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_workflow_sync_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_workflow_sync_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_workflow_sync_source_workflow_id_workflow_id_fk": { + "name": "workspace_fork_workflow_sync_source_workflow_id_workflow_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workflow", + "columnsFrom": ["source_workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_workflow_sync_target_workflow_id_workflow_id_fk": { + "name": "workspace_fork_workflow_sync_target_workflow_id_workflow_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workflow", + "columnsFrom": ["target_workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_operation_receipt": { + "name": "workspace_operation_receipt", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "report": { + "name": "report", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_operation_receipt_request_unique": { + "name": "workspace_operation_receipt_request_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_operation_receipt_workspace_created_idx": { + "name": "workspace_operation_receipt_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_operation_receipt_workspace_id_workspace_id_fk": { + "name": "workspace_operation_receipt_workspace_id_workspace_id_fk", + "tableFrom": "workspace_operation_receipt", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_resource_key": { + "name": "workspace_resource_key", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "workspace_resource_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_resource_key_ws_kind_key_unique": { + "name": "workspace_resource_key_ws_kind_key_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_resource_key_ws_kind_resource_unique": { + "name": "workspace_resource_key_ws_kind_resource_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_resource_key_workspace_id_workspace_id_fk": { + "name": "workspace_resource_key_workspace_id_workspace_id_fk", + "tableFrom": "workspace_resource_key", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_resource_key_created_by_user_id_fk": { + "name": "workspace_resource_key_created_by_user_id_fk", + "tableFrom": "workspace_resource_key", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_resource_key_key_format": { + "name": "workspace_resource_key_key_format", + "value": "\"workspace_resource_key\".\"key\" ~ '^[a-z][a-z0-9_-]{0,63}$'" + }, + "workspace_resource_key_origin_check": { + "name": "workspace_resource_key_origin_check", + "value": "\"workspace_resource_key\".\"origin\" IN ('allocated', 'adopted', 'created')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_sandbox": { + "name": "workspace_sandbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "language": { + "name": "language", + "type": "sandbox_language", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "dependencies": { + "name": "dependencies", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "cli_tools": { + "name": "cli_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "system_packages": { + "name": "system_packages", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "spec_hash": { + "name": "spec_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_sandbox_workspace_name_unique": { + "name": "workspace_sandbox_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_sandbox_spec_hash_idx": { + "name": "workspace_sandbox_spec_hash_idx", + "columns": [ + { + "expression": "spec_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_sandbox_workspace_id_workspace_id_fk": { + "name": "workspace_sandbox_workspace_id_workspace_id_fk", + "tableFrom": "workspace_sandbox", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_sandbox_created_by_user_id_fk": { + "name": "workspace_sandbox_created_by_user_id_fk", + "tableFrom": "workspace_sandbox", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_source_apply_lease": { + "name": "workspace_source_apply_lease", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "acquired_at": { + "name": "acquired_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_source_apply_lease_workspace_id_workspace_id_fk": { + "name": "workspace_source_apply_lease_workspace_id_workspace_id_fk", + "tableFrom": "workspace_source_apply_lease", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_source_staged_blob": { + "name": "workspace_source_staged_blob", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "consumed_at": { + "name": "consumed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_source_staged_blob_scope_hash_unique": { + "name": "workspace_source_staged_blob_scope_hash_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sha256", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_source_staged_blob_expires_at_idx": { + "name": "workspace_source_staged_blob_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_source_staged_blob_workspace_id_workspace_id_fk": { + "name": "workspace_source_staged_blob_workspace_id_workspace_id_fk", + "tableFrom": "workspace_source_staged_blob", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_visit": { + "name": "workspace_visit", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visited_at": { + "name": "visited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_visit_workspace_idx": { + "name": "workspace_visit_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_visit_user_id_user_id_fk": { + "name": "workspace_visit_user_id_user_id_fk", + "tableFrom": "workspace_visit", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_visit_workspace_id_workspace_id_fk": { + "name": "workspace_visit_workspace_id_workspace_id_fk", + "tableFrom": "workspace_visit", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_visit_user_id_workspace_id_pk": { + "name": "workspace_visit_user_id_workspace_id_pk", + "columns": ["user_id", "workspace_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.api_key_access": { + "name": "api_key_access", + "schema": "public", + "values": ["read", "write"] + }, + "public.aws_marketplace_license_status": { + "name": "aws_marketplace_license_status", + "schema": "public", + "values": ["pending", "active", "inactive"] + }, + "public.aws_marketplace_usage_report_status": { + "name": "aws_marketplace_usage_report_status", + "schema": "public", + "values": ["pending", "reported", "rejected"] + }, + "public.background_work_kind": { + "name": "background_work_kind", + "schema": "public", + "values": ["deployment_side_effects", "fork_content_copy", "fork_sync", "fork_rollback"] + }, + "public.background_work_status_value": { + "name": "background_work_status_value", + "schema": "public", + "values": ["pending", "processing", "completed", "completed_with_warnings", "failed"] + }, + "public.billing_blocked_reason": { + "name": "billing_blocked_reason", + "schema": "public", + "values": ["payment_failed", "dispute"] + }, + "public.billing_entity_type": { + "name": "billing_entity_type", + "schema": "public", + "values": ["user", "organization"] + }, + "public.chat_type": { + "name": "chat_type", + "schema": "public", + "values": ["mothership", "copilot"] + }, + "public.copilot_async_tool_status": { + "name": "copilot_async_tool_status", + "schema": "public", + "values": ["pending", "running", "completed", "failed", "cancelled", "delivered"] + }, + "public.copilot_run_status": { + "name": "copilot_run_status", + "schema": "public", + "values": ["active", "paused_waiting_for_tool", "resuming", "complete", "error", "cancelled"] + }, + "public.copilot_tool_permission_decision": { + "name": "copilot_tool_permission_decision", + "schema": "public", + "values": ["allow", "allow_chat", "always_allow", "skip"] + }, + "public.credential_group_enrollment_status": { + "name": "credential_group_enrollment_status", + "schema": "public", + "values": ["invited", "delivery_failed", "in_progress", "completed", "revoked"] + }, + "public.credential_group_status": { + "name": "credential_group_status", + "schema": "public", + "values": ["active", "disabled"] + }, + "public.credential_member_role": { + "name": "credential_member_role", + "schema": "public", + "values": ["admin", "member"] + }, + "public.credential_member_status": { + "name": "credential_member_status", + "schema": "public", + "values": ["active", "pending", "revoked"] + }, + "public.credential_type": { + "name": "credential_type", + "schema": "public", + "values": [ + "oauth", + "managed_oauth", + "managed_mcp", + "env_workspace", + "env_personal", + "service_account", + "personal_token" + ] + }, + "public.data_drain_cadence": { + "name": "data_drain_cadence", + "schema": "public", + "values": ["hourly", "daily"] + }, + "public.data_drain_destination": { + "name": "data_drain_destination", + "schema": "public", + "values": [ + "s3", + "gcs", + "azure_blob", + "sentinel", + "datadog", + "bigquery", + "snowflake", + "webhook" + ] + }, + "public.data_drain_run_status": { + "name": "data_drain_run_status", + "schema": "public", + "values": ["running", "success", "failed"] + }, + "public.data_drain_run_trigger": { + "name": "data_drain_run_trigger", + "schema": "public", + "values": ["cron", "manual"] + }, + "public.data_drain_source": { + "name": "data_drain_source", + "schema": "public", + "values": ["workflow_logs", "job_logs", "audit_logs", "copilot_chats", "copilot_runs"] + }, + "public.execution_large_value_reference_source": { + "name": "execution_large_value_reference_source", + "schema": "public", + "values": ["execution_log", "paused_snapshot"] + }, + "public.folder_resource_type": { + "name": "folder_resource_type", + "schema": "public", + "values": ["workflow", "file", "knowledge_base", "table"] + }, + "public.invitation_kind": { + "name": "invitation_kind", + "schema": "public", + "values": ["organization", "workspace"] + }, + "public.invitation_membership_intent": { + "name": "invitation_membership_intent", + "schema": "public", + "values": ["internal", "external"] + }, + "public.invitation_status": { + "name": "invitation_status", + "schema": "public", + "values": ["pending", "accepted", "rejected", "cancelled", "expired"] + }, + "public.managed_oauth_credential_status": { + "name": "managed_oauth_credential_status", + "schema": "public", + "values": ["active", "needs_reauth", "revoked"] + }, + "public.permission_type": { + "name": "permission_type", + "schema": "public", + "values": ["admin", "write", "read"] + }, + "public.sandbox_image_status": { + "name": "sandbox_image_status", + "schema": "public", + "values": ["pending", "building", "ready", "failed"] + }, + "public.sandbox_language": { + "name": "sandbox_language", + "schema": "public", + "values": ["javascript", "python"] + }, + "public.secret_usage_scope": { + "name": "secret_usage_scope", + "schema": "public", + "values": ["workspace", "personal"] + }, + "public.secret_usage_source": { + "name": "secret_usage_source", + "schema": "public", + "values": ["workflow", "copilot", "mcp"] + }, + "public.upload_session_method": { + "name": "upload_session_method", + "schema": "public", + "values": ["put", "multipart"] + }, + "public.upload_session_provider": { + "name": "upload_session_provider", + "schema": "public", + "values": ["local", "s3", "blob", "gcs"] + }, + "public.upload_session_purpose": { + "name": "upload_session_purpose", + "schema": "public", + "values": [ + "workspace_file", + "project_file", + "table_import", + "knowledge_import", + "knowledge_document", + "profile_picture", + "workspace_logo", + "organization_logo", + "mothership_attachment", + "execution_attachment" + ] + }, + "public.upload_session_status": { + "name": "upload_session_status", + "schema": "public", + "values": [ + "uploading", + "completing", + "finalizing", + "completed", + "aborting", + "aborted", + "failed", + "expired" + ] + }, + "public.usage_log_category": { + "name": "usage_log_category", + "schema": "public", + "values": ["model", "fixed", "tool", "model_unbilled"] + }, + "public.usage_log_source": { + "name": "usage_log_source", + "schema": "public", + "values": [ + "workflow", + "wand", + "copilot", + "workspace-chat", + "mcp_copilot", + "mothership_block", + "knowledge-base", + "voice-input", + "enrichment", + "voice-output", + "api-tool", + "workflow-test" + ] + }, + "public.workspace_file_search_index_status": { + "name": "workspace_file_search_index_status", + "schema": "public", + "values": ["pending", "ready", "skipped", "failed"] + }, + "public.workspace_file_version_source": { + "name": "workspace_file_version_source", + "schema": "public", + "values": ["upload", "user", "api", "copilot", "workflow", "collab", "revert", "unknown"] + }, + "public.workspace_fork_promote_direction": { + "name": "workspace_fork_promote_direction", + "schema": "public", + "values": ["push", "pull"] + }, + "public.workspace_fork_resource_type": { + "name": "workspace_fork_resource_type", + "schema": "public", + "values": [ + "workflow", + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "knowledge_document", + "file", + "file_folder", + "mcp_server", + "workflow_mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ] + }, + "public.workspace_mode": { + "name": "workspace_mode", + "schema": "public", + "values": ["personal", "organization", "grandfathered_shared"] + }, + "public.workspace_resource_kind": { + "name": "workspace_resource_kind", + "schema": "public", + "values": [ + "credential", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ] + } + }, + "schemas": {}, + "sequences": { + "public.copilot_async_tool_calls_persist_seq": { + "name": "copilot_async_tool_calls_persist_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index ade4f1cf5cd..b08a4b8a9af 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -3277,6 +3277,13 @@ "when": 1795223641227, "tag": "0468_retire_legacy_search_and_contracts", "breakpoints": true + }, + { + "idx": 469, + "version": "7", + "when": 1795263216402, + "tag": "0469_staged_blob_consumed_at", + "breakpoints": true } ] } diff --git a/packages/db/schema.ts b/packages/db/schema.ts index 6de022a60ca..083c5696919 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -2937,6 +2937,11 @@ export const workspaceSourceStagedBlob = pgTable( storageKey: text('storage_key').notNull(), createdAt: timestamp('created_at').notNull().defaultNow(), expiresAt: timestamp('expires_at').notNull(), + /** + * When an apply wrote these bytes into the workspace, which then stores (and charges for) them: + * a consumed blob no longer counts toward the payer's storage quota. Staging it again clears it. + */ + consumedAt: timestamp('consumed_at'), }, (table) => ({ scopeHashUnique: uniqueIndex('workspace_source_staged_blob_scope_hash_unique').on( diff --git a/packages/testing/src/mocks/schema-tables.generated.ts b/packages/testing/src/mocks/schema-tables.generated.ts index 97029acb014..d809579525c 100644 --- a/packages/testing/src/mocks/schema-tables.generated.ts +++ b/packages/testing/src/mocks/schema-tables.generated.ts @@ -713,6 +713,7 @@ export const GENERATED_SCHEMA_TABLES = { 'storageKey', 'createdAt', 'expiresAt', + 'consumedAt', ], workspaceSourceApplyLease: ['workspaceId', 'token', 'acquiredAt', 'expiresAt'], workspaceForkDependentValue: [ From 3e725ea637da56df960d119b4a9dcc6358f6c8cf Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:18:43 -0800 Subject: [PATCH 43/85] fix(workflow-code): the Code tab's source read runs in a slot lane of its own, so API and CLI gets cannot starve it --- .../api/workflows/[id]/source/route.test.ts | 20 +++++++++++++++++++ .../app/api/workflows/[id]/source/route.ts | 5 +++-- apps/sim/lib/workflows/api/source-slots.ts | 16 +++++++++++---- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/apps/sim/app/api/workflows/[id]/source/route.test.ts b/apps/sim/app/api/workflows/[id]/source/route.test.ts index ac0fd810c6e..394143b6ca3 100644 --- a/apps/sim/app/api/workflows/[id]/source/route.test.ts +++ b/apps/sim/app/api/workflows/[id]/source/route.test.ts @@ -1,4 +1,5 @@ import { authMockFns } from '@sim/testing' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' import { NextRequest } from 'next/server' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -17,6 +18,8 @@ vi.mock('@/lib/workflows/application/read-workflow-source', () => ({ }, })) +import { withSourceSlot } from '@/lib/workflows/api/source-slots' +import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' import { GET } from '@/app/api/workflows/[id]/source/route' const WORKFLOW_ID = 'workflow-123' @@ -57,6 +60,23 @@ describe('GET /api/workflows/[id]/source', () => { }) }) + it('reads in a lane of its own: API and CLI source gets filling theirs never refuse the Code tab', async () => { + const finish: Array<() => void> = [] + mockRead.mockImplementation(() => new Promise((resolve) => finish.push(() => resolve(source)))) + const apiGet = withSourceSlot(readWorkflowSource, 'read') + const principal = createSessionPrincipal({ userId: 'user-123', sessionId: 'session-123' }) + const running = Array.from({ length: 4 }, () => + apiGet.execute({ principal, input: { workflowId: WORKFLOW_ID } }) + ) + await vi.waitFor(() => expect(finish).toHaveLength(4)) + mockRead.mockResolvedValueOnce(source) + + expect((await read()).status).toBe(200) + + for (const done of finish) done() + await Promise.all(running) + }) + it('answers 429 with Retry-After to a read past the source gets this server runs at once', async () => { const finish: Array<() => void> = [] mockRead.mockImplementation(() => new Promise((resolve) => finish.push(() => resolve(source)))) diff --git a/apps/sim/app/api/workflows/[id]/source/route.ts b/apps/sim/app/api/workflows/[id]/source/route.ts index ff4457a5d60..d5af53cfea7 100644 --- a/apps/sim/app/api/workflows/[id]/source/route.ts +++ b/apps/sim/app/api/workflows/[id]/source/route.ts @@ -36,7 +36,8 @@ const SOURCE_READ_RATE_LIMIT: TokenBucketConfig = { * The bare fingerprint would not do: it ignores what it does not hash (canvas positions, * comments), which the printed files and lock can still carry. * - * Runs in a source read slot, like the v2 read (`429` with `Retry-After` when the server is full). + * Runs in a source slot of the editor's own lane, so API and CLI gets never starve the Code tab + * (`429` with `Retry-After` when the server already runs as many Code tab reads as it may). * The tag is taken after the read: the printed resource keys are known only once the graph is * canonicalized, so no earlier tag would be sound. * @@ -57,7 +58,7 @@ export const GET = defineInternalJsonRoute({ workflowId: params.id, ...(query.functionCode ? { functionCode: query.functionCode } : {}), }), - useCase: withSourceSlot(readWorkflowSource, 'read'), + useCase: withSourceSlot(readWorkflowSource, 'editor'), entityTag: (source) => `${source.base.fingerprint}.${sha256Hex(JSON.stringify(source))}`, present: (source) => ({ data: withBoundSourceFindings(source) }), }) diff --git a/apps/sim/lib/workflows/api/source-slots.ts b/apps/sim/lib/workflows/api/source-slots.ts index 7b095a467dc..cc2338cce60 100644 --- a/apps/sim/lib/workflows/api/source-slots.ts +++ b/apps/sim/lib/workflows/api/source-slots.ts @@ -6,15 +6,23 @@ import { v2Error } from '@/app/api/v2/lib/response' /** * Source requests of one lane this server process runs at once. Plans have a lane of their own, - * so a read-role caller asking for a status never takes a slot an apply needs. + * so a read-role caller asking for a status never takes a slot an apply needs, and the editor's + * Code tab reads in its own, so API and CLI gets and the editor never starve each other. A table + * plan inside one slot may run a few workflow reads at once (`kinds/table`), so the bound is per + * request, not per workflow load. */ -const MAX_CONCURRENT_SOURCE_REQUESTS = { read: 4, plan: 4, apply: 4 } as const +const MAX_CONCURRENT_SOURCE_REQUESTS = { read: 4, editor: 4, plan: 4, apply: 4 } as const type SourceLane = keyof typeof MAX_CONCURRENT_SOURCE_REQUESTS -const LANE_NOUNS: Record = { read: 'gets', plan: 'plans', apply: 'applies' } +const LANE_NOUNS: Record = { + read: 'gets', + editor: 'Code tab reads', + plan: 'plans', + apply: 'applies', +} -const runningSourceRequests: Record = { read: 0, plan: 0, apply: 0 } +const runningSourceRequests: Record = { read: 0, editor: 0, plan: 0, apply: 0 } /** The wait a request refused for want of a slot is told to take. */ const SOURCE_BUSY_HEADERS = { 'Retry-After': '5' } From 33c4857dcefcc3bd8941938953a380bf87128d45 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:20:46 -0800 Subject: [PATCH 44/85] fix(sim-cli): workspace status drops only compile and lint findings for a folder an apply sends by its base, never a plan refusal --- .../protocol/workspace-source-status.test.ts | 26 +++++++++++++++++++ .../protocol/workspace-source-status.ts | 8 +++--- .../workspace-code/src/diagnostics/codes.ts | 14 ++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) 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 89761c88d09..40f54e4d4f7 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 @@ -576,6 +576,32 @@ describe('workspaces source status', () => { expect(report.diagnostics ?? []).toEqual([]) }) + it('keeps a plan refusal about a workflow an apply sends by its base: status counts the error the apply refuses with', async () => { + mockRequest.mockResolvedValue( + dryRun( + [ + { kind: 'workflow', key: 'ingest', action: 'noop' }, + { kind: 'table', key: 'leads', action: 'delete' }, + ], + [ + { + code: 'E_PLAN_REF_DELETED', + severity: 'error', + message: 'workflows/ingest/ uses table "leads", which this apply deletes.', + kind: 'workflow', + key: 'ingest', + }, + ] + ) + ) + + await run('status') + + const report = printed() + expect(report.plan).toMatchObject({ delete: 1, errors: 1 }) + expect(report.diagnostics?.map((finding) => finding.code)).toEqual(['E_PLAN_REF_DELETED']) + }) + it('keeps lint findings on a workflow edited here, which an apply sends whole', async () => { write('workflows/ingest/workflow.ts', INGEST.replace("'Ingest'", "'Ingest v2'")) mockRequest.mockResolvedValue( 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 d96d7323ddb..ca6ea25b52d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -11,6 +11,7 @@ import { isRecordLike, toRecord } from '@sim/utils/object' 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' import { kindOfPath, WORKSPACE_BASE_FILE, WORKSPACE_SKIPPED_FILE } from '@sim/workspace-code/layout' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' @@ -243,12 +244,13 @@ function planAsApplied( /** * The dry run's findings the plan counts, as an apply's dry run would report them: all but the - * server changes the status lists, and none about a workflow folder an apply sends by its base - * (the server compiles and lints only a folder sent whole). + * server changes the status lists, and none from compiling or linting a workflow folder an apply + * sends by its base (the server evaluates only a folder sent whole). A plan check about such a + * folder, such as one using a resource this apply deletes, still refuses the apply, so it stays. */ function workspacePlanFindings(data: PlanData, byBase: ReadonlySet): Diagnostic[] { return planFindings(data.diagnostics, isServerChangeFinding).filter( - (finding) => !aboutWorkflowSentByBase(finding, byBase) + (finding) => !(aboutWorkflowSentByBase(finding, byBase) && isFolderEvaluationFinding(finding)) ) } diff --git a/packages/workspace-code/src/diagnostics/codes.ts b/packages/workspace-code/src/diagnostics/codes.ts index a3b1ca034d5..c35be3967e7 100644 --- a/packages/workspace-code/src/diagnostics/codes.ts +++ b/packages/workspace-code/src/diagnostics/codes.ts @@ -329,6 +329,20 @@ type OwnCode = (typeof OWN_CODES)[number] /** Every code a workspace source finding can carry, as a value: the wire contracts' enum. */ export const WORKSPACE_DIAGNOSTIC_CODES = [...OWN_CODES, ...SHARED_CODES] as const +const OWN_CODE_SET: ReadonlySet = new Set(OWN_CODES) +const SHARED_CODE_SET: ReadonlySet = new Set(SHARED_CODES) + +/** + * Whether a finding comes from evaluating a workflow folder's files (compile, lint): a workflow + * pipeline code, or one {@link SHARED_CODES} holds pinned to a file. The server reports these only + * for a folder sent whole; a workspace code (a plan check such as `E_PLAN_REF_DELETED`, a held + * reference, a stale resource) can be about any folder, sent whole or by its base. + */ +export function isFolderEvaluationFinding(finding: { code: string; file?: string }): boolean { + if (OWN_CODE_SET.has(finding.code)) return false + return !SHARED_CODE_SET.has(finding.code) || finding.file !== undefined +} + /** * One of {@link WORKSPACE_DIAGNOSTIC_CODES}. It is `never`, which fails every use, if a workspace * code is declared twice or is also a workflow code outside {@link SHARED_CODES}. From 577feed4f57902021375836f0fabf85fa6b10a9f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:25:30 -0800 Subject: [PATCH 45/85] fix(tables): a table name missing from a workspace answers exactly as one the caller cannot reach, and dispatches and exports take a name like every table route --- apps/docs/content/docs/cli/reference.mdx | 80 ++++----- apps/docs/content/docs/cli/tables.mdx | 80 ++++----- apps/docs/openapi-v2-tables.json | 156 +++++++++--------- .../[tableId]/rows/[rowId]/route.test.ts | 3 +- .../app/api/v2/tables/[tableId]/route.test.ts | 3 +- apps/sim/lib/api/contracts/tables.ts | 14 +- apps/sim/lib/api/contracts/v2/tables.ts | 3 +- apps/sim/lib/table/api/route-policies.ts | 7 +- .../sim/lib/table/application/context.test.ts | 22 ++- apps/sim/lib/table/application/context.ts | 15 +- .../sim/lib/table/application/exports.test.ts | 15 ++ apps/sim/lib/table/application/exports.ts | 10 +- apps/sim/lib/table/application/runs.test.ts | 13 +- apps/sim/lib/table/application/runs.ts | 22 +-- apps/sim/lib/table/constants.ts | 7 + apps/sim/lib/table/ids.ts | 10 ++ packages/sim-cli/src/generated/v2-api.ts | 78 ++++----- 17 files changed, 308 insertions(+), 230 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index fa0e8144134..82f333ebb0f 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -5868,7 +5868,7 @@ sim tables columns create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -5900,7 +5900,7 @@ sim tables columns delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -5931,7 +5931,7 @@ sim tables columns update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -5962,7 +5962,7 @@ sim tables groups create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -5997,7 +5997,7 @@ sim tables groups delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6028,7 +6028,7 @@ sim tables groups list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6048,7 +6048,7 @@ sim tables groups update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6113,7 +6113,7 @@ sim tables rows update-each [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6143,7 +6143,7 @@ sim tables rows create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6176,7 +6176,7 @@ sim tables rows delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | @@ -6209,7 +6209,7 @@ sim tables rows batch-delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6242,7 +6242,7 @@ sim tables rows get [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | @@ -6274,7 +6274,7 @@ sim tables rows list [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6307,7 +6307,7 @@ sim tables rows query [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6342,7 +6342,7 @@ sim tables rows count [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6372,7 +6372,7 @@ sim tables rows enrich | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | | `groupId` | Yes | Workflow or enrichment group to run. | @@ -6394,7 +6394,7 @@ sim tables rows search [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6428,7 +6428,7 @@ sim tables rows batch-update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6461,7 +6461,7 @@ sim tables rows update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | @@ -6494,7 +6494,7 @@ sim tables dispatches cancel [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `dispatchId` | Yes | Unique table run-dispatch identifier. | @@ -6525,7 +6525,7 @@ sim tables dispatches create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6560,7 +6560,7 @@ sim tables dispatches get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `dispatchId` | Yes | Unique table run-dispatch identifier. | @@ -6581,7 +6581,7 @@ sim tables dispatches list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6601,7 +6601,7 @@ sim tables exports cancel | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `exportId` | Yes | Unique table-export identifier. | @@ -6622,7 +6622,7 @@ sim tables exports create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6652,7 +6652,7 @@ sim tables exports get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `exportId` | Yes | Unique table-export identifier. | @@ -6673,7 +6673,7 @@ sim tables exports download | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `exportId` | Yes | Unique table-export identifier. | @@ -6748,7 +6748,7 @@ sim tables cancel-runs [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6926,7 +6926,7 @@ sim tables views create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -6959,7 +6959,7 @@ sim tables views delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `viewId` | Yes | Unique saved-view identifier. | @@ -6990,7 +6990,7 @@ sim tables views get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `viewId` | Yes | Unique saved-view identifier. | @@ -7011,7 +7011,7 @@ sim tables views list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -7031,7 +7031,7 @@ sim tables views update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `viewId` | Yes | Unique saved-view identifier. | @@ -7068,7 +7068,7 @@ sim tables delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -7098,7 +7098,7 @@ sim tables enrichment get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | | `groupId` | Yes | Workflow or enrichment group to run. | @@ -7120,7 +7120,7 @@ sim tables get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -7187,7 +7187,7 @@ sim tables restore | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique identifier of the archived table. A restore takes the id alone: archived tables need not have unique names. | @@ -7207,7 +7207,7 @@ sim tables update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -7239,7 +7239,7 @@ sim tables mv | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `folder` | Yes | Folder path as shown in the app; the leading / is optional | @@ -7260,7 +7260,7 @@ sim tables upsert [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | diff --git a/apps/docs/content/docs/cli/tables.mdx b/apps/docs/content/docs/cli/tables.mdx index 5bf72591cdb..589050deb8a 100644 --- a/apps/docs/content/docs/cli/tables.mdx +++ b/apps/docs/content/docs/cli/tables.mdx @@ -48,7 +48,7 @@ sim tables get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -87,7 +87,7 @@ sim tables update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -137,7 +137,7 @@ sim tables mv | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `folder` | Yes | Folder path as shown in the app; the leading / is optional | @@ -158,7 +158,7 @@ sim tables delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -208,7 +208,7 @@ sim tables restore | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique identifier of the archived table. A restore takes the id alone: archived tables need not have unique names. | @@ -228,7 +228,7 @@ sim tables rows list [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -259,7 +259,7 @@ sim tables rows get [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | @@ -289,7 +289,7 @@ sim tables rows query [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -322,7 +322,7 @@ sim tables rows count [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -350,7 +350,7 @@ sim tables rows search [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -380,7 +380,7 @@ sim tables rows create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -409,7 +409,7 @@ sim tables rows update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | @@ -438,7 +438,7 @@ sim tables rows update-each [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -468,7 +468,7 @@ sim tables rows batch-update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -499,7 +499,7 @@ sim tables rows enrich | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | | `groupId` | Yes | Workflow or enrichment group to run. | @@ -521,7 +521,7 @@ sim tables rows delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | @@ -552,7 +552,7 @@ sim tables rows batch-delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -583,7 +583,7 @@ sim tables upsert [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -614,7 +614,7 @@ sim tables columns create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -642,7 +642,7 @@ sim tables columns update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -673,7 +673,7 @@ sim tables columns delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -704,7 +704,7 @@ sim tables views list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -722,7 +722,7 @@ sim tables views get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `viewId` | Yes | Unique saved-view identifier. | @@ -741,7 +741,7 @@ sim tables views create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -770,7 +770,7 @@ sim tables views update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `viewId` | Yes | Unique saved-view identifier. | @@ -805,7 +805,7 @@ sim tables views delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `viewId` | Yes | Unique saved-view identifier. | @@ -836,7 +836,7 @@ sim tables groups list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -854,7 +854,7 @@ sim tables groups create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -885,7 +885,7 @@ sim tables groups update [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -926,7 +926,7 @@ sim tables groups delete [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -955,7 +955,7 @@ sim tables enrichment get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `rowId` | Yes | Unique table row identifier. | | `groupId` | Yes | Workflow or enrichment group to run. | @@ -975,7 +975,7 @@ sim tables dispatches list | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -993,7 +993,7 @@ sim tables dispatches get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `dispatchId` | Yes | Unique table run-dispatch identifier. | @@ -1012,7 +1012,7 @@ sim tables dispatches create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -1047,7 +1047,7 @@ sim tables dispatches cancel [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `dispatchId` | Yes | Unique table run-dispatch identifier. | @@ -1078,7 +1078,7 @@ sim tables cancel-runs [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -1205,7 +1205,7 @@ sim tables exports create [options] | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | @@ -1233,7 +1233,7 @@ sim tables exports get | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `exportId` | Yes | Unique table-export identifier. | @@ -1252,7 +1252,7 @@ sim tables exports download | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `exportId` | Yes | Unique table-export identifier. | @@ -1271,7 +1271,7 @@ sim tables exports cancel | Argument | Required | Description | | --- | --- | --- | -| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works. | +| `tableId` | Yes | Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id). | | `exportId` | Yes | Unique table-export identifier. | diff --git a/apps/docs/openapi-v2-tables.json b/apps/docs/openapi-v2-tables.json index b02dd46f6f6..70cecfd5455 100644 --- a/apps/docs/openapi-v2-tables.json +++ b/apps/docs/openapi-v2-tables.json @@ -318,11 +318,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -405,11 +405,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -492,11 +492,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -597,11 +597,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -702,11 +702,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -841,11 +841,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -945,11 +945,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -1067,11 +1067,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -1172,11 +1172,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -1285,11 +1285,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -1389,11 +1389,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -1497,11 +1497,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -1612,11 +1612,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -1712,11 +1712,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -1820,11 +1820,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -1959,11 +1959,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -2064,11 +2064,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -2148,11 +2148,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -2266,11 +2266,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -2361,11 +2361,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -2472,11 +2472,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -2569,11 +2569,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -2653,11 +2653,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -2771,11 +2771,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -2877,11 +2877,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -2981,11 +2981,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -3080,11 +3080,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -3166,11 +3166,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -3286,11 +3286,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -3397,11 +3397,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -4039,11 +4039,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -4143,11 +4143,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -4239,11 +4239,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -4340,11 +4340,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -4441,11 +4441,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -5056,11 +5056,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique identifier of the archived table. A restore takes the id alone: archived tables need not have unique names.", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique identifier of the archived table. A restore takes the id alone: archived tables need not have unique names." } } ], @@ -5159,11 +5159,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } } ], @@ -5276,11 +5276,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { @@ -5372,11 +5372,11 @@ "name": "tableId", "in": "path", "required": true, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works.", + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).", "schema": { "type": "string", "minLength": 1, - "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works." + "description": "Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id)." } }, { diff --git a/apps/sim/app/api/table/[tableId]/rows/[rowId]/route.test.ts b/apps/sim/app/api/table/[tableId]/rows/[rowId]/route.test.ts index 2352d7fdd3b..a403513c5d6 100644 --- a/apps/sim/app/api/table/[tableId]/rows/[rowId]/route.test.ts +++ b/apps/sim/app/api/table/[tableId]/rows/[rowId]/route.test.ts @@ -26,6 +26,7 @@ vi.mock('@/lib/table/api', () => tableApiMock) import { NoWorkspaceAccessError } from '@/lib/core/application' import { OrchestrationError } from '@/lib/core/orchestration/types' +import { TABLE_NOT_FOUND_MESSAGE } from '@/lib/table/constants' import { TableLockedError } from '@/lib/table/mutation-locks' import { GET, PATCH } from '@/app/api/table/[tableId]/rows/[rowId]/route' @@ -114,7 +115,7 @@ describe('deliberate wire changes', () => { const response = await GET(getRequest(), routeContext()) expect(response.status).toBe(404) - await expect(response.json()).resolves.toMatchObject({ error: 'Table not found' }) + await expect(response.json()).resolves.toMatchObject({ error: TABLE_NOT_FOUND_MESSAGE }) }) it('still answers 403 for an in-workspace denial, which is not concealed', async () => { diff --git a/apps/sim/app/api/v2/tables/[tableId]/route.test.ts b/apps/sim/app/api/v2/tables/[tableId]/route.test.ts index 0a7881a6af2..3bf9d759065 100644 --- a/apps/sim/app/api/v2/tables/[tableId]/route.test.ts +++ b/apps/sim/app/api/v2/tables/[tableId]/route.test.ts @@ -26,6 +26,7 @@ vi.mock('@/lib/table/billing', () => tableBillingMock) import { NoWorkspaceAccessError } from '@/lib/core/application' import { OrchestrationError } from '@/lib/core/orchestration/types' +import { TABLE_NOT_FOUND_MESSAGE } from '@/lib/table/constants' import { DELETE, GET, PATCH } from '@/app/api/v2/tables/[tableId]/route' const { mockGetUserEmailsByIds } = usersQueriesMockFns @@ -157,7 +158,7 @@ describe('/api/v2/tables/[tableId]', () => { expect(response.status).toBe(404) expect((await response.json()).error).toEqual({ code: 'NOT_FOUND', - message: 'Table not found', + message: TABLE_NOT_FOUND_MESSAGE, }) } }) diff --git a/apps/sim/lib/api/contracts/tables.ts b/apps/sim/lib/api/contracts/tables.ts index 92f4a903e8f..332177cfdbc 100644 --- a/apps/sim/lib/api/contracts/tables.ts +++ b/apps/sim/lib/api/contracts/tables.ts @@ -181,7 +181,17 @@ export const tableIdParamsSchema = z.object({ .string() .min(1) .describe( - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.' + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).' + ), +}) + +/** A restore's address: the id alone, since archived tables' names need not be unique. */ +export const archivedTableIdParamsSchema = z.object({ + tableId: z + .string() + .min(1) + .describe( + 'Unique identifier of the archived table. A restore takes the id alone: archived tables need not have unique names.' ), }) @@ -1016,7 +1026,7 @@ export const deleteTableContract = defineRouteContract({ export const restoreTableContract = defineRouteContract({ method: 'POST', path: '/api/table/[tableId]/restore', - params: tableIdParamsSchema, + params: archivedTableIdParamsSchema, response: { mode: 'json', schema: successResponseSchema(z.object({ table: tableDefinitionSchema })), diff --git a/apps/sim/lib/api/contracts/v2/tables.ts b/apps/sim/lib/api/contracts/v2/tables.ts index cba5d2b0f40..c4731bc0c14 100644 --- a/apps/sim/lib/api/contracts/v2/tables.ts +++ b/apps/sim/lib/api/contracts/v2/tables.ts @@ -6,6 +6,7 @@ import { } from '@/lib/api/contracts/primitives' import { addWorkflowGroupBodySchema, + archivedTableIdParamsSchema, cancelTableRunsBodyBaseSchema, columnNameSchema, columnTypeSchema, @@ -1406,7 +1407,7 @@ export type V2WorkspaceScopedBody = z.input export const v2RestoreTableContract = defineRouteContract({ method: 'POST', path: '/api/v2/tables/[tableId]/restore', - params: tableIdParamsSchema, + params: archivedTableIdParamsSchema, query: noInputSchema, body: v2WorkspaceScopedBodySchema, response: { diff --git a/apps/sim/lib/table/api/route-policies.ts b/apps/sim/lib/table/api/route-policies.ts index bd8402a0809..cd6698a9ad9 100644 --- a/apps/sim/lib/table/api/route-policies.ts +++ b/apps/sim/lib/table/api/route-policies.ts @@ -9,6 +9,7 @@ import { } from '@/lib/api/server/routes' import { TABLE_DELEGATION_AUDIENCE } from '@/lib/table/application/authorization' import { TableOperationError } from '@/lib/table/application/errors' +import { TABLE_NOT_FOUND_MESSAGE } from '@/lib/table/constants' import { TableLockedError } from '@/lib/table/mutation-locks' import { v2CaughtOrchestrationError, @@ -45,7 +46,7 @@ export const v2TableErrorPolicies = { render: renderTableError, } satisfies V2ErrorPolicy, concealTableAuthorization: createV2ResourceConcealmentPolicy({ - notFoundMessage: 'Table not found', + notFoundMessage: TABLE_NOT_FOUND_MESSAGE, render: renderTableError, }), concealImportAuthorization: createV2ResourceConcealmentPolicy({ @@ -92,11 +93,11 @@ export const internalTableErrorPolicies = { bulk: internalTableGroupErrorPolicy, concealTableAuthorization: createInternalResourceConcealmentPolicy({ base: internalOrchestrationErrorPolicy, - notFoundMessage: 'Table not found', + notFoundMessage: TABLE_NOT_FOUND_MESSAGE, }), concealTableGroupAuthorization: createInternalResourceConcealmentPolicy({ base: internalTableGroupErrorPolicy, - notFoundMessage: 'Table not found', + notFoundMessage: TABLE_NOT_FOUND_MESSAGE, }), concealImportAuthorization: createInternalResourceConcealmentPolicy({ base: internalOrchestrationErrorPolicy, diff --git a/apps/sim/lib/table/application/context.test.ts b/apps/sim/lib/table/application/context.test.ts index 67d2a7a7b8d..c5836fef455 100644 --- a/apps/sim/lib/table/application/context.test.ts +++ b/apps/sim/lib/table/application/context.test.ts @@ -8,10 +8,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('@/lib/table/service', () => tableServiceMock) vi.mock('@/lib/workspaces/application/context', () => workspaceContextMock) +import { NoWorkspaceAccessError } from '@/lib/core/application' +import { v2TableErrorPolicies } from '@/lib/table/api/route-policies' import { resolveActiveTableContext, resolveArchivedTableContext, } from '@/lib/table/application/context' +import { TABLE_NOT_FOUND_MESSAGE } from '@/lib/table/constants' const getTableById = tableServiceMockFns.mockGetTableById const findByName = tableServiceMockFns.mockFindActiveTablesByExactName @@ -110,6 +113,23 @@ describe('table application context', () => { expect(findByName).not.toHaveBeenCalled() }) + it('answers a name missing from a workspace byte for byte as a refused authorization over a name that exists there', async () => { + getTableById.mockResolvedValue(null) + findByName.mockResolvedValue([]) + const missing = await resolveActiveTableContext({ + tableId: 'payroll', + assertedWorkspaceId: 'workspace-2', + }).catch((error: unknown) => error) + const { render } = v2TableErrorPolicies.concealTableAuthorization + + const [missingBody, refusedBody] = await Promise.all( + [missing, new NoWorkspaceAccessError()].map((error) => render(error)?.text()) + ) + + expect(missingBody).toBeDefined() + expect(missingBody).toBe(refusedBody) + }) + it('conceals an asserted cross-workspace table as not found', async () => { await expect( resolveActiveTableContext({ tableId: 'table-1', assertedWorkspaceId: 'workspace-2' }) @@ -151,7 +171,7 @@ describe('table application context', () => { await expect( resolveActiveTableContext({ tableId: 'table-1', assertedWorkspaceId: 'workspace-1' }) - ).rejects.toMatchObject({ code: 'not_found', message: 'Table not found' }) + ).rejects.toMatchObject({ code: 'not_found', message: TABLE_NOT_FOUND_MESSAGE }) }) it('fails when the canonical workspace is unavailable', async () => { diff --git a/apps/sim/lib/table/application/context.ts b/apps/sim/lib/table/application/context.ts index 441f58fbb2a..d1690f572a2 100644 --- a/apps/sim/lib/table/application/context.ts +++ b/apps/sim/lib/table/application/context.ts @@ -1,5 +1,6 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import type { TableAuthorizationContext } from '@/lib/table/application/authorization' +import { TABLE_NOT_FOUND_MESSAGE } from '@/lib/table/constants' import { TABLE_ID_PREFIX } from '@/lib/table/ids' import { findActiveTablesByExactName, getTableById } from '@/lib/table/service' import type { TableDefinition } from '@/lib/table/types' @@ -28,9 +29,8 @@ export async function resolveTableWorkspaceContext( * workspace a table is also found by its name (`sim tables rows list leads`), which is unique * among the workspace's active tables; an id always wins, a reference shaped like an id is never * read as a name (a stale id costs no second query), and a name never reaches past the asserted - * workspace. + * workspace. Every miss reads {@link TABLE_NOT_FOUND_MESSAGE}, as a refused authorization does. */ - async function requireTable(tableId: string, workspaceId: string | undefined) { let table = await getTableById(tableId) if (!table && workspaceId !== undefined && !tableId.startsWith(TABLE_ID_PREFIX)) { @@ -38,10 +38,7 @@ async function requireTable(tableId: string, workspaceId: string | undefined) { if (named.length === 1) table = named[0] } if (!table || (workspaceId !== undefined && table.workspaceId !== workspaceId)) { - throw new OrchestrationError( - 'not_found', - `Table "${tableId}" not found in this workspace, by id or by name — it may not exist or may belong to a different workspace. List the tables in this workspace to see the ids and names you can use here.` - ) + throw new OrchestrationError('not_found', TABLE_NOT_FOUND_MESSAGE) } return table } @@ -87,7 +84,7 @@ export async function resolveActiveTableContext(input: { const table = tableOutcome.value const workspaceContext = workspaceOutcome.value if (workspaceContext.workspaceId !== table.workspaceId) { - throw new OrchestrationError('not_found', 'Table not found') + throw new OrchestrationError('not_found', TABLE_NOT_FOUND_MESSAGE) } return { ...workspaceContext, tableId: table.id, table } } @@ -114,7 +111,7 @@ export async function resolveActiveTableInWorkspace( * so it cannot go through {@link resolveActiveTableContext} — that resolver's * `getTableById` skips archived rows and would report every restorable table as * missing. The asserted-workspace comparison and its not-found concealment are - * identical. + * identical. It takes the id alone: archived tables' names need not be unique. */ export async function resolveArchivedTableContext(input: { tableId: string @@ -125,7 +122,7 @@ export async function resolveArchivedTableContext(input: { !table || (input.assertedWorkspaceId !== undefined && table.workspaceId !== input.assertedWorkspaceId) ) { - throw new OrchestrationError('not_found', 'Table not found') + throw new OrchestrationError('not_found', TABLE_NOT_FOUND_MESSAGE) } const workspaceContext = await resolveTableWorkspaceContext(table.workspaceId) return { ...workspaceContext, tableId: table.id, table } diff --git a/apps/sim/lib/table/application/exports.test.ts b/apps/sim/lib/table/application/exports.test.ts index c942f019526..812cd14b3ec 100644 --- a/apps/sim/lib/table/application/exports.test.ts +++ b/apps/sim/lib/table/application/exports.test.ts @@ -134,6 +134,21 @@ describe('table export application use cases', () => { expect(mocks.create).not.toHaveBeenCalled() }) + it('cancels an export under its table named by its name, and conceals one under another table', async () => { + mocks.getTable.mockImplementation(async (id: string) => + id === table.id ? table : { ...table, id, name: `Table ${id}` } + ) + const cancel = (tableId: string) => + cancelTableExportUseCase.execute({ + principal: { kind: 'session' as const, userId: 'user-1' }, + input: { exportId: 'export-1', workspaceId: 'workspace-1', tableId }, + }) + + await expect(cancel(table.name)).resolves.toMatchObject({ export: { status: 'canceled' } }) + await expect(cancel('Elsewhere')).rejects.toMatchObject({ code: 'not_found' }) + await expect(cancel('tbl_other')).rejects.toMatchObject({ code: 'not_found' }) + }) + describe('permission-group capability', () => { const member = { kind: 'session' as const, userId: 'user-1' } const governedContext = { diff --git a/apps/sim/lib/table/application/exports.ts b/apps/sim/lib/table/application/exports.ts index 01a86f5e1fd..8c84f682a7a 100644 --- a/apps/sim/lib/table/application/exports.ts +++ b/apps/sim/lib/table/application/exports.ts @@ -9,6 +9,7 @@ import { resolveTableWorkspaceContext, } from '@/lib/table/application/context' import { tableOperations } from '@/lib/table/application/operations' +import { referencesTable } from '@/lib/table/ids' import { cancelTableExportResource, createTableExportResource, @@ -60,11 +61,12 @@ async function resolveTableExportContext( input: TableExportResourceInput ): Promise { const record = await requireTableExport(input.exportId, input.workspaceId) - if (input.tableId !== undefined && input.tableId !== record.tableId) { - throw new OrchestrationError('not_found', 'Table export not found') - } const table = await getTableById(record.tableId) - if (!table || table.workspaceId !== record.workspaceId) { + if ( + !table || + table.workspaceId !== record.workspaceId || + (input.tableId !== undefined && !referencesTable(input.tableId, table)) + ) { throw new OrchestrationError('not_found', 'Table export not found') } const workspace = await resolveTableWorkspaceContext(record.workspaceId) diff --git a/apps/sim/lib/table/application/runs.test.ts b/apps/sim/lib/table/application/runs.test.ts index 71bdf18b686..b721d4d85b2 100644 --- a/apps/sim/lib/table/application/runs.test.ts +++ b/apps/sim/lib/table/application/runs.test.ts @@ -272,11 +272,22 @@ describe('table run dispatch reads', () => { allowPersonalApiKeys: true, billedAccountUserId: 'billing-owner-1', }) - mockGetTableById.mockResolvedValue(TABLE) + mockGetTableById.mockImplementation(async (id: string) => + id === TABLE.id ? TABLE : { ...TABLE, id, name: `Table ${id}` } + ) mockReadDispatch.mockResolvedValue(DISPATCH) mockListDispatches.mockResolvedValue([DISPATCH]) }) + it('reads a dispatch under its table named by its name, as every table route takes it', async () => { + await expect( + readTableDispatch.execute({ + principal: PRINCIPAL, + input: { tableId: TABLE.name, dispatchId: DISPATCH.id, workspaceId: TABLE.workspaceId }, + }) + ).resolves.toMatchObject({ dispatch: { id: DISPATCH.id } }) + }) + it('conceals a dispatch in another workspace as not found', async () => { mockReadDispatch.mockResolvedValue({ ...DISPATCH, workspaceId: 'workspace-other' }) diff --git a/apps/sim/lib/table/application/runs.ts b/apps/sim/lib/table/application/runs.ts index 1d0db508300..682b0c95717 100644 --- a/apps/sim/lib/table/application/runs.ts +++ b/apps/sim/lib/table/application/runs.ts @@ -29,6 +29,7 @@ import { readDispatch, } from '@/lib/table/dispatcher' import { signalTableRowsChanged } from '@/lib/table/events' +import { referencesTable } from '@/lib/table/ids' import { cancelWorkflowGroupRuns, runWorkflowColumn } from '@/lib/table/workflow-columns' interface TableRunInput { @@ -252,24 +253,25 @@ interface TableDispatchContext extends TableAuthorizationContext { * stored row, then asserts the caller's asserted scope against them. * * The canonical scope always comes from the dispatch itself — the asserted - * workspace and table are compared to it, never substituted for it. A workspace - * mismatch, a `tableId` naming a different table, a dispatch whose table was - * deleted, and a dispatch that never existed all report the same not-found, so - * the id space leaks nothing across tenants or across tables. + * workspace and table (by id or by name, as every table route takes it) are + * compared to it, never substituted for it. A workspace mismatch, a `tableId` + * naming a different table, a dispatch whose table was deleted, and a dispatch + * that never existed all report the same not-found, so the id space leaks + * nothing across tenants or across tables. */ async function resolveTableDispatchContext( input: TableDispatchResourceInput ): Promise { const dispatch = await readDispatch(input.dispatchId) - if ( - !dispatch || - dispatch.workspaceId !== input.workspaceId || - dispatch.tableId !== input.tableId - ) { + if (!dispatch || dispatch.workspaceId !== input.workspaceId) { throw new OrchestrationError('not_found', 'Table run dispatch not found') } const table = await getTableById(dispatch.tableId) - if (!table || table.workspaceId !== dispatch.workspaceId) { + if ( + !table || + table.workspaceId !== dispatch.workspaceId || + !referencesTable(input.tableId, table) + ) { throw new OrchestrationError('not_found', 'Table run dispatch not found') } return { ...(await resolveTableWorkspaceContext(dispatch.workspaceId)), dispatch } diff --git a/apps/sim/lib/table/constants.ts b/apps/sim/lib/table/constants.ts index 5560877e0e5..f84de3248b1 100644 --- a/apps/sim/lib/table/constants.ts +++ b/apps/sim/lib/table/constants.ts @@ -518,3 +518,10 @@ export function generateUniqueTableName(existingNames: string[]): string { const suffix = randomInt(100, 1000) return `${adj.toLowerCase()}_${noun.toLowerCase()}_${suffix}` } + +/** + * Every table not-found answer, a table that does not exist and one the caller may not reach + * alike: a name is guessable where an id is not, so the two must read the same. + */ +export const TABLE_NOT_FOUND_MESSAGE = + 'Table not found in this workspace, by id or by name. It may not exist or may belong to a different workspace; list the tables in this workspace to see the ids and names you can use here.' diff --git a/apps/sim/lib/table/ids.ts b/apps/sim/lib/table/ids.ts index 5eea789dff7..c4b035af915 100644 --- a/apps/sim/lib/table/ids.ts +++ b/apps/sim/lib/table/ids.ts @@ -3,6 +3,16 @@ import { generateId } from '@sim/utils/id' /** What every table id starts with: a reference that does not is no table id. */ export const TABLE_ID_PREFIX = 'tbl_' +/** + * Whether `reference`, a table route's `{tableId}`, names `table`: its id, or (when not shaped + * like an id) its name, which is unique among a workspace's active tables. + */ +export function referencesTable(reference: string, table: { id: string; name: string }): boolean { + return ( + reference === table.id || (!reference.startsWith(TABLE_ID_PREFIX) && reference === table.name) + ) +} + /** * Mints a fresh table id: `tbl_` plus a dash-stripped v4 UUID, the shape Tables have carried * since they shipped and the one the CLI and Copilot describe to users. Every path that diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index c44ef00238a..4d2f09399df 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -20547,7 +20547,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Add column', @@ -20562,7 +20562,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Add workflow group', @@ -20935,7 +20935,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Bulk update rows', @@ -20984,7 +20984,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'dispatchId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', dispatchId: 'Unique table run-dispatch identifier.', }, responseMode: 'json', @@ -21003,7 +21003,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'exportId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', exportId: 'Unique table-export identifier.', }, responseMode: 'json', @@ -21043,7 +21043,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Cancel column runs', @@ -22142,7 +22142,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Create run dispatch', @@ -22175,7 +22175,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Create table export', @@ -22257,7 +22257,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Create rows', @@ -22272,7 +22272,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Create view', @@ -22799,7 +22799,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Delete table', @@ -22813,7 +22813,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Delete column', @@ -22859,7 +22859,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'rowId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', rowId: 'Unique table row identifier.', }, responseMode: 'json', @@ -22874,7 +22874,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Delete rows', @@ -22895,7 +22895,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'viewId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', viewId: 'Unique saved-view identifier.', }, responseMode: 'json', @@ -22958,7 +22958,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Delete workflow group', @@ -24062,7 +24062,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'rowId', 'groupId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', rowId: 'Unique table row identifier.', groupId: 'Workflow or enrichment group to run.', }, @@ -24345,7 +24345,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Get table', @@ -24359,7 +24359,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'dispatchId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', dispatchId: 'Unique table run-dispatch identifier.', }, responseMode: 'json', @@ -24378,7 +24378,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'exportId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', exportId: 'Unique table-export identifier.', }, responseMode: 'json', @@ -24418,7 +24418,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'rowId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', rowId: 'Unique table row identifier.', }, responseMode: 'json', @@ -24438,7 +24438,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'viewId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', viewId: 'Unique saved-view identifier.', }, responseMode: 'json', @@ -26937,7 +26937,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'List run dispatches', @@ -26987,7 +26987,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'List rows', @@ -27072,7 +27072,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'List views', @@ -27175,7 +27175,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'List workflow groups', @@ -28037,7 +28037,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Query rows', @@ -28070,7 +28070,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Count rows', @@ -28615,7 +28615,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique identifier of the archived table. A restore takes the id alone: archived tables need not have unique names.', }, responseMode: 'json', summary: 'Restore table', @@ -28799,7 +28799,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'rowId', 'groupId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', rowId: 'Unique table row identifier.', groupId: 'Workflow or enrichment group to run.', }, @@ -29257,7 +29257,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Search rows', @@ -29362,7 +29362,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'exportId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', exportId: 'Unique table-export identifier.', }, responseMode: 'json', @@ -29981,7 +29981,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Update rows by filter', @@ -30111,7 +30111,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Update table', @@ -30135,7 +30135,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Update column', @@ -30155,7 +30155,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'rowId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', rowId: 'Unique table row identifier.', }, responseMode: 'json', @@ -30175,7 +30175,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId', 'viewId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', viewId: 'Unique saved-view identifier.', }, responseMode: 'json', @@ -30219,7 +30219,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Update workflow group', @@ -30490,7 +30490,7 @@ export const V2_OPERATIONS = { pathParams: ['tableId'] as const, pathParamDocs: { tableId: - 'Unique table identifier. With a workspace named, the name of one of its active tables also works.', + 'Unique table identifier. With a workspace named, the name of one of its active tables also works (a reference starting `tbl_` is always read as an id).', }, responseMode: 'json', summary: 'Upsert row', From e5144c486eb720eb27db03e8519f8ca9fe315f9a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:26:25 -0800 Subject: [PATCH 46/85] docs(cli): the CI recipe commits the directory after a partial apply (exit 15 or 8), and the apply table lists 14 and the exit 15 change --- apps/docs/content/docs/cli/scripting.mdx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/docs/content/docs/cli/scripting.mdx b/apps/docs/content/docs/cli/scripting.mdx index cd4dc3307ec..a6a494589e3 100644 --- a/apps/docs/content/docs/cli/scripting.mdx +++ b/apps/docs/content/docs/cli/scripting.mdx @@ -215,9 +215,12 @@ The CLI resends a request the API answers `429` only when sending it twice is sa | `9` | Still rate limited (`429`) after the CLI's retries; nothing was written | | `10` | Busy, retry: another apply is writing the workspace (`409 SOURCE_BUSY`), or another `sim workspaces source` command is using the same directory (`SOURCE_DIR_BUSY`); nothing was written: run the command again once the other finished | | `13` | `AUTH_REQUIRED`: not logged in, or the server refused the credential; nothing was sent | +| `14` | Run without `--yes` and with no terminal to ask: the plan was printed with no errors and nothing was written; run the same command with `--yes` | | `15` | Written in part: changes that use a declared secret with no value, or a credential key nothing binds to, were held back and the rest was applied and saved; set the secret or connect the credential, then apply again (a promotion with `--to` too) | | `130` | Interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check | +Earlier CLI releases exited `1` when an apply held changes back, whether or not it wrote the rest. A script that reads `1` as "held back" should test for `15` too. + Both waits default to 3600 seconds; `--wait-timeout 0` waits indefinitely. `SIM_TIMEOUT_SECONDS` independently bounds one API request. A timeout does not cancel the underlying run or operation. A synchronous or followed workflow run prints its result before exiting 1 for failure/cancellation. A paused run is not failed and can return 0; use `runs wait` or inspect status if your script requires completion. Fetching a failed run or listing runs only reports their state. @@ -411,7 +414,7 @@ jobs: - run: sim workspaces source apply --dir workspace --dry-run - if: github.event_name == 'push' run: sim workspaces source apply --dir workspace --yes - - if: github.event_name == 'push' + - if: ${{ !cancelled() && github.event_name == 'push' }} run: | git add -A workspace if ! git diff --cached --quiet; then @@ -421,7 +424,7 @@ jobs: fi ``` -`check` runs first because it is offline and fast, and it regenerates `.sim/sdk/workspace.d.ts`, so the `tsc` step after it types resources the pull request adds. A workspace API key can apply tables, rows, knowledge bases, files, custom tools, MCP servers and credential bindings. Workflows, skills, secrets and deployments need a member's personal API key, and deployments need an admin. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. After merging two branches that each applied, a dry run with no changes means the files match the workspace. Exit `5` means a resource changed since this branch's base: get the workspace into a fresh directory and carry the edit over. Exit `10` means another apply is writing the workspace (or another command is using the directory), so retry; the `concurrency` key keeps two runs of this job from overlapping. +`check` runs first because it is offline and fast, and it regenerates `.sim/sdk/workspace.d.ts`, so the `tsc` step after it types resources the pull request adds. A workspace API key can apply tables, rows, knowledge bases, files, custom tools, MCP servers and credential bindings. Workflows, skills, secrets and deployments need a member's personal API key, and deployments need an admin. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. That step runs even when the apply failed (`!cancelled()`), because an apply can fail having written part of its plan: exit `15` means it held back changes that use a secret with no value or a credential nothing binds to and applied the rest, and exit `8` means it stopped part-way. Either way the directory records what was written, so committing it keeps the next run from being refused as stale (exit `5`) for resources this run wrote; the job still fails, so set the secret, connect the credential or fix the failure, and push again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. After merging two branches that each applied, a dry run with no changes means the files match the workspace. Exit `5` means a resource changed since this branch's base: get the workspace into a fresh directory and carry the edit over. Exit `10` means another apply is writing the workspace (or another command is using the directory), so retry; the `concurrency` key keeps two runs of this job from overlapping. To promote the same directory to a second workspace, add a step with `--to` before the step that commits the files back: From 53bf0d8f43c2523f4ad64313aad3c17d717a81fd Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:26:51 -0800 Subject: [PATCH 47/85] fix(sim-cli): GitHub annotations give each file's path from the repository root, so they land when the step runs in a subdirectory --- .../sim-cli/src/output/github-actions.test.ts | 13 ++++++++++++- packages/sim-cli/src/output/github-actions.ts | 16 +++++++++++----- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/sim-cli/src/output/github-actions.test.ts b/packages/sim-cli/src/output/github-actions.test.ts index e7bc1025c52..133f5c7a471 100644 --- a/packages/sim-cli/src/output/github-actions.test.ts +++ b/packages/sim-cli/src/output/github-actions.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { annotationLine } from './github-actions' +import { annotationLine, annotationPath } from './github-actions' describe('GitHub Actions workflow commands', () => { it('escapes a message and its properties as the runner unescapes them', () => { @@ -14,4 +14,15 @@ describe('GitHub Actions workflow commands', () => { '::error file=workflows/a%2Cb/workflow.ts,line=3,col=9,title=E_X%3A y::100%25 wrong%0Asecond line' ) }) + + it('points an annotation at its path from the repository root, whatever directory the step runs in', () => { + const env = { GITHUB_WORKSPACE: '/home/runner/work/repo/repo' } + + expect( + annotationPath('/home/runner/work/repo/repo/workspace', 'workflows/ingest/workflow.ts', env) + ).toBe('workspace/workflows/ingest/workflow.ts') + expect(annotationPath('/tmp/elsewhere', 'workflows/ingest/workflow.ts', env)).toBe( + '/tmp/elsewhere/workflows/ingest/workflow.ts' + ) + }) }) diff --git a/packages/sim-cli/src/output/github-actions.ts b/packages/sim-cli/src/output/github-actions.ts index 2934822d511..6cb1cd279cf 100644 --- a/packages/sim-cli/src/output/github-actions.ts +++ b/packages/sim-cli/src/output/github-actions.ts @@ -7,7 +7,7 @@ * stays the one result document a script parses. */ import { appendFileSync } from 'node:fs' -import { isAbsolute, join, relative } from 'node:path' +import { isAbsolute, relative, resolve } from 'node:path' import { getErrorMessage } from '@sim/utils/errors' import { embedStore } from '../embed-context' import { isEnabled } from '../environment' @@ -53,11 +53,17 @@ export function annotationLine( /** * `file` (relative to the source directory `dir`) as the runner resolves an annotation's path: - * relative to the job's working directory, where the checkout is. A path outside it stays absolute. + * relative to the repository root (`GITHUB_WORKSPACE`), whatever the step's working directory. A + * file outside the repository is given by its absolute path. */ -export function annotationPath(dir: string, file: string): string { - const path = relative(process.cwd(), isAbsolute(file) ? file : join(dir, file)) - return path.startsWith('..') || isAbsolute(path) ? join(dir, file) : path +export function annotationPath( + dir: string, + file: string, + env: NodeJS.ProcessEnv = process.env +): string { + const absolute = resolve(dir, file) + const path = relative(env.GITHUB_WORKSPACE || process.cwd(), absolute) + return path.startsWith('..') || isAbsolute(path) ? absolute : path } /** Prints `lines` as workflow commands, when this is a GitHub Actions step. */ From da94b4bb9d3e688de9c9a7e130cf40e1a7994716 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:28:02 -0800 Subject: [PATCH 48/85] fix(table): a managed rows write refuses the row limit only when it grows the table --- apps/sim/lib/table/rows/keyed-write.ts | 6 ++-- .../application/rows.integration.ts | 34 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/table/rows/keyed-write.ts b/apps/sim/lib/table/rows/keyed-write.ts index 20d9e668ac4..7e244b52a7d 100644 --- a/apps/sim/lib/table/rows/keyed-write.ts +++ b/apps/sim/lib/table/rows/keyed-write.ts @@ -37,8 +37,9 @@ export interface KeyedRows { /** Whether stored rows no declared row matches are deleted; otherwise they refuse the write. */ allowDelete: boolean /** - * The plan's row limit for the table, when it has one: the write is refused when the rows it - * leaves, the stored rows with no key value it keeps included, would cross it. + * The plan's row limit for the table (negative for none): a write that grows the table is + * refused when the rows it leaves, the stored rows with no key value it keeps included, would + * cross it. A write that adds no rows on balance is never refused, as other row writes are not. */ rowLimit?: number } @@ -141,6 +142,7 @@ export async function writeKeyedRowsWithTx( const { rowLimit } = declared if ( rowLimit !== undefined && + inserts.length > removed.length && wouldExceedRowLimit(rowLimit, stored.length - removed.length, inserts.length) ) { throw new TableRowLimitError(rowLimit) diff --git a/apps/sim/lib/workspace-source/application/rows.integration.ts b/apps/sim/lib/workspace-source/application/rows.integration.ts index 2aa75fa4ebe..d2acd6eab6f 100644 --- a/apps/sim/lib/workspace-source/application/rows.integration.ts +++ b/apps/sim/lib/workspace-source/application/rows.integration.ts @@ -1174,6 +1174,40 @@ export default defineTable({ } ) + check( + 'still applies a managed write that adds no rows to a table already over its row limit', + async () => { + const workspaceId = await newWorkspace() + const optionalKey = MANAGED.replace( + 'column.string({ required: true, unique: true })', + 'column.string({ unique: true })' + ) + const created = await apply(workspaceId, { + 'tables/plans.ts': optionalKey, + 'tables/plans.rows.jsonl': ROWS, + }) + expect(created.failed).toBeUndefined() + await addUiRow(workspaceId, {}) + await addUiRow(workspaceId, {}) + const read = await runner.get(workspaceId) + planRowLimit.value = 3 + try { + const written = await apply( + workspaceId, + { + ...read.files, + 'tables/plans.rows.jsonl': ROWS.replace('"seats":10', '"seats":12'), + }, + { base: read.base } + ) + expect(written.failed).toBeUndefined() + } finally { + planRowLimit.value = undefined + } + expect((await storedRows(workspaceId)).map((row) => row.seats)).toContain(12) + } + ) + check( 'refuses at plan time a column made required that a row the UI added leaves empty, though the rows file is unchanged', async () => { From c9f4fced36b172b56f155acaca9841a7e1a2d121 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:28:10 -0800 Subject: [PATCH 49/85] docs(workflow-persistence): creation order is stable only for rows a save stamped; tied rows load in physical order --- packages/workflow-persistence/src/load.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/workflow-persistence/src/load.ts b/packages/workflow-persistence/src/load.ts index 247a85e0641..5e21a383957 100644 --- a/packages/workflow-persistence/src/load.ts +++ b/packages/workflow-persistence/src/load.ts @@ -181,10 +181,12 @@ export async function loadWorkflowsFromNormalizedTablesRaw( /** * The order a workflow's block, edge or subflow rows load in: creation order. A save stamps the - * rows it inserts together a microsecond apart, in the order the state listed them, so this is - * that order; rows written in one statement with one timestamp (older saves, a duplicate, a - * paste) keep the order they were inserted in. The executor reads it for a condition or router - * edge with no handle, and the editor for its node order. + * rows it inserts together a microsecond apart, in the order the state listed them, so those rows + * keep that order however often they are rewritten later. Rows that share one timestamp (older + * saves, a duplicate, a paste, realtime batch adds) load in physical (`ctid`) order, as they + * always did: insertion order until a row is rewritten, which moves it to the end of its tie + * group. The executor reads the order for a condition or router edge with no handle, and the + * editor for its node order. */ export function creationOrder(table: GraphTable) { return [asc(table.createdAt), sql`ctid`] as const From a2e6c362a31d6dd82d3dfe84984cc1950acde1a5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:29:28 -0800 Subject: [PATCH 50/85] fix(files): a content read never retries a superseded storage key, and the test waits for it to settle before counting fetches --- apps/sim/hooks/queries/workspace-files.test.tsx | 2 ++ apps/sim/hooks/queries/workspace-files.ts | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/sim/hooks/queries/workspace-files.test.tsx b/apps/sim/hooks/queries/workspace-files.test.tsx index 9551852c5b9..15e98cce428 100644 --- a/apps/sim/hooks/queries/workspace-files.test.tsx +++ b/apps/sim/hooks/queries/workspace-files.test.tsx @@ -271,6 +271,8 @@ describe('useWorkspaceFileContent stale storage key', () => { const refetchQueries = vi.spyOn(queryClient, 'refetchQueries') await vi.waitFor(() => expect(refetchQueries).toHaveBeenCalled()) + // Settled, so a fetch or refetch that would follow the first one has had its chance to show. + await vi.waitFor(() => expect(queryClient.isFetching()).toBe(0)) expect(fetchCount).toBe(1) expect(refetchQueries).toHaveBeenCalledWith( diff --git a/apps/sim/hooks/queries/workspace-files.ts b/apps/sim/hooks/queries/workspace-files.ts index 59f8aa70f1f..0afd21a90b0 100644 --- a/apps/sim/hooks/queries/workspace-files.ts +++ b/apps/sim/hooks/queries/workspace-files.ts @@ -893,7 +893,11 @@ export function useWorkspaceFileContent( }, enabled: !!workspaceId && !!fileId && !!key, staleTime: WORKSPACE_FILE_CONTENT_STALE_TIME, - retry: (failureCount, error) => failureCount < 1 && !(error instanceof FileTextSizeError), + // A superseded key is never retried: the record is re-resolved instead (useStaleKeyRecovery). + retry: (failureCount, error) => + failureCount < 1 && + !(error instanceof FileTextSizeError) && + !(error instanceof StaleStorageKeyError), refetchOnWindowFocus: options?.refetchOnWindowFocus === false ? false : 'always', refetchInterval: options?.refetchInterval ?? false, }) From 2503fa7eb2c72a0e270effb910cc7c2d9af3e0c9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:30:07 -0800 Subject: [PATCH 51/85] test(extension): every fixture API call goes through one helper that opens a fresh connection --- .../sim/scripts/test-browser-extension-e2e.ts | 86 +++++++++++++------ 1 file changed, 60 insertions(+), 26 deletions(-) diff --git a/apps/sim/scripts/test-browser-extension-e2e.ts b/apps/sim/scripts/test-browser-extension-e2e.ts index 86d2002b4e0..f3ef89a1bcf 100644 --- a/apps/sim/scripts/test-browser-extension-e2e.ts +++ b/apps/sim/scripts/test-browser-extension-e2e.ts @@ -38,12 +38,30 @@ const logger = createLogger('BrowserExtensionAppE2E') const expect = browserExpect.configure({ timeout: 30_000 }) const ACCESS_REVALIDATION_TIMEOUT_MS = 35_000 const ACCESS_POLL_INTERVAL_MS = 30_000 +/** The options a fixture API call takes, as `APIRequestContext.fetch` does. */ +type FixtureRequestOptions = Omit< + NonNullable[1]>, + 'method' +> + /** - * `next start` on Node 24 destroys a keep-alive socket idle for 6s (keepAliveTimeout plus its 1s - * buffer), and an API-context request reusing that socket as it closes hangs up (ECONNRESET), so - * every fixture call opens its own connection. + * A fixture API call through `context`'s request context (its cookies, so its session), always on + * a connection of its own: `next start` on Node 24 destroys a keep-alive socket idle for 6s + * (keepAliveTimeout plus its 1s buffer), and a request reusing that socket as it closes hangs up + * (ECONNRESET). Every fixture call goes through here, so none can forget the header. */ -const FRESH_CONNECTION = { Connection: 'close' } as const +function fixtureRequest( + context: BrowserContext, + method: 'GET' | 'POST' | 'PATCH', + url: string, + options: FixtureRequestOptions = {} +) { + return context.request.fetch(url, { + ...options, + method, + headers: { ...options.headers, Connection: 'close' }, + }) +} function required(name: string): string { const value = process.env[name] assert(value, `${name} must be explicitly provided`) @@ -543,14 +561,19 @@ try { } }) const signInAndSeed = async () => { - const signup = await browserContext.request.post(`${base.origin}/api/auth/sign-up/email`, { - headers: { ...FRESH_CONNECTION, origin: base.origin }, - data: { - name: 'Extension QA', - email: `extension-${generateId()}@example.test`, - password: generateRandomHex(24), - }, - }) + const signup = await fixtureRequest( + browserContext, + 'POST', + `${base.origin}/api/auth/sign-up/email`, + { + headers: { origin: base.origin }, + data: { + name: 'Extension QA', + email: `extension-${generateId()}@example.test`, + password: generateRandomHex(24), + }, + } + ) assert.equal(signup.status(), 200, `Sign-up failed: ${await signup.text()}`) const payload: unknown = await signup.json() const id = toRecord(toRecord(payload).user).id @@ -1133,9 +1156,11 @@ try { 'Toolbar and authenticated chat align at 320/390 pixels in light and dark themes', async () => { for (const theme of ['light', 'dark'] as const) { - const settings = await browserContext.request.patch( + const settings = await fixtureRequest( + browserContext, + 'PATCH', `${base.origin}/api/users/me/settings`, - { headers: FRESH_CONNECTION, data: { theme } } + { data: { theme } } ) assert.equal(settings.status(), 200) await navigate(`${base.origin}/extension/${alphaId}`) @@ -2184,10 +2209,12 @@ try { } ) const setActiveOrganization = async () => { - const active = await browserContext.request.post( + const active = await fixtureRequest( + browserContext, + 'POST', `${base.origin}/api/auth/organization/set-active`, { - headers: { ...FRESH_CONNECTION, origin: base.origin }, + headers: { origin: base.origin }, data: { organizationId }, } ) @@ -2894,18 +2921,20 @@ try { await input.fill('Keep text, but discard the page when Chat access is revoked.') await expect(attachments()).toHaveCount(1) await shell.bringToFront() - const discovery = await browserContext.request.get( - `${base.origin}/api/access-requests/discovery?kind=workspace&workspaceId=${hostedWorkspaceId}&targetKind=feature`, - { headers: FRESH_CONNECTION } + const discovery = await fixtureRequest( + browserContext, + 'GET', + `${base.origin}/api/access-requests/discovery?kind=workspace&workspaceId=${hostedWorkspaceId}&targetKind=feature` ) assert.equal(discovery.status(), 200) assert.equal(toRecord(await discovery.json()).enabled, allowRequests) await sql`insert into permission_group (id, organization_id, name, config, created_by, is_default) values (${permissionGroupId}, ${otherOrganizationId}, 'Revoked Chat access', ${sql.json({ hideCopilot: true })}, ${otherUserId}, true)` - const policy = await browserContext.request.get( - `${base.origin}/api/permission-groups/user?workspaceId=${hostedWorkspaceId}`, - { headers: FRESH_CONNECTION } + const policy = await fixtureRequest( + browserContext, + 'GET', + `${base.origin}/api/permission-groups/user?workspaceId=${hostedWorkspaceId}` ) assert.equal(policy.status(), 200) assert.equal(toRecord(toRecord(await policy.json()).config).hideCopilot, true) @@ -3345,10 +3374,15 @@ try { 'Signing out removes authenticated chat and captured page context', async () => { await capture() - const response = await browserContext.request.post(`${base.origin}/api/auth/sign-out`, { - headers: { ...FRESH_CONNECTION, origin: base.origin }, - data: {}, - }) + const response = await fixtureRequest( + browserContext, + 'POST', + `${base.origin}/api/auth/sign-out`, + { + headers: { origin: base.origin }, + data: {}, + } + ) assert.equal(response.status(), 200) await shell.clock.setFixedTime(Date.now() + 360_000) await reconnect() From 959c33ba898e50120e32a6b57126effd2519a7d2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:30:51 -0800 Subject: [PATCH 52/85] fix(sim-cli): a workspace apply's step summary says what it wrote, and the held exit code drops a condition that is always true --- .../protocol/workspace-source-apply.test.ts | 14 ++++++++++++++ .../commands/protocol/workspace-source-apply.ts | 6 ++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index 05ea67a3015..d9706e985a3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1714,6 +1714,20 @@ describe('workspaces source apply', () => { ]) }) + it('says what an apply wrote in the step summary, not what it would write', async () => { + const summary = join(dir, 'step-summary.md') + vi.stubEnv('GITHUB_ACTIONS', 'true') + vi.stubEnv('GITHUB_STEP_SUMMARY', summary) + const created = { kind: 'table' as const, key: 'leads', action: 'create' as const } + request.mockResolvedValue(answer({ plan: [created], applied: [created] })) + + await apply('--yes') + + const markdown = readFileSync(summary, 'utf8') + expect(markdown).toContain('### Sim workspace apply: ws_local') + expect(markdown).toContain('1 created, 0 updated, 0 deleted') + }) + it('exits 1, not 15, when every change it would write was held back and nothing was written', async () => { request.mockResolvedValue( answer({ diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 13a2c807911..794e0e50940 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -912,7 +912,7 @@ export function attachWorkspaceSourceApply(source: Command): void { `Held back, not written: ${held.map((change) => `${change.kind} ${change.key}`).join(', ')}. Fix what each one's error names, then apply again.` ) // Written in part is not the same outcome as nothing written: a script must tell them apart. - setSoftExitCode(!data.dryRun && data.applied.length > 0 ? SOURCE_HELD_EXIT_CODE : 1) + setSoftExitCode(data.applied.length > 0 ? SOURCE_HELD_EXIT_CODE : 1) } if (data.failed) { printError(`Stopped at ${data.failed.kind} ${data.failed.key}: ${data.failed.message}`) @@ -949,7 +949,9 @@ function planMarkdown(data: ApplyData, workspaceId: string): string { const lines = [ `### Sim workspace ${data.dryRun ? 'plan' : 'apply'}: ${cell(workspaceId)}`, '', - `${summary.created.length} to create, ${summary.updated} to update, ${summary.deleted} to delete, ${summary.unchanged} unchanged; ${summary.errors} error(s), ${summary.warnings} warning(s).`, + data.dryRun + ? `${summary.created.length} to create, ${summary.updated} to update, ${summary.deleted} to delete, ${summary.unchanged} unchanged; ${summary.errors} error(s), ${summary.warnings} warning(s).` + : `${summary.created.length} created, ${summary.updated} updated, ${summary.deleted} deleted, ${summary.unchanged} unchanged; ${summary.errors} error(s), ${summary.warnings} warning(s).`, ...(rows.length > 0 ? [ '', From 93f914d4ea0860c0a7ce33f7b6ee1f1c3c36f4fc Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:32:26 -0800 Subject: [PATCH 53/85] fix(sim-cli): run --dir maps only a block's failure, reads a line only from the executor's prefix, never replaces the run's failure, and is refused with --follow or --async --- .../commands/protocol/run-source-location.ts | 35 +++++++--- .../protocol/workflow-run-follow.test.ts | 68 ++++++++++++++++++- .../commands/protocol/workflow-run-follow.ts | 11 ++- 3 files changed, 102 insertions(+), 12 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/run-source-location.ts b/packages/sim-cli/src/commands/protocol/run-source-location.ts index b91668f5640..445e5460bd5 100644 --- a/packages/sim-cli/src/commands/protocol/run-source-location.ts +++ b/packages/sim-cli/src/commands/protocol/run-source-location.ts @@ -3,6 +3,7 @@ * the directory's lock binds that id to the block's key, const and function file, and a function * block's error names its line, which the stored code keeps one to one with the file. */ +import { getErrorMessage } from '@sim/utils/errors' import { toRecord } from '@sim/utils/object' import { escapeRegExp } from '@sim/utils/string' import { parseWorkflowLock } from '@sim/workflow-code' @@ -23,9 +24,13 @@ interface RunFailureSite { declaredAt: string | null } -/** The line a function block's error names (`Type Error: Line 3: …`), else `null`. */ +/** + * The line a function block's error names, in the executor's own prefix (`Line 3: …`, + * `Line 3 - …`, or either after an error type such as `Type Error: `), else `null`: a `Line 3` + * further into the message is the user's own text, not a source line. + */ function errorLine(message: string): number | null { - const match = /\bLine (\d+)\b/.exec(message) + const match = /^(?:[A-Za-z]+(?: [A-Za-z]+)?: )?Line (\d+)(?::| - )/.exec(message) return match ? Number(match[1]) : null } @@ -37,16 +42,15 @@ function declarationLine(entry: string, ident: string): number | null { } /** - * Where the run's failure sits in the workflow source directory `dir`: `null` when the error names - * no block, the directory holds another workflow's source, or its lock does not bind the block. + * Where the failure of `blockId` sits in the workflow source directory `dir`: `null` when the + * directory holds another workflow's source, or its lock does not bind the block. */ async function runFailureSite( dir: string, workflowId: string, - error: unknown + blockId: string, + message: unknown ): Promise { - const { blockId, message } = toRecord(error) - if (typeof blockId !== 'string') return null if (toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)).workflowId !== workflowId) return null const { lock } = parseWorkflowLock(await readPreviousLock(dir)) const bound = Object.entries(lock?.blocks ?? {}).find(([, entry]) => entry.id === blockId) @@ -69,14 +73,26 @@ async function runFailureSite( /** * Prints where a failed run failed in `dir` (on stderr, and as a GitHub Actions annotation in a - * job), or that `dir` cannot say. + * job), or that `dir` cannot say. Prints nothing for a failure that names no block (a timeout, an + * input refused), and never throws: a directory it cannot read is a note, so the run's own failure + * and exit code stand. */ export async function printRunFailureSite( dir: string, workflowId: string, error: unknown ): Promise { - const site = await runFailureSite(dir, workflowId, error) + const { blockId, message } = toRecord(error) + if (typeof blockId !== 'string') return + let site: RunFailureSite | null + try { + site = await runFailureSite(dir, workflowId, blockId, message) + } catch (readError) { + printError( + `The failure is not mapped to a source line: ${dir} could not be read (${getErrorMessage(readError)}).` + ) + return + } if (!site) { printError( `${dir} does not bind the block that failed (another workflow's source, or a block added since the get), so the failure is not mapped to a source line.` @@ -85,7 +101,6 @@ export async function printRunFailureSite( } const where = `${site.file}${site.line === null ? '' : `:${site.line}`}` const declared = site.declaredAt ? `, declared at ${site.declaredAt}` : '' - const message = toRecord(error).message const text = typeof message === 'string' ? message : 'The block failed.' printError(`${where}: ${text} (block ${site.block}${declared})`) printAnnotations([ diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index ee3c11372fc..207d32076ee 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Command } from 'commander' @@ -469,6 +469,72 @@ describe('sim workflows run --follow', () => { } }) + it('with --dir, maps only a block failure, reads a line only from the executor prefix, and keeps the run failure when the directory cannot be read', async () => { + const dir = mkdtempSync(join(tmpdir(), 'sim-run-site-')) + try { + mkdirSync(join(dir, '.sim'), { recursive: true }) + writeFileSync(join(dir, '.sim/base.json'), JSON.stringify({ workflowId: WORKFLOW_ID })) + writeFileSync( + join(dir, '.sim/lock.json'), + JSON.stringify({ + version: 1, + blocks: { + normalize: { + id: 'b-fn', + parent: null, + ident: 'normalize', + order: 0, + codeFile: 'functions/normalize.js', + }, + }, + variables: {}, + }) + ) + const failed = (error: Record) => + ndjsonResponse({ + type: 'final', + data: { runId: 'run-1', workflowId: WORKFLOW_ID, status: 'failed', output: {}, error }, + }) + vi.spyOn(console, 'log').mockImplementation(() => {}) + const stderr = vi.spyOn(console, 'error').mockImplementation(() => {}) + const printed = () => stderr.mock.calls.map((call) => call.join(' ')).join('\n') + + requestRaw.mockResolvedValue(failed({ message: 'The run timed out', code: 'TIMEOUT' })) + await expect(run(WORKFLOW_ID, '--dir', dir)).rejects.toThrow('The run timed out') + expect(printed()).not.toContain(dir) + + stderr.mockClear() + writeFileSync(join(dir, 'workflow.ts'), "export default workflow('W', () => {})\n") + requestRaw.mockResolvedValue( + failed({ message: 'Error: Line 3 of the CSV is bad', blockId: 'b-fn' }) + ) + await expect(run(WORKFLOW_ID, '--dir', dir)).rejects.toThrow('Line 3 of the CSV') + expect(printed()).toContain( + `${join(dir, 'functions/normalize.js')}: Error: Line 3 of the CSV is bad (block normalize)` + ) + + stderr.mockClear() + rmSync(join(dir, 'workflow.ts')) + symlinkSync(join(dir, '.sim/base.json'), join(dir, 'workflow.ts')) + requestRaw.mockResolvedValue(failed({ message: 'Line 2 - boom', blockId: 'b-fn' })) + await expect(run(WORKFLOW_ID, '--dir', dir)).rejects.toThrow('boom') + expect(printed()).toContain('could not be read') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('refuses --dir with --follow or --async before sending anything', async () => { + await expect(run(WORKFLOW_ID, '--dir', '.', '--follow')).rejects.toThrow( + '--follow and --async do not report the block that failed' + ) + await expect(run(WORKFLOW_ID, '--dir', '.', '--async')).rejects.toThrow( + '--follow and --async do not report the block that failed' + ) + expect(request).not.toHaveBeenCalled() + expect(requestRaw).not.toHaveBeenCalled() + }) + it('explains a deployment that answers JSON instead of an event stream', async () => { const cancel = vi.fn().mockResolvedValue(undefined) requestRaw.mockResolvedValue({ 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 692ef162e2b..248964898ca 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -510,6 +510,15 @@ function followOrDelegate(previous: ((args: unknown[]) => unknown) | null) { 0 ) } + if ( + typeof initialFlags.dir === 'string' && + (initialFlags.follow === true || initialFlags.async === true) + ) { + throw new SimApiError( + '--dir maps the failure of a run this command waits for; --follow and --async do not report the block that failed. Drop --dir, or run without them', + 0 + ) + } const selection = resolveWorkflowRunSelection(initialFlags) if (selection) command.setOptionValue('run', selection) const flags = command.optsWithGlobals() as Record @@ -603,7 +612,7 @@ export function attachWorkflowRunFollow(workflows: Command): void { ) .option( '--dir ', - "This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json" + "This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running" ) .option( WAIT_TIMEOUT_FLAG, From 2bd8ed9264b12161d974c35a2eeb73be2a1010b1 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:33:35 -0800 Subject: [PATCH 54/85] fix(docs): the CLI reference keeps a help table laid out in columns, as the operations guide's handles, instead of one run-on paragraph --- apps/docs/content/docs/cli/reference.mdx | 23 +++++++++++++++++++++-- apps/docs/content/docs/cli/workflows.mdx | 23 +++++++++++++++++++++-- scripts/generate-cli-docs.test.ts | 14 +++++++++++++- scripts/generate-cli-docs.ts | 14 +++++++++++--- 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 82f333ebb0f..865e712b92d 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -7755,7 +7755,26 @@ sim workflows operations apply [options] -Edges: connections maps a source handle to its targets: {"source":"<id>"}, {"source":["<a>","<b>"]}, or {"source":{"block":"<id>","handle":"<target handle>"}}; "success" is an alias of "source". An add's connections create the new block's edges. An edit's connections REPLACE every outgoing edge of that block, on every handle: list again each edge to keep. To remove one edge, edit its source block with {"removeEdges":[{"targetBlockId":"<id>","sourceHandle":"source"}]} (sourceHandle defaults to "source"). Source handles: source the normal path error a failure (a block that has an error output) if, else-if-0, else a condition's branches, in order (else-if-1, … for more) route-0, route-1, … a router's routes, in order loop-start-source a loop into its body; loop-end-source after the loop parallel-start-source, parallel-end-source the same for a parallel Renames: An edit's {"name":"New name"} also rewrites every <old key.field> reference to the block, in other blocks' inputs and in a loop's or parallel's collection and condition. +```text +Edges: + connections maps a source handle to its targets: {"source":""}, {"source":["",""]}, + or {"source":{"block":"","handle":""}}; "success" is an alias of "source". + An add's connections create the new block's edges. An edit's connections REPLACE every + outgoing edge of that block, on every handle: list again each edge to keep. + To remove one edge, edit its source block with + {"removeEdges":[{"targetBlockId":"","sourceHandle":"source"}]} (sourceHandle defaults to + "source"). +Source handles: + source the normal path + error a failure (a block that has an error output) + if, else-if-0, else a condition's branches, in order (else-if-1, … for more) + route-0, route-1, … a router's routes, in order + loop-start-source a loop into its body; loop-end-source after the loop + parallel-start-source, parallel-end-source the same for a parallel +Renames: + An edit's {"name":"New name"} also rewrites every reference to the block, in + other blocks' inputs and in a loop's or parallel's collection and condition. +``` API request and response schemas: [applyWorkflowOperations](/api-reference/workflows/applyWorkflowOperations). @@ -8446,7 +8465,7 @@ sim workflows run [options] | `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | | `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | -| `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. | +| `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running. | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | | `--follow` | No | Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns. | | `--include-thinking` | No | Show model reasoning while following (requires --follow). | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index e62678330fe..641fe2e9abe 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -335,7 +335,26 @@ sim workflows operations apply [options] -Edges: connections maps a source handle to its targets: {"source":"<id>"}, {"source":["<a>","<b>"]}, or {"source":{"block":"<id>","handle":"<target handle>"}}; "success" is an alias of "source". An add's connections create the new block's edges. An edit's connections REPLACE every outgoing edge of that block, on every handle: list again each edge to keep. To remove one edge, edit its source block with {"removeEdges":[{"targetBlockId":"<id>","sourceHandle":"source"}]} (sourceHandle defaults to "source"). Source handles: source the normal path error a failure (a block that has an error output) if, else-if-0, else a condition's branches, in order (else-if-1, … for more) route-0, route-1, … a router's routes, in order loop-start-source a loop into its body; loop-end-source after the loop parallel-start-source, parallel-end-source the same for a parallel Renames: An edit's {"name":"New name"} also rewrites every <old key.field> reference to the block, in other blocks' inputs and in a loop's or parallel's collection and condition. +```text +Edges: + connections maps a source handle to its targets: {"source":""}, {"source":["",""]}, + or {"source":{"block":"","handle":""}}; "success" is an alias of "source". + An add's connections create the new block's edges. An edit's connections REPLACE every + outgoing edge of that block, on every handle: list again each edge to keep. + To remove one edge, edit its source block with + {"removeEdges":[{"targetBlockId":"","sourceHandle":"source"}]} (sourceHandle defaults to + "source"). +Source handles: + source the normal path + error a failure (a block that has an error output) + if, else-if-0, else a condition's branches, in order (else-if-1, … for more) + route-0, route-1, … a router's routes, in order + loop-start-source a loop into its body; loop-end-source after the loop + parallel-start-source, parallel-end-source the same for a parallel +Renames: + An edit's {"name":"New name"} also rewrites every reference to the block, in + other blocks' inputs and in a loop's or parallel's collection and condition. +``` API request and response schemas: [applyWorkflowOperations](/api-reference/workflows/applyWorkflowOperations). @@ -776,7 +795,7 @@ sim workflows run [options] | `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | | `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | -| `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. | +| `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running. | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | | `--follow` | No | Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns. | | `--include-thinking` | No | Show model reasoning while following (requires --follow). | diff --git a/scripts/generate-cli-docs.test.ts b/scripts/generate-cli-docs.test.ts index 6e2b050e9b2..9a0e2ff1dee 100644 --- a/scripts/generate-cli-docs.test.ts +++ b/scripts/generate-cli-docs.test.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs' import path from 'node:path' import { describe, expect, it } from 'vitest' -import { describeOption, GUIDE_PAGES, OUTPUT_DIR } from './generate-cli-docs' +import { describeOption, GUIDE_PAGES, helpParagraph, OUTPUT_DIR } from './generate-cli-docs' /** `describeOption` reads only these two fields; the rest of the Option is irrelevant. */ function option(fields: { description?: string; defaultValue?: unknown }) { @@ -30,6 +30,18 @@ describe('an option default rendered into the reference table', () => { }) }) +describe('a command help paragraph rendered into its page', () => { + it('keeps a table laid out in columns as it reads in the terminal, and reflows prose', () => { + const table = + 'Source handles:\n source the normal path\n error a failure' + expect(helpParagraph(table)).toEqual(['```text', table, '```', '']) + expect(helpParagraph('Fails the check on\n W_REQUIRED_MISSING,\n W_VALUE_KIND.')).toEqual([ + 'Fails the check on W_REQUIRED_MISSING, W_VALUE_KIND.', + '', + ]) + }) +}) + /** * The id shapes the CLI states in its own root help (`HELP_EPILOGUE`, * `packages/sim-cli/src/program.ts`): workflow, knowledge-base, workspace and diff --git a/scripts/generate-cli-docs.ts b/scripts/generate-cli-docs.ts index e96b9ba94f5..072fd726fa9 100644 --- a/scripts/generate-cli-docs.ts +++ b/scripts/generate-cli-docs.ts @@ -887,6 +887,16 @@ function orderedCommands(entries: DocumentedCommand[]): DocumentedCommand[] { ) } +/** + * One paragraph of help text as Markdown: prose reflows into one line, and a paragraph laid out + * in columns (an indented line with a gap of two or more spaces inside it, as a table of handles + * is) keeps its layout in a fence. + */ +export function helpParagraph(paragraph: string): string[] { + if (/^ {2,}\S.*\S {2,}\S/m.test(paragraph)) return ['```text', paragraph.trimEnd(), '```', ''] + return [escapeProse(paragraph.replace(/\s*\n\s*/g, ' ').trim()), ''] +} + /** Reads command-specific help additions without emitting the root’s help epilogue. */ function additionalHelp(command: Command): string[] { const chunks: string[] = [] @@ -896,9 +906,7 @@ function additionalHelp(command: Command): string[] { const text = chunks.join('').trim() if (!text) return [] const [prose = '', examples] = text.split(/\nExamples:\s*\n/, 2) - const lines = prose - .split(/\n\s*\n/) - .flatMap((paragraph) => [escapeProse(paragraph.replace(/\s*\n\s*/g, ' ').trim()), '']) + const lines = prose.split(/\n\s*\n/).flatMap(helpParagraph) if (examples) { lines.push( '**Examples**', From 2d131687efcb0ef7e54592296bfa9a961284a5e1 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:34:26 -0800 Subject: [PATCH 55/85] docs(sim-cli): the workspace primer names exit 15, and --trigger says it takes a block id --- packages/sim-cli/src/commands/protocol/source-primer.ts | 2 ++ packages/sim-cli/src/commands/protocol/workflow-run-follow.ts | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 94a1302aa3f..51ecf4176a9 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -16,6 +16,7 @@ import { RATE_LIMITED_EXIT_CODE, SOURCE_BUSY_EXIT_CODE, SOURCE_DRIFT_EXIT_CODE, + SOURCE_HELD_EXIT_CODE, SOURCE_LOCAL_CHANGES_EXIT_CODE, SOURCE_STALE_EXIT_CODE, } from '../../exit-codes' @@ -73,6 +74,7 @@ This directory is a Sim workspace as files (\`tables/\`, \`workflows//workf - **Deletes**: a removed file (a resource this directory managed), table column, workflow block or workflow variable is deleted only with \`apply --allow-delete\` (else refused), and cannot be undone. A kind is managed only when its folder exists. - **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply, which prints its webhook URLs; without one, apply never deploys. - **Promote** (dev → prod): \`sim workspaces source apply --dir . --to --dry-run\`, then \`--yes\`. +- **Exit ${SOURCE_HELD_EXIT_CODE}**: written in part; changes using an unset secret or unbound credential were held back: set it, apply again. ${sharedRules('sim workspaces source', WORKSPACE_RENAMES)} ` 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 248964898ca..99f8c49313c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -592,7 +592,7 @@ export function attachWorkflowRunFollow(workflows: Command): void { .option('--manual', 'Run the current saved workflow state instead of the active deployment') .option( '--trigger ', - 'Enter the run through this runnable trigger; runs the current saved workflow state (implies --manual)' + 'Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual)' ) .option( '--mock-payload', From bc35fb0a48651a60ba5c02e6bcd3a375a6dc9e84 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:34:32 -0800 Subject: [PATCH 56/85] test(logs): drop the logging-session check that only restated a pass-through; execution-core covers the run input --- .../logs/execution/logging-session.test.ts | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/apps/sim/lib/logs/execution/logging-session.test.ts b/apps/sim/lib/logs/execution/logging-session.test.ts index da6ad0bfbdf..69c1211fb30 100644 --- a/apps/sim/lib/logs/execution/logging-session.test.ts +++ b/apps/sim/lib/logs/execution/logging-session.test.ts @@ -986,26 +986,6 @@ describe('LoggingSession completion retries', () => { ) }) - it('persists the run input of a failed or cancelled run', async () => { - completeWorkflowExecutionMock.mockResolvedValue({}) - const failed = new LoggingSession('workflow-1', 'execution-7', 'manual', 'req-1') - failed.setResolvedSecretTraceRegistry(createSecretRegistry([])) - await failed.safeCompleteWithError({ - error: { message: 'boom' }, - workflowInput: { company: 'Acme' }, - }) - expect(completeWorkflowExecutionMock).toHaveBeenLastCalledWith( - expect.objectContaining({ executionId: 'execution-7', workflowInput: { company: 'Acme' } }) - ) - - const cancelled = new LoggingSession('workflow-1', 'execution-8', 'manual', 'req-1') - cancelled.setResolvedSecretTraceRegistry(createSecretRegistry([])) - await cancelled.safeCompleteWithCancellation({ workflowInput: { company: 'Acme' } }) - expect(completeWorkflowExecutionMock).toHaveBeenLastCalledWith( - expect.objectContaining({ executionId: 'execution-8', workflowInput: { company: 'Acme' } }) - ) - }) - it('marks paused completions as completed and deduplicates later attempts', async () => { const session = new LoggingSession('workflow-1', 'execution-1', 'api', 'req-1') From e4b2ec58977157ac296a9810a0a5f95f07dc802d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:35:01 -0800 Subject: [PATCH 57/85] fix(tables): a bulk action on a table named twice, by id and by name, acts on it once --- apps/sim/lib/table/application/bulk.test.ts | 21 +++++++++++++++++++++ apps/sim/lib/table/application/bulk.ts | 6 +++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/table/application/bulk.test.ts b/apps/sim/lib/table/application/bulk.test.ts index a7f45f20497..e5db7ef3842 100644 --- a/apps/sim/lib/table/application/bulk.test.ts +++ b/apps/sim/lib/table/application/bulk.test.ts @@ -174,6 +174,27 @@ describe('table bulk application use cases', () => { expect(result.deleted).toEqual([{ kind: 'table', id: 'table-2', name: 'Archived' }]) }) + it('acts once on a table named twice, by its id and by its name', async () => { + mocks.resolveTableContext.mockImplementation(async (tableId: string) => + tableContext(tableId === 'Table table-2' ? 'table-2' : tableId) + ) + + const result = await bulkDeleteTables.execute({ + principal, + input: { + assertedWorkspaceId: 'workspace-1', + tableIds: ['table-2', 'Table table-2'], + folderKeying: 'ids' as const, + folders: [], + }, + }) + + expect(mocks.deleteTable).toHaveBeenCalledTimes(1) + expect(result.deleted).toEqual([{ kind: 'table', id: 'table-2', name: 'Archived' }]) + expect(result.notFound).toEqual([]) + expect(result.failed).toEqual([]) + }) + it('conceals an inaccessible table as not-found rather than naming it', async () => { mocks.resolveTableContext.mockRejectedValueOnce( new OrchestrationError('not_found', 'Table not found') diff --git a/apps/sim/lib/table/application/bulk.ts b/apps/sim/lib/table/application/bulk.ts index 9fd587b4732..b43ad1b151e 100644 --- a/apps/sim/lib/table/application/bulk.ts +++ b/apps/sim/lib/table/application/bulk.ts @@ -301,7 +301,8 @@ async function notifyBatchedTableChanges( * A table filed inside one of the selected folders is skipped: the folder * operation already carries it, and acting on it separately would either pull * it out of the folder it is travelling with or archive it under a second - * timestamp its folder's restore could never recover. + * timestamp its folder's restore could never recover. A table named twice (by + * its id and by its name, say) is acted on once. */ async function runTableItems( tableIds: readonly string[], @@ -313,10 +314,13 @@ async function runTableItems( succeeded: BulkTableItem[], outcome: BulkTablesOutcome ): Promise { + const seen = new Set() for (const tableId of tableIds) { let tableName = tableId try { const canonical = await resolveActiveTableInWorkspace(tableId, workspace) + if (seen.has(canonical.table.id)) continue + seen.add(canonical.table.id) tableName = canonical.table.name if (canonical.table.folderId && covered.has(canonical.table.folderId)) { outcome.skipped.push({ kind: 'table', id: canonical.table.id, name: tableName }) From 4e83741d8941ae233fa7b0b9960e581706c7032c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:35:35 -0800 Subject: [PATCH 58/85] docs(tables): a row cursor is sent back under the table reference the first page used --- apps/docs/content/docs/cli/reference.mdx | 2 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/openapi-v2-tables.json | 6 +++--- apps/sim/lib/api/contracts/v2/tables.ts | 6 ++++-- packages/sim-cli/src/generated/v2-api.ts | 8 ++++++-- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 865e712b92d..f47db12440f 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8460,7 +8460,7 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | -| `--trigger ` | No | Enter the run through this runnable trigger; runs the current saved workflow state (implies --manual). | +| `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 641fe2e9abe..1f69d9ef0d8 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -790,7 +790,7 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | -| `--trigger ` | No | Enter the run through this runnable trigger; runs the current saved workflow state (implies --manual). | +| `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | diff --git a/apps/docs/openapi-v2-tables.json b/apps/docs/openapi-v2-tables.json index 70cecfd5455..e07534290df 100644 --- a/apps/docs/openapi-v2-tables.json +++ b/apps/docs/openapi-v2-tables.json @@ -981,9 +981,9 @@ "name": "cursor", "in": "query", "required": false, - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "description": "Opaque cursor from the previous page. Send it back with the same sort, filters and table reference (its id or its name, as the first page used); only `limit` may change. Change anything else and pagination must restart without a cursor.", "schema": { - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "description": "Opaque cursor from the previous page. Send it back with the same sort, filters and table reference (its id or its name, as the first page used); only `limit` may change. Change anything else and pagination must restart without a cursor.", "type": "string", "minLength": 1 } @@ -7811,7 +7811,7 @@ "maximum": 1000 }, "cursor": { - "description": "Opaque cursor returned by the previous query page.", + "description": "Opaque cursor returned by the previous query page. Send it back under the same table reference (its id or its name, as the first page used).", "type": "string", "minLength": 1 }, diff --git a/apps/sim/lib/api/contracts/v2/tables.ts b/apps/sim/lib/api/contracts/v2/tables.ts index c4731bc0c14..00d945a085a 100644 --- a/apps/sim/lib/api/contracts/v2/tables.ts +++ b/apps/sim/lib/api/contracts/v2/tables.ts @@ -897,7 +897,7 @@ export const v2TableRowsQuerySchema = tableRowsQueryBaseSchema .min(1, 'cursor must be a non-empty token') .optional() .describe( - 'Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.' + 'Opaque cursor from the previous page. Send it back with the same sort, filters and table reference (its id or its name, as the first page used); only `limit` may change. Change anything else and pagination must restart without a cursor.' ), includeRunState: booleanQueryFlagSchema .optional() @@ -972,7 +972,9 @@ export const v2QueryRowsBodySchema = z .string() .min(1, 'cursor must be a non-empty token') .optional() - .describe('Opaque cursor returned by the previous query page.'), + .describe( + 'Opaque cursor returned by the previous query page. Send it back under the same table reference (its id or its name, as the first page used).' + ), includeRunState: z .boolean() .optional() diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 4d2f09399df..bfe963dcebb 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -27003,7 +27003,7 @@ export const V2_OPERATIONS = { cursor: { kind: 'string', describe: - 'Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.', + 'Opaque cursor from the previous page. Send it back with the same sort, filters and table reference (its id or its name, as the first page used); only `limit` may change. Change anything else and pagination must restart without a cursor.', }, includeRunState: { kind: 'boolean', @@ -28055,7 +28055,11 @@ export const V2_OPERATIONS = { describe: 'Maximum rows per page. `0` requests all matches, subject to a 5 MiB row-data ceiling; larger results return `400` with `TABLE_QUERY_RESULT_TOO_LARGE`. Use paged queries or an export for larger results.', }, - cursor: { kind: 'string', describe: 'Opaque cursor returned by the previous query page.' }, + cursor: { + kind: 'string', + describe: + 'Opaque cursor returned by the previous query page. Send it back under the same table reference (its id or its name, as the first page used).', + }, includeRunState: { kind: 'boolean', default: false, From fa1bf731e5414848b487d723c9694ae251bf85f2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:36:47 -0800 Subject: [PATCH 59/85] fix(workspace-source): staging renews the blobs a batch re-sent even when the quota refuses its new ones --- .../application/staging.integration.ts | 41 ++++++++++++++++++- .../sim/lib/workspace-source/staging/store.ts | 26 ++++++------ 2 files changed, 53 insertions(+), 14 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/staging.integration.ts b/apps/sim/lib/workspace-source/application/staging.integration.ts index e9df54dd9f2..5a7afbd1367 100644 --- a/apps/sim/lib/workspace-source/application/staging.integration.ts +++ b/apps/sim/lib/workspace-source/application/staging.integration.ts @@ -81,6 +81,9 @@ const payer = createSessionPrincipal({ userId: payerId, sessionId: generateId() /** A second payer of its own, whose stored bytes an apply changes. */ const applierId = generateId() const applier = createSessionPrincipal({ userId: applierId, sessionId: generateId() }) +/** A third payer of its own, near its quota. */ +const renewerId = generateId() +const renewer = createSessionPrincipal({ userId: renewerId, sessionId: generateId() }) const { check, writeReport } = sourceChecks( 'WORKSPACE_SOURCE_STAGING_REPORT_PATH', 'workspace-source-staging.json' @@ -171,7 +174,7 @@ beforeAll(async () => { ) const now = new Date() await db.insert(user).values( - [ownerId, writerId, readerId, payerId, applierId].map((id) => ({ + [ownerId, writerId, readerId, payerId, applierId, renewerId].map((id) => ({ id, name: 'Workspace source staging fixture', email: `${id}@workspace-source.invalid`, @@ -186,7 +189,9 @@ afterAll(async () => { await writeReport() resetUploadsSetupMock() await workspaces.cleanup() - await db.delete(user).where(inArray(user.id, [ownerId, writerId, readerId, payerId, applierId])) + await db + .delete(user) + .where(inArray(user.id, [ownerId, writerId, readerId, payerId, applierId, renewerId])) await rm(storageRoot, { recursive: true, force: true }) }) @@ -301,6 +306,38 @@ describe('workspace source staging', () => { } ) + check( + 'a batch whose new blobs the quota refuses still renews the staged blobs it re-sent', + async () => { + const quota = 1024 ** 3 + await db + .insert(userStats) + .values({ id: generateId(), userId: renewerId, storageUsedBytes: quota - 10 }) + const workspaceId = await workspaces.create({ name: 'Staging renewal', ownerId: renewerId }) + const kept = blob('five5') + vi.stubEnv('FREE_STORAGE_LIMIT_GB', '1') + try { + await stage(renewer, workspaceId, [kept]) + const soon = new Date(Date.now() + 30 * 60 * 1000) + await db + .update(workspaceSourceStagedBlob) + .set({ expiresAt: soon }) + .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) + + const refused = await failure(stage(renewer, workspaceId, [kept, blob('six b4')])) + expect(refused).toMatchObject({ name: 'SourceStagingFullError' }) + + const [row] = await db + .select({ expiresAt: workspaceSourceStagedBlob.expiresAt }) + .from(workspaceSourceStagedBlob) + .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) + expect(row.expiresAt.getTime()).toBeGreaterThan(Date.now() + 23 * 60 * 60 * 1000) + } finally { + vi.unstubAllEnvs() + } + } + ) + check( 'a quota that cannot be read refuses staging as unavailable, never as a full staging area', async () => { diff --git a/apps/sim/lib/workspace-source/staging/store.ts b/apps/sim/lib/workspace-source/staging/store.ts index 1e4e979f3a2..df96de0c5b6 100644 --- a/apps/sim/lib/workspace-source/staging/store.ts +++ b/apps/sim/lib/workspace-source/staging/store.ts @@ -230,6 +230,20 @@ export async function stageBlobs( fresh.length > 0 && isStorageEnforcementEnabled() ? await resolveStorageBillingContext(target.workspaceId) : null + // Renewing adds no bytes, so it needs no quota check and commits on its own: a batch whose new + // blobs are refused still keeps the ones it re-sent. + if (known.size > 0) { + await db + .update(workspaceSourceStagedBlob) + .set({ expiresAt: expiry(), consumedAt: null }) + .where( + and( + inScope(target), + inArray(workspaceSourceStagedBlob.sha256, [...known.keys()]), + gt(workspaceSourceStagedBlob.expiresAt, new Date()) + ) + ) + } try { for (const blob of fresh) { const key = newStorageKey(target, blob.sha256) @@ -250,18 +264,6 @@ export async function stageBlobs( 'workspace_source_staging', `workspace-source-staging:${target.workspaceId}:${target.scope}` ) - if (known.size > 0) { - await tx - .update(workspaceSourceStagedBlob) - .set({ expiresAt: expiry(), consumedAt: null }) - .where( - and( - inScope(target), - inArray(workspaceSourceStagedBlob.sha256, [...known.keys()]), - gt(workspaceSourceStagedBlob.expiresAt, new Date()) - ) - ) - } if (fresh.length === 0) return new Map() const adding = { count: fresh.length, From 938f3644920c50554e94714d8929339603ea320c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:37:10 -0800 Subject: [PATCH 60/85] fix(self-hosting): Compose starts realtime only after the migrations finish; the runbook note covers Helm alone --- apps/docs/content/docs/platform/self-hosting/upgrades.mdx | 2 +- docker-compose.local.yml | 2 ++ docker-compose.prod.yml | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx index 2602b27aa69..10c22694f2a 100644 --- a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx +++ b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx @@ -287,7 +287,7 @@ Migrations are Drizzle SQL files plus registered script (data) migrations, appli - **Docker Compose** — a one-shot `migrations` service with `restart: no` that runs before the app. - Only the app waits for migrations. The realtime service starts without them: on Helm its pods have no migrations init container, and on Compose `realtime` does not depend on the `migrations` service. A realtime pod of the new release that starts before its migrations finish fails the editor writes that read a new table or column, such as deleting a block or a variable, until they do. Run the migrations before new realtime pods start: run the migration image yourself before `helm upgrade` (see [Migration environment](#migration-environment)), or stop `realtime` until the `migrations` service has exited successfully. + On Kubernetes only the app waits for migrations: realtime pods have no migrations init container. A realtime pod of the new release that starts before its migrations finish fails the editor writes that read a new table or column, such as deleting a block or a variable, until they do. Run the migration image yourself before `helm upgrade` (see [Migration environment](#migration-environment)). On Docker Compose, `realtime` also waits for the `migrations` service to exit successfully. Migrations are **forward-only**. Take the backup described in the upgrade procedure before applying them; there are no down-migrations. diff --git a/docker-compose.local.yml b/docker-compose.local.yml index 40a1c1801ca..9f376c78b06 100644 --- a/docker-compose.local.yml +++ b/docker-compose.local.yml @@ -70,6 +70,8 @@ services: condition: service_healthy redis: condition: service_healthy + migrations: + condition: service_completed_successfully restart: unless-stopped ports: - '3002:3002' diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 6b9627efea2..c410a19b7da 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -98,6 +98,8 @@ services: condition: service_healthy redis: condition: service_healthy + migrations: + condition: service_completed_successfully healthcheck: test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:3002/health'] interval: 90s From cadce1e9f139ee3fa6ce55951c43670fe7e7c8d1 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:41:32 -0800 Subject: [PATCH 61/85] refactor(workflow-code): simplify the combined changes: one lane table, one annotation gate, sanitized run and URL text, and indexed consumed marking --- apps/sim/lib/workflows/api/source-slots.ts | 22 +++++----- .../sim/lib/workspace-source/staging/store.ts | 43 ++++++++++--------- .../src/commands/protocol/deployed-urls.ts | 3 +- .../commands/protocol/run-source-location.ts | 3 +- .../src/commands/protocol/source-status.ts | 2 +- .../src/commands/protocol/source-ui.ts | 27 +++++------- .../protocol/workspace-source-apply.ts | 7 +-- 7 files changed, 52 insertions(+), 55 deletions(-) diff --git a/apps/sim/lib/workflows/api/source-slots.ts b/apps/sim/lib/workflows/api/source-slots.ts index cc2338cce60..865b57c3023 100644 --- a/apps/sim/lib/workflows/api/source-slots.ts +++ b/apps/sim/lib/workflows/api/source-slots.ts @@ -11,16 +11,14 @@ import { v2Error } from '@/app/api/v2/lib/response' * plan inside one slot may run a few workflow reads at once (`kinds/table`), so the bound is per * request, not per workflow load. */ -const MAX_CONCURRENT_SOURCE_REQUESTS = { read: 4, editor: 4, plan: 4, apply: 4 } as const +const SOURCE_LANES = { + read: { max: 4, noun: 'gets' }, + editor: { max: 4, noun: 'Code tab reads' }, + plan: { max: 4, noun: 'plans' }, + apply: { max: 4, noun: 'applies' }, +} as const -type SourceLane = keyof typeof MAX_CONCURRENT_SOURCE_REQUESTS - -const LANE_NOUNS: Record = { - read: 'gets', - editor: 'Code tab reads', - plan: 'plans', - apply: 'applies', -} +type SourceLane = keyof typeof SOURCE_LANES const runningSourceRequests: Record = { read: 0, editor: 0, plan: 0, apply: 0 } @@ -31,7 +29,7 @@ const SOURCE_BUSY_HEADERS = { 'Retry-After': '5' } class SourceSlotBusyError extends Error { constructor(readonly lane: SourceLane) { super( - `This server is already running ${MAX_CONCURRENT_SOURCE_REQUESTS[lane]} source ${LANE_NOUNS[lane]}; retry shortly.` + `This server is already running ${SOURCE_LANES[lane].max} source ${SOURCE_LANES[lane].noun}; retry shortly.` ) this.name = 'SourceSlotBusyError' } @@ -41,7 +39,7 @@ class SourceSlotBusyError extends Error { * `useCase`, run in one of its lane's slots (`laneOf`, or the lane it picks for the input): a get, * plan or apply (each holds a workflow's or a directory's worth of text, stored state and * canonical forms in memory) waits for nothing, and is refused with a `429` (see - * {@link renderSourceSlotBusy}) when the process already runs {@link MAX_CONCURRENT_SOURCE_REQUESTS} + * {@link renderSourceSlotBusy}) when the process already runs {@link SOURCE_LANES} * of them, so a burst cannot run the process out of memory. */ export function withSourceSlot( @@ -52,7 +50,7 @@ export function withSourceSlot( ...useCase, async execute(args) { const lane = typeof laneOf === 'function' ? laneOf(args.input) : laneOf - if (runningSourceRequests[lane] >= MAX_CONCURRENT_SOURCE_REQUESTS[lane]) { + if (runningSourceRequests[lane] >= SOURCE_LANES[lane].max) { throw new SourceSlotBusyError(lane) } runningSourceRequests[lane] += 1 diff --git a/apps/sim/lib/workspace-source/staging/store.ts b/apps/sim/lib/workspace-source/staging/store.ts index df96de0c5b6..33e769d8469 100644 --- a/apps/sim/lib/workspace-source/staging/store.ts +++ b/apps/sim/lib/workspace-source/staging/store.ts @@ -146,8 +146,8 @@ async function payerStagedBytes(tx: DbTransaction, payer: BillingEntity): Promis /** * Refuses staging `bytes` more in `billing`'s workspace when the bytes its payer stores, plus those * staged in any of the payer's workspaces, plus these would pass the payer's storage quota. Holds the - * payer's staging lock until `tx` ends, so concurrent staging in another workspace of the same - * payer cannot pass the check together. A quota that could not be read is a `503`, never + * payer's staging lock until `tx` ends (through the insert that follows), so concurrent staging in + * another workspace of the same payer cannot pass the check together. A quota that could not be read is a `503`, never * {@link SourceStagingFullError}, which a client takes as permanent. */ async function assertStagingWithinQuota( @@ -225,25 +225,26 @@ export async function stageBlobs( const keys = new Map() const replaced: string[] = [] let recorded = new Map() - // The payer resolves before the transaction, so its locks are held only for the quota sums. - const billing = + // The payer resolves before the transaction, so the transaction reads no billing rows. Renewing + // adds no bytes, so it needs no quota check and commits on its own: a batch whose new blobs are + // refused still keeps the ones it re-sent. + const [billing] = await Promise.all([ fresh.length > 0 && isStorageEnforcementEnabled() - ? await resolveStorageBillingContext(target.workspaceId) - : null - // Renewing adds no bytes, so it needs no quota check and commits on its own: a batch whose new - // blobs are refused still keeps the ones it re-sent. - if (known.size > 0) { - await db - .update(workspaceSourceStagedBlob) - .set({ expiresAt: expiry(), consumedAt: null }) - .where( - and( - inScope(target), - inArray(workspaceSourceStagedBlob.sha256, [...known.keys()]), - gt(workspaceSourceStagedBlob.expiresAt, new Date()) - ) - ) - } + ? resolveStorageBillingContext(target.workspaceId) + : null, + known.size > 0 + ? db + .update(workspaceSourceStagedBlob) + .set({ expiresAt: expiry(), consumedAt: null }) + .where( + and( + inScope(target), + inArray(workspaceSourceStagedBlob.sha256, [...known.keys()]), + gt(workspaceSourceStagedBlob.expiresAt, new Date()) + ) + ) + : null, + ]) try { for (const blob of fresh) { const key = newStorageKey(target, blob.sha256) @@ -338,7 +339,7 @@ export async function markStagedBlobsConsumed( .where( and( inScope(target), - inArray(workspaceSourceStagedBlob.storageKey, [...new Set(blobs.map((b) => b.storageKey))]) + inArray(workspaceSourceStagedBlob.sha256, [...new Set(blobs.map((blob) => blob.sha256))]) ) ) } diff --git a/packages/sim-cli/src/commands/protocol/deployed-urls.ts b/packages/sim-cli/src/commands/protocol/deployed-urls.ts index e3b925dd3f0..0ad2087a284 100644 --- a/packages/sim-cli/src/commands/protocol/deployed-urls.ts +++ b/packages/sim-cli/src/commands/protocol/deployed-urls.ts @@ -5,6 +5,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { parseWorkflowLock } from '@sim/workflow-code' import { printError } from '#sim-cli/output/io' +import { sanitize } from '#sim-cli/output/render' import type { GetWorkflowDeploymentResponse } from '../../generated/v2-api' import type { OperationClient } from '../../runtime/called-operations' @@ -69,5 +70,5 @@ export async function deployedUrls( /** The URLs as one display line: `leadin (hook) https://…, …`. */ export function deployedUrlsText(urls: readonly DeployedUrl[]): string { - return urls.map(({ block, url }) => `${block} ${url}`).join(', ') + return urls.map(({ block, url }) => `${sanitize(block)} ${sanitize(url)}`).join(', ') } diff --git a/packages/sim-cli/src/commands/protocol/run-source-location.ts b/packages/sim-cli/src/commands/protocol/run-source-location.ts index 445e5460bd5..2863a8fd56b 100644 --- a/packages/sim-cli/src/commands/protocol/run-source-location.ts +++ b/packages/sim-cli/src/commands/protocol/run-source-location.ts @@ -10,6 +10,7 @@ import { parseWorkflowLock } from '@sim/workflow-code' import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' import { annotationLine, annotationPath, printAnnotations } from '#sim-cli/output/github-actions' import { printError } from '#sim-cli/output/io' +import { safeOneLine } from '#sim-cli/output/render' import { blockLabel } from './deployed-urls' import { readPreviousLock, readSourceJson, readSourceText } from './source-dir' @@ -101,7 +102,7 @@ export async function printRunFailureSite( } const where = `${site.file}${site.line === null ? '' : `:${site.line}`}` const declared = site.declaredAt ? `, declared at ${site.declaredAt}` : '' - const text = typeof message === 'string' ? message : 'The block failed.' + const text = typeof message === 'string' ? safeOneLine(message) : 'The block failed.' printError(`${where}: ${text} (block ${site.block}${declared})`) printAnnotations([ annotationLine('error', text, { diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index ba7b57ceabe..edc4bb0070c 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -152,7 +152,7 @@ export function printStatusReport( findings: readonly Diagnostic[] ): void { const shown = findingsOutput(format, false, report.dir) - if (format === 'json' || format === 'yaml') { + if (shown.machine) { printDocument(format, findings.length > 0 ? { ...report, ...shown.result(findings) } : report) return } diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index 98cd337785f..5aad954a0f7 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -8,12 +8,7 @@ import { boundFindingText, type RefusalClass } from '@sim/workflow-code/diagnost import { SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { type FlatDiagnostic, refusalClass } from '@sim/workspace-code' import type { Command } from 'commander' -import { - annotationLine, - annotationPath, - inGithubActions, - printAnnotations, -} from '#sim-cli/output/github-actions' +import { annotationLine, annotationPath, printAnnotations } from '#sim-cli/output/github-actions' import { printError } from '#sim-cli/output/io' import { askLine } from '#sim-cli/terminal/line-input' import type { OutputFormat } from '../../config/index' @@ -214,13 +209,15 @@ export interface FindingsOutput { */ function findingAnnotation(diagnostic: Diagnostic, dir: string | undefined): string[] { if (diagnostic.severity === 'info') return [] - const file = - diagnostic.file === undefined || diagnostic.path !== undefined - ? undefined - : dir === undefined - ? diagnostic.file - : annotationPath(dir, diagnostic.file) - const site = file === undefined ? {} : { file, line: diagnostic.line, column: diagnostic.column } + // A finding in a non-source file (`path`, a JSON path into it) has no line to point at. + const located = diagnostic.file !== undefined && diagnostic.path === undefined + const site = located + ? { + file: dir === undefined ? diagnostic.file : annotationPath(dir, diagnostic.file), + line: diagnostic.line, + column: diagnostic.column, + } + : {} const message = diagnostic.hint ? `${diagnostic.message} Hint: ${diagnostic.hint}` : diagnostic.message @@ -258,9 +255,7 @@ export function findingsOutput( ) .map((diagnostic) => boundFindingText(diagnostic)) if (!machine) printDiagnostics(unseen) - if (inGithubActions()) { - printAnnotations(unseen.flatMap((diagnostic) => findingAnnotation(diagnostic, dir))) - } + printAnnotations(unseen.flatMap((diagnostic) => findingAnnotation(diagnostic, dir))) }, result: (diagnostics) => resultDiagnostics( diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 794e0e50940..c31c0915aa8 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -939,6 +939,9 @@ function cell(text: string): string { */ function planMarkdown(data: ApplyData, workspaceId: string): string { const summary = summarize(data) + const [created, updated, deleted] = data.dryRun + ? ['to create', 'to update', 'to delete'] + : ['created', 'updated', 'deleted'] const changes = data.plan.filter((change) => change.action !== 'noop') const rows = changes.slice(0, SUMMARY_ROWS).map((change) => { const fields = change.fields?.length ? ` (${cell(change.fields.join(', '))})` : '' @@ -949,9 +952,7 @@ function planMarkdown(data: ApplyData, workspaceId: string): string { const lines = [ `### Sim workspace ${data.dryRun ? 'plan' : 'apply'}: ${cell(workspaceId)}`, '', - data.dryRun - ? `${summary.created.length} to create, ${summary.updated} to update, ${summary.deleted} to delete, ${summary.unchanged} unchanged; ${summary.errors} error(s), ${summary.warnings} warning(s).` - : `${summary.created.length} created, ${summary.updated} updated, ${summary.deleted} deleted, ${summary.unchanged} unchanged; ${summary.errors} error(s), ${summary.warnings} warning(s).`, + `${summary.created.length} ${created}, ${summary.updated} ${updated}, ${summary.deleted} ${deleted}, ${summary.unchanged} unchanged; ${summary.errors} error(s), ${summary.warnings} warning(s).`, ...(rows.length > 0 ? [ '', From 7da1bfad4f2197914f06cce60e286b5634414b87 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:45:20 -0800 Subject: [PATCH 62/85] chore: cleanup pass on the combined changes: tests assert outcomes, not mocks, and one redundant comment goes --- apps/sim/lib/catalog/application/reads.test.ts | 8 +------- apps/sim/lib/table/application/exports.test.ts | 3 --- .../application/kinds/table/renames.ts | 2 -- scripts/generate-cli-docs.test.ts | 16 ++++++++-------- scripts/generate-cli-docs.ts | 2 +- 5 files changed, 10 insertions(+), 21 deletions(-) diff --git a/apps/sim/lib/catalog/application/reads.test.ts b/apps/sim/lib/catalog/application/reads.test.ts index 66b5a3b7903..2bfa8751178 100644 --- a/apps/sim/lib/catalog/application/reads.test.ts +++ b/apps/sim/lib/catalog/application/reads.test.ts @@ -370,13 +370,7 @@ describe('catalog block and tool reads', () => { expect(detail.id).toBe('starter') expect(detail.description).toBe('Legacy — replaced by start_trigger. Start the workflow.') - // A superseded version hidden from the toolbar with no sunset stays as unknown as before. - await expect( - getCatalogBlock.execute({ - principal: session, - input: { workspaceId: WORKSPACE_ID, blockId: 'confluence' }, - }) - ).resolves.toMatchObject({ block: { id: 'confluence_v2' } }) + // With no newer version, a toolbar-hidden block with no sunset stays unknown. mocks.getLatestBlockForViewer.mockReturnValue(undefined) await expect( getCatalogBlock.execute({ diff --git a/apps/sim/lib/table/application/exports.test.ts b/apps/sim/lib/table/application/exports.test.ts index 812cd14b3ec..90221a5d3ad 100644 --- a/apps/sim/lib/table/application/exports.test.ts +++ b/apps/sim/lib/table/application/exports.test.ts @@ -135,9 +135,6 @@ describe('table export application use cases', () => { }) it('cancels an export under its table named by its name, and conceals one under another table', async () => { - mocks.getTable.mockImplementation(async (id: string) => - id === table.id ? table : { ...table, id, name: `Table ${id}` } - ) const cancel = (tableId: string) => cancelTableExportUseCase.execute({ principal: { kind: 'session' as const, userId: 'user-1' }, diff --git a/apps/sim/lib/workspace-source/application/kinds/table/renames.ts b/apps/sim/lib/workspace-source/application/kinds/table/renames.ts index 1b68a60b0d0..1e51c9835e1 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/renames.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/renames.ts @@ -127,8 +127,6 @@ export async function checkColumnRenamesInUse( .filter((workflow) => !deleted.has(workflow.id)) .map((workflow) => ({ table, columns, workflow })) }) - // Each check loads a workflow's draft, source or live version: independent reads, run a few at - // once, their findings kept in check order. const found = await mapWithConcurrency(checks, READ_CONCURRENCY, async (check) => { const { table, columns, workflow } = check const findings: WorkspaceSourceDiagnostic[] = [] diff --git a/scripts/generate-cli-docs.test.ts b/scripts/generate-cli-docs.test.ts index 9a0e2ff1dee..d1e0fa89506 100644 --- a/scripts/generate-cli-docs.test.ts +++ b/scripts/generate-cli-docs.test.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs' import path from 'node:path' import { describe, expect, it } from 'vitest' -import { describeOption, GUIDE_PAGES, helpParagraph, OUTPUT_DIR } from './generate-cli-docs' +import { describeOption, GUIDE_PAGES, OUTPUT_DIR } from './generate-cli-docs' /** `describeOption` reads only these two fields; the rest of the Option is irrelevant. */ function option(fields: { description?: string; defaultValue?: unknown }) { @@ -32,13 +32,13 @@ describe('an option default rendered into the reference table', () => { describe('a command help paragraph rendered into its page', () => { it('keeps a table laid out in columns as it reads in the terminal, and reflows prose', () => { - const table = - 'Source handles:\n source the normal path\n error a failure' - expect(helpParagraph(table)).toEqual(['```text', table, '```', '']) - expect(helpParagraph('Fails the check on\n W_REQUIRED_MISSING,\n W_VALUE_KIND.')).toEqual([ - 'Fails the check on W_REQUIRED_MISSING, W_VALUE_KIND.', - '', - ]) + const page = guide('workflows') + expect(page).toMatch( + /```text\n[\s\S]*?Source handles:\n {2}source {15}the normal path\n[\s\S]*?```/ + ) + expect(page).toContain( + 'These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind' + ) }) }) diff --git a/scripts/generate-cli-docs.ts b/scripts/generate-cli-docs.ts index 072fd726fa9..6c83eaefafd 100644 --- a/scripts/generate-cli-docs.ts +++ b/scripts/generate-cli-docs.ts @@ -892,7 +892,7 @@ function orderedCommands(entries: DocumentedCommand[]): DocumentedCommand[] { * in columns (an indented line with a gap of two or more spaces inside it, as a table of handles * is) keeps its layout in a fence. */ -export function helpParagraph(paragraph: string): string[] { +function helpParagraph(paragraph: string): string[] { if (/^ {2,}\S.*\S {2,}\S/m.test(paragraph)) return ['```text', paragraph.trimEnd(), '```', ''] return [escapeProse(paragraph.replace(/\s*\n\s*/g, ' ').trim()), ''] } From 805e17a9582d32f9ae8ddec38d0e3c30b376f5d2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:46:09 -0800 Subject: [PATCH 63/85] fix(sim-cli): keep the annotation file narrowed, and type the status refusal test --- .../sim-cli/src/commands/protocol/source-ui.ts | 17 +++++++++-------- .../protocol/workspace-source-status.test.ts | 2 +- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index 5aad954a0f7..bdfc04686ee 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -210,14 +210,15 @@ export interface FindingsOutput { function findingAnnotation(diagnostic: Diagnostic, dir: string | undefined): string[] { if (diagnostic.severity === 'info') return [] // A finding in a non-source file (`path`, a JSON path into it) has no line to point at. - const located = diagnostic.file !== undefined && diagnostic.path === undefined - const site = located - ? { - file: dir === undefined ? diagnostic.file : annotationPath(dir, diagnostic.file), - line: diagnostic.line, - column: diagnostic.column, - } - : {} + const { file } = diagnostic + const site = + file !== undefined && diagnostic.path === undefined + ? { + file: dir === undefined ? file : annotationPath(dir, file), + line: diagnostic.line, + column: diagnostic.column, + } + : {} const message = diagnostic.hint ? `${diagnostic.message} Hint: ${diagnostic.hint}` : diagnostic.message 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 40f54e4d4f7..9072e2d6f69 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 @@ -599,7 +599,7 @@ describe('workspaces source status', () => { const report = printed() expect(report.plan).toMatchObject({ delete: 1, errors: 1 }) - expect(report.diagnostics?.map((finding) => finding.code)).toEqual(['E_PLAN_REF_DELETED']) + expect(report.diagnostics).toEqual([expect.objectContaining({ code: 'E_PLAN_REF_DELETED' })]) }) it('keeps lint findings on a workflow edited here, which an apply sends whole', async () => { From 66cb3e3184f8eae8e9e5e7d4966aa8a77eb43a7b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 04:50:56 -0800 Subject: [PATCH 64/85] test(api): the table concealment policies answer the shared table not-found message --- .../sim/lib/api/server/routes/resource-concealment.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/api/server/routes/resource-concealment.test.ts b/apps/sim/lib/api/server/routes/resource-concealment.test.ts index 466da272902..d05ae29ea77 100644 --- a/apps/sim/lib/api/server/routes/resource-concealment.test.ts +++ b/apps/sim/lib/api/server/routes/resource-concealment.test.ts @@ -19,6 +19,7 @@ import { v2KnowledgeErrorPolicies, } from '@/lib/knowledge/api/route-policies' import { internalTableErrorPolicies, v2TableErrorPolicies } from '@/lib/table/api/route-policies' +import { TABLE_NOT_FOUND_MESSAGE } from '@/lib/table/constants' import { createInternalWorkflowErrorPolicy, internalWorkflowErrorPolicies, @@ -50,7 +51,7 @@ const policies: Array<{ { domain: 'table', policy: v2TableErrorPolicies.concealTableAuthorization, - notFoundMessage: 'Table not found', + notFoundMessage: TABLE_NOT_FOUND_MESSAGE, }, { domain: 'table import', @@ -217,12 +218,12 @@ const internalPolicies: Array<{ { route: 'POST /api/table/imports, POST /api/table/[tableId]/exports', policy: internalTableErrorPolicies.concealTableAuthorization, - notFoundMessage: 'Table not found', + notFoundMessage: TABLE_NOT_FOUND_MESSAGE, }, { route: 'POST/PATCH/DELETE /api/table/[tableId]/groups', policy: internalTableErrorPolicies.concealTableGroupAuthorization, - notFoundMessage: 'Table not found', + notFoundMessage: TABLE_NOT_FOUND_MESSAGE, }, { route: 'GET/DELETE /api/table/imports/[importId]', From 0c498a2ed72dda5a86f1bf75c8e61927a254666f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 05:05:59 -0800 Subject: [PATCH 65/85] chore(sim-cli): keep the GitHub Actions check private to its module --- packages/sim-cli/src/output/github-actions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sim-cli/src/output/github-actions.ts b/packages/sim-cli/src/output/github-actions.ts index 6cb1cd279cf..117f6cd0e6c 100644 --- a/packages/sim-cli/src/output/github-actions.ts +++ b/packages/sim-cli/src/output/github-actions.ts @@ -14,7 +14,7 @@ import { isEnabled } from '../environment' import { printError } from './io' /** Whether this process runs as a GitHub Actions step (never inside an embedded host). */ -export function inGithubActions(env: NodeJS.ProcessEnv = process.env): boolean { +function inGithubActions(env: NodeJS.ProcessEnv = process.env): boolean { return isEnabled(env.GITHUB_ACTIONS) && !embedStore.getStore() } From 21e0fbe967d5acc551835338e5ae2dc0f5ae2653 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 05:20:51 -0800 Subject: [PATCH 66/85] test(tables): build the export test's principal with the typed factory --- apps/sim/lib/table/application/exports.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/table/application/exports.test.ts b/apps/sim/lib/table/application/exports.test.ts index 90221a5d3ad..0f638eebd46 100644 --- a/apps/sim/lib/table/application/exports.test.ts +++ b/apps/sim/lib/table/application/exports.test.ts @@ -1,5 +1,8 @@ import { permissionGroupScopeMock, permissionGroupScopeMockFns } from '@sim/testing' -import { createExecutorPrincipal } from '@sim/testing/factories/principal.factory' +import { + createExecutorPrincipal, + createSessionPrincipal, +} from '@sim/testing/factories/principal.factory' import { auditMock } from '@sim/testing/mocks/audit.mock' import { storageServiceMock } from '@sim/testing/mocks/storage-service.mock' import { tableMock, tableMockFns } from '@sim/testing/mocks/table.mock' @@ -137,7 +140,7 @@ describe('table export application use cases', () => { it('cancels an export under its table named by its name, and conceals one under another table', async () => { const cancel = (tableId: string) => cancelTableExportUseCase.execute({ - principal: { kind: 'session' as const, userId: 'user-1' }, + principal: createSessionPrincipal({ userId: 'user-1' }), input: { exportId: 'export-1', workspaceId: 'workspace-1', tableId }, }) From ab89ebef06ea32d499ea823178c5fe69ffce2db0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 05:36:46 -0800 Subject: [PATCH 67/85] docs: record the CLI pages' changed code examples (the CI recipe and the operations guide's handle table) in the compatibility baseline --- .../scripts/fixtures/content-baseline.json | 74 +++++++++++-------- 1 file changed, 44 insertions(+), 30 deletions(-) diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index a20177e791f..aa47ad5c2c0 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -12053,84 +12053,84 @@ "meta": null, "sha256": "48441bc81c5893bfd1567acf2a401eb191e4b7bef2862b8c29aa158a517adb82", "bytes": 93, - "line": 3987 + "line": 3988 }, { "lang": "bash", "meta": null, "sha256": "74d9b766eac6b565c6287e10884f95c2f74ecd8dd4947b488cda0ff1c1f16597", "bytes": 80, - "line": 4019 + "line": 4020 }, { "lang": "bash", "meta": null, "sha256": "4b74edf3d708c0fafd7bb8ba6a827644f65d6cd755a4cf1822b5308a45eb76c3", "bytes": 106, - "line": 4053 + "line": 4054 }, { "lang": "bash", "meta": null, "sha256": "229448ff3c47ffdfdd720fb88b38edcf58f51d063f7b7836d4f4fdc478f99b5c", "bytes": 69, - "line": 4597 + "line": 4088 }, { "lang": "bash", "meta": null, "sha256": "7863a0cbd4e2cb3715358cca55047765a210f9a42a3dd171e42f574185fe0ab9", "bytes": 73, - "line": 4629 + "line": 4120 }, { "lang": "bash", "meta": null, "sha256": "412f8bcf9151f7075294ba9e7cfcbb86581e91dbd1b217775e9fb6958df71a2e", "bytes": 72, - "line": 4152 + "line": 4153 }, { "lang": "bash", "meta": null, "sha256": "483447579062e117424ae72463645f166fea91b8a87fe6efcf48a24a3a8145f8", "bytes": 49, - "line": 4187 + "line": 4188 }, { "lang": "bash", "meta": null, "sha256": "e57bccfdde20412a95b0aeb601448b791eb566d28af3b17bbc16d1e62bbcfb4c", "bytes": 60, - "line": 4215 + "line": 4216 }, { "lang": "bash", "meta": null, "sha256": "34378bac1290005ec4e6a46fc968c097307dc2dd27dffd2ed275b885dcc8502b", "bytes": 57, - "line": 4246 + "line": 4247 }, { "lang": "bash", "meta": null, "sha256": "91c6910aa33b8d3c65dccd59a480a9d986eadf89d8d4974ade0c8cb47c7ac821", "bytes": 47, - "line": 4276 + "line": 4277 }, { "lang": "bash", "meta": null, "sha256": "303d009467865566416478bccdf9e95291862e222144f55ca61bae5d446fa9d5", "bytes": 50, - "line": 4300 + "line": 4301 }, { "lang": "bash", "meta": null, "sha256": "7deac995bc8ac114dae3500bb4792b73fdb39f5b666f4a2886428320e1ffbd00", "bytes": 60, - "line": 4324 + "line": 4325 }, { "lang": "bash", @@ -12965,6 +12965,13 @@ "bytes": null, "line": null }, + { + "lang": "text", + "meta": null, + "sha256": "48dd143dafc65a4f4c1cd5bfa0edc1ece98bec432d3e8d35b561c73cd3e3bfc2", + "bytes": 1109, + "line": 7754 + }, { "lang": "bash", "meta": null, @@ -13551,14 +13558,14 @@ "meta": null, "sha256": "1dbcb58a66005a55dccd94c633f3be04c7b462980746ce0bdfc7275bf728f009", "bytes": 35, - "line": 9507 + "line": 9963 }, { "lang": "bash", "meta": null, "sha256": "384da7ccbd87c00eba8c8301b7904ac71161b4faa0f51c208e833ddb1eba9a3c", "bytes": 37, - "line": 9531 + "line": 9989 }, { "lang": "bash", @@ -14237,98 +14244,98 @@ "meta": null, "sha256": "a19ec054796bc74549f7dbe83949c9eb6c5ae1f54cda5b5c9f8a7e1db5f99d80", "bytes": 349, - "line": 117 + "line": 113 }, { "lang": "bash", "meta": null, "sha256": "068b9eadd1fcffae232855024fdb4ff017b0f010ced2273c53f3b3fd2e898de2", "bytes": 236, - "line": 140 + "line": 226 }, { "lang": "bash", "meta": null, "sha256": "21d6503ee5e2f4362d6d086a74d41704bded199dd6f1a7a2f5760d4c06a78dab", "bytes": 260, - "line": 152 + "line": 238 }, { "lang": "bash", "meta": null, "sha256": "774f1a6b1c5e4ad85fa5551fba8a5faed7d82b3bb25e7d46336fb0b65e1e9522", "bytes": 220, - "line": 171 + "line": 257 }, { "lang": "bash", "meta": null, "sha256": "736d071516b05af975232c48c7e23065fc0334fc07c541ada21a806ea43f84e7", "bytes": 109, - "line": 184 + "line": 270 }, { "lang": "bash", "meta": null, "sha256": "019796d6002868ad852ec9b9bba75bff42f7f8f6eb2073dfb897aa359065721a", "bytes": 159, - "line": 190 + "line": 276 }, { "lang": "bash", "meta": null, "sha256": "3a91f6de422f9407871de6fa5bac996f2337001079def7f966bd0068086d7c63", "bytes": 199, - "line": 199 + "line": 285 }, { "lang": "bash", "meta": null, "sha256": "cdbd2c99596ad694d9ebd9eca43740e8c7371fabba9eca7cc580c16ae96bc800", "bytes": 166, - "line": 216 + "line": 302 }, { "lang": "bash", "meta": null, "sha256": "3edb250258fdf417424a8f185dd601a1a6374ce8b93dd553276cfef39875f959", "bytes": 323, - "line": 231 + "line": 317 }, { "lang": "bash", "meta": null, "sha256": "1d949072a36a628c98e3d17961acc9c59f07edcc89f63413f212adc3baec879e", "bytes": 290, - "line": 240 + "line": 326 }, { "lang": "bash", "meta": null, "sha256": "4cc080decc18686ffbbfe9c5c51c621d23d2b8de9f189ed8145973189681900b", "bytes": 219, - "line": 250 + "line": 336 }, { "lang": "bash", "meta": null, "sha256": "ab8b2eb4638d04f81b66e3eba3d9acfe49e6ae2531094ed48d0d3468537c188b", "bytes": 160, - "line": 257 + "line": 343 }, { "lang": "bash", "meta": "title=\"nightly-digest.sh\"", "sha256": "25d588b87d9f49723f0b1e41edadedfb33ec1eb28460b9b8574d2dfef87a7870", "bytes": 747, - "line": 266 + "line": 352 }, { "lang": "yaml", "meta": "title=\".github/workflows/sim-workspace.yml\"", - "sha256": "462cd2b7cd6f95ad467b9f7b19d644296b5efb5686fafb3231da4f5fd23885ed", - "bytes": null, - "line": null + "sha256": "9e7ef199fcc3626b482f4377b15d500c8cf417675cdf19fbdcf9188cce424963", + "bytes": 1136, + "line": 382 }, { "lang": "bash", @@ -17495,6 +17502,13 @@ "bytes": null, "line": null }, + { + "lang": "text", + "meta": null, + "sha256": "48dd143dafc65a4f4c1cd5bfa0edc1ece98bec432d3e8d35b561c73cd3e3bfc2", + "bytes": null, + "line": null + }, { "lang": "bash", "meta": null, From 869406bd86b6a18170aae2a112759543e0e10def Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:00:56 -0800 Subject: [PATCH 68/85] fix(workspace-source): staging a consumed blob again is checked against the payer's quota before it counts again --- .../application/staging.integration.ts | 35 ++++++++++--- .../sim/lib/workspace-source/staging/store.ts | 51 ++++++++++++++----- 2 files changed, 66 insertions(+), 20 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/staging.integration.ts b/apps/sim/lib/workspace-source/application/staging.integration.ts index 5a7afbd1367..ab764a03700 100644 --- a/apps/sim/lib/workspace-source/application/staging.integration.ts +++ b/apps/sim/lib/workspace-source/application/staging.integration.ts @@ -271,7 +271,7 @@ describe('workspace source staging', () => { ) check( - 'a blob an apply wrote stops counting toward the quota, since the workspace now stores it; staging it again counts it again', + 'a blob an apply wrote stops counting toward the quota, since the workspace now stores it; staging it again counts it again, refused when the quota has no room', async () => { const quota = 1024 ** 3 await db @@ -293,13 +293,36 @@ describe('workspace source staging', () => { expect(usage.storageUsedBytes).toBe(quota - 20 + notes.byteLength) // Stored 8 short of the quota: 6 more fit, unless the 12 applied bytes count twice. - await stage(applier, workspaceId, [blob('six b3')]) + const six = blob('six b3') + await stage(applier, workspaceId, [six]) - await stage(applier, workspaceId, [ - { sha256: sha256Hex(notes), size: notes.byteLength, content: notes }, - ]) - const refused = await failure(stage(applier, workspaceId, [blob('1')])) + const restaged = { sha256: sha256Hex(notes), size: notes.byteLength, content: notes } + const refused = await failure(stage(applier, workspaceId, [restaged])) expect(refused).toMatchObject({ name: 'SourceStagingFullError' }) + const consumedNotes = await db + .select({ consumedAt: workspaceSourceStagedBlob.consumedAt }) + .from(workspaceSourceStagedBlob) + .where( + and( + eq(workspaceSourceStagedBlob.workspaceId, workspaceId), + eq(workspaceSourceStagedBlob.sha256, restaged.sha256) + ) + ) + expect(consumedNotes).toEqual([{ consumedAt: expect.any(Date) }]) + + // Renewing a blob that still counts adds nothing, so it fits with 2 bytes left. + expect((await stage(applier, workspaceId, [six])).staged).toEqual([ + { sha256: six.sha256, size: six.size }, + ]) + // Room left for exactly the notes: staging them again takes it, so 1 byte more is refused. + await db + .update(userStats) + .set({ storageUsedBytes: quota - six.size - restaged.size }) + .where(eq(userStats.userId, applierId)) + await stage(applier, workspaceId, [restaged]) + expect(await failure(stage(applier, workspaceId, [blob('1')]))).toMatchObject({ + name: 'SourceStagingFullError', + }) } finally { vi.unstubAllEnvs() } diff --git a/apps/sim/lib/workspace-source/staging/store.ts b/apps/sim/lib/workspace-source/staging/store.ts index 33e769d8469..d321ae86197 100644 --- a/apps/sim/lib/workspace-source/staging/store.ts +++ b/apps/sim/lib/workspace-source/staging/store.ts @@ -79,21 +79,22 @@ const inScope = ({ workspaceId, scope }: StagingScope) => ) /** - * The staged blobs among `hashes` that are still staged `until` (default now), by hash, with when - * each expires. A read: it never extends an expiry. + * The staged blobs among `hashes` that are still staged `until` (default now), by hash, each + * marked `consumed` once an apply wrote it. A read: it never extends an expiry. */ export async function findStagedBlobs( target: StagingScope, hashes: readonly string[], until: Date = new Date() -): Promise> { - const found = new Map() +): Promise> { + const found = new Map() if (hashes.length === 0) return found const rows = await db .select({ sha256: workspaceSourceStagedBlob.sha256, size: workspaceSourceStagedBlob.size, storageKey: workspaceSourceStagedBlob.storageKey, + consumed: sql`${workspaceSourceStagedBlob.consumedAt} is not null`, }) .from(workspaceSourceStagedBlob) .where( @@ -213,7 +214,8 @@ export function assertStagingFits( * Stages `blobs` (bytes the caller already hashed): writes each one not yet staged to storage, * then records them under one lock on the scope, refusing a batch that would pass the caps or the * payer's storage quota (and removing the objects it wrote). A blob already staged is not written - * again: sending its bytes renews it, and counts it toward the quota again if an apply consumed it. + * again: sending its bytes renews it, and counts it toward the quota again (refused like a new + * blob when the quota has no room) if an apply consumed it. */ export async function stageBlobs( target: StagingScope, @@ -222,25 +224,30 @@ export async function stageBlobs( const unique = new Map(blobs.map((blob) => [blob.sha256, blob])) const known = await findStagedBlobs(target, [...unique.keys()]) const fresh = [...unique.values()].filter((blob) => !known.has(blob.sha256)) + const held = [...known.values()] + const renewing = held.filter((blob) => !blob.consumed).map((blob) => blob.sha256) + const reclaiming = held.filter((blob) => blob.consumed).map((blob) => blob.sha256) + const charged = fresh.length > 0 || reclaiming.length > 0 const keys = new Map() const replaced: string[] = [] let recorded = new Map() // The payer resolves before the transaction, so the transaction reads no billing rows. Renewing - // adds no bytes, so it needs no quota check and commits on its own: a batch whose new blobs are - // refused still keeps the ones it re-sent. + // a blob that still counts adds no bytes, so it needs no quota check and commits on its own: a + // batch whose other blobs are refused still keeps the ones it re-sent. const [billing] = await Promise.all([ - fresh.length > 0 && isStorageEnforcementEnabled() + charged && isStorageEnforcementEnabled() ? resolveStorageBillingContext(target.workspaceId) : null, - known.size > 0 + renewing.length > 0 ? db .update(workspaceSourceStagedBlob) - .set({ expiresAt: expiry(), consumedAt: null }) + .set({ expiresAt: expiry() }) .where( and( inScope(target), - inArray(workspaceSourceStagedBlob.sha256, [...known.keys()]), - gt(workspaceSourceStagedBlob.expiresAt, new Date()) + inArray(workspaceSourceStagedBlob.sha256, renewing), + gt(workspaceSourceStagedBlob.expiresAt, new Date()), + isNull(workspaceSourceStagedBlob.consumedAt) ) ) : null, @@ -265,13 +272,29 @@ export async function stageBlobs( 'workspace_source_staging', `workspace-source-staging:${target.workspaceId}:${target.scope}` ) - if (fresh.length === 0) return new Map() + if (!charged) return new Map() + // A consumed blob staged again counts toward the quota again: it is restored here, so the + // quota check below reads its bytes among the payer's staged ones (its row already counts + // toward the caps), and a refusal leaves it consumed. + if (reclaiming.length > 0) { + await tx + .update(workspaceSourceStagedBlob) + .set({ expiresAt: expiry(), consumedAt: null }) + .where( + and( + inScope(target), + inArray(workspaceSourceStagedBlob.sha256, reclaiming), + gt(workspaceSourceStagedBlob.expiresAt, new Date()) + ) + ) + } const adding = { count: fresh.length, bytes: fresh.reduce((sum, blob) => sum + blob.bytes.byteLength, 0), } - assertStagingFits(await stagedUsage(target, tx), adding) + if (fresh.length > 0) assertStagingFits(await stagedUsage(target, tx), adding) if (billing) await assertStagingWithinQuota(tx, billing, adding.bytes) + if (fresh.length === 0) return new Map() const hashes = fresh.map((blob) => blob.sha256) // An expired row of the same hash is replaced, so the unique index admits the new one. const expired = await tx From 745995e72f676829c763ee69546e0cd94d5309eb Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:03:22 -0800 Subject: [PATCH 69/85] fix(table): a managed rows write is checked against the row limit only under the lock, so an over-limit table can still be edited or shrunk --- apps/sim/lib/table/application/reshape.ts | 24 +++++++------ .../application/rows.integration.ts | 35 +++++++++++++++++++ 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/apps/sim/lib/table/application/reshape.ts b/apps/sim/lib/table/application/reshape.ts index e8a214bd736..00cfe913e33 100644 --- a/apps/sim/lib/table/application/reshape.ts +++ b/apps/sim/lib/table/application/reshape.ts @@ -25,7 +25,7 @@ import { tableFieldAudits, writeTableFields, } from '@/lib/table/application/tables' -import { assertRowCapacity, notifyTableRowUsage } from '@/lib/table/billing' +import { assertRowCapacity, getMaxRowsPerTable, notifyTableRowUsage } from '@/lib/table/billing' import { buildIdByName, columnMatchesRef, @@ -271,16 +271,18 @@ export const reshapeTableUseCase = defineAuthorizedTableUseCase({ workspaceBillingOwnerUserId: context.billedAccountUserId, }) const requestId = generateRequestId() - // Checked before the transaction opens (it reads the billing pool), for the rows the table - // holds once they are written; a managed write, which keeps stored rows with no key value, - // checks again under the lock once it has read them. - const rowLimit = input.rows - ? await assertRowCapacity({ - workspaceId, - currentRowCount: input.rows.mode === 'seed' ? context.table.rowCount : 0, - addedRows: input.rows.rows.length, - }) - : null + // Read before the transaction opens (it reads the billing pool). Seed rows only add, so they + // are checked here; a managed write is checked under the lock once it has read the stored rows, + // so one that adds no rows on balance passes even on a table already over its limit. + const rowLimit = !input.rows + ? null + : input.rows.mode === 'seed' + ? await assertRowCapacity({ + workspaceId, + currentRowCount: context.table.rowCount, + addedRows: input.rows.rows.length, + }) + : await getMaxRowsPerTable(workspaceId) const actor = { userId: attributedUserId, capabilityGovernedUserId: capabilityGovernedPrincipalUserId(principal), diff --git a/apps/sim/lib/workspace-source/application/rows.integration.ts b/apps/sim/lib/workspace-source/application/rows.integration.ts index d2acd6eab6f..85f6e449e87 100644 --- a/apps/sim/lib/workspace-source/application/rows.integration.ts +++ b/apps/sim/lib/workspace-source/application/rows.integration.ts @@ -1208,6 +1208,41 @@ export default defineTable({ } ) + check( + 'edits and shrinks a managed table whose declared rows alone already pass its row limit, as after a plan downgrade', + async () => { + const workspaceId = await newWorkspace() + const three = `${ROWS}{"code":"ent","seats":50,"tier":"pro"}\n` + const created = await apply(workspaceId, { + 'tables/plans.ts': MANAGED, + 'tables/plans.rows.jsonl': three, + }) + expect(created.failed).toBeUndefined() + planRowLimit.value = 1 + try { + const read = await runner.get(workspaceId) + const twelve = three.replace('"seats":10', '"seats":12') + const edited = await apply( + workspaceId, + { ...read.files, 'tables/plans.rows.jsonl': twelve }, + { base: read.base } + ) + expect(edited.failed).toBeUndefined() + + const reread = await runner.get(workspaceId) + const shrunk = await apply( + workspaceId, + { ...reread.files, 'tables/plans.rows.jsonl': twelve.split('\n').slice(1).join('\n') }, + { base: reread.base, allowDelete: true } + ) + expect(shrunk.failed).toBeUndefined() + } finally { + planRowLimit.value = undefined + } + expect((await storedRows(workspaceId)).map((row) => row.seats).sort()).toEqual([12, 50]) + } + ) + check( 'refuses at plan time a column made required that a row the UI added leaves empty, though the rows file is unchanged', async () => { From d77e8cb615ab64b515a40b4b729bdf39000c8338 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:04:12 -0800 Subject: [PATCH 70/85] fix(tables): a bulk action resolves and dedupes every table reference before acting, so a table named twice is not reported missing after its delete --- apps/sim/lib/table/application/bulk.test.ts | 13 +++- apps/sim/lib/table/application/bulk.ts | 74 +++++++++++++-------- 2 files changed, 57 insertions(+), 30 deletions(-) diff --git a/apps/sim/lib/table/application/bulk.test.ts b/apps/sim/lib/table/application/bulk.test.ts index e5db7ef3842..203eba02031 100644 --- a/apps/sim/lib/table/application/bulk.test.ts +++ b/apps/sim/lib/table/application/bulk.test.ts @@ -175,9 +175,16 @@ describe('table bulk application use cases', () => { }) it('acts once on a table named twice, by its id and by its name', async () => { - mocks.resolveTableContext.mockImplementation(async (tableId: string) => - tableContext(tableId === 'Table table-2' ? 'table-2' : tableId) - ) + const archived = new Set() + mocks.resolveTableContext.mockImplementation(async (reference: string) => { + const tableId = reference === 'Table table-2' ? 'table-2' : reference + if (archived.has(tableId)) throw new OrchestrationError('not_found', 'Table not found') + return tableContext(tableId) + }) + mocks.deleteTable.mockImplementation(async (tableId: string) => { + archived.add(tableId) + return { archived: { name: 'Archived', workspaceId: 'workspace-1' } } + }) const result = await bulkDeleteTables.execute({ principal, diff --git a/apps/sim/lib/table/application/bulk.ts b/apps/sim/lib/table/application/bulk.ts index b43ad1b151e..356e71443b8 100644 --- a/apps/sim/lib/table/application/bulk.ts +++ b/apps/sim/lib/table/application/bulk.ts @@ -302,7 +302,9 @@ async function notifyBatchedTableChanges( * operation already carries it, and acting on it separately would either pull * it out of the folder it is travelling with or archive it under a second * timestamp its folder's restore could never recover. A table named twice (by - * its id and by its name, say) is acted on once. + * its id and by its name, say) is acted on once: every reference resolves + * before anything is written, since a delete archives a table, and a later + * reference to it would no longer find it active. */ async function runTableItems( tableIds: readonly string[], @@ -314,40 +316,58 @@ async function runTableItems( succeeded: BulkTableItem[], outcome: BulkTablesOutcome ): Promise { + /** Records a per-item failure; returns the error when it must end the batch instead. */ + const settle = (error: unknown, tableId: string, tableName: string): unknown | undefined => { + const disposition = classifyBulkItemError(error, tableLockVerdict) + if (disposition.kind === 'notFound') { + outcome.notFound.push({ kind: 'table', id: tableId }) + return undefined + } + if (disposition.kind === 'failed') { + outcome.failed.push({ + kind: 'table', + id: tableId, + name: tableName, + reason: disposition.reason, + }) + return undefined + } + return disposition.error + } + const seen = new Set() + const selection: Array< + { tableId: string; canonical: ActiveTableContext } | { tableId: string; error: unknown } + > = [] for (const tableId of tableIds) { - let tableName = tableId try { const canonical = await resolveActiveTableInWorkspace(tableId, workspace) if (seen.has(canonical.table.id)) continue seen.add(canonical.table.id) - tableName = canonical.table.name - if (canonical.table.folderId && covered.has(canonical.table.folderId)) { - outcome.skipped.push({ kind: 'table', id: canonical.table.id, name: tableName }) - continue - } + selection.push({ tableId, canonical }) + } catch (error) { + selection.push({ tableId, error }) + } + } + + for (const item of selection) { + if ('error' in item) { + const fatal = settle(item.error, item.tableId, item.tableId) + if (fatal !== undefined) return fatal + continue + } + const { tableId, canonical } = item + const tableName = canonical.table.name + if (canonical.table.folderId && covered.has(canonical.table.folderId)) { + outcome.skipped.push({ kind: 'table', id: canonical.table.id, name: tableName }) + continue + } + try { await authorize(canonical) - succeeded.push({ - kind: 'table', - id: canonical.table.id, - name: await apply(canonical), - }) + succeeded.push({ kind: 'table', id: canonical.table.id, name: await apply(canonical) }) } catch (error) { - const disposition = classifyBulkItemError(error, tableLockVerdict) - if (disposition.kind === 'notFound') { - outcome.notFound.push({ kind: 'table', id: tableId }) - continue - } - if (disposition.kind === 'failed') { - outcome.failed.push({ - kind: 'table', - id: tableId, - name: tableName, - reason: disposition.reason, - }) - continue - } - return disposition.error + const fatal = settle(error, tableId, tableName) + if (fatal !== undefined) return fatal } } return undefined From 2360030479b0b7832a2c0099bb059a9632a28bd4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:05:57 -0800 Subject: [PATCH 71/85] test(sim-cli): tests start outside a GitHub Actions job, whatever the runner sets, and a JSON check in a job still annotates on stderr --- .../protocol/workflow-source-check.test.ts | 15 +++++++++++++++ packages/sim-cli/vitest.config.ts | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index 737bf89396f..2bc359fe850 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts @@ -336,6 +336,21 @@ describe('sim workflows source check', () => { expect(vi.mocked(console.error)).not.toHaveBeenCalled() }) + it('with --output json in a GitHub Actions job, still annotates each finding on stderr, as a workflow command only', async () => { + vi.stubEnv('GITHUB_ACTIONS', 'true') + cacheCatalog() + writeFileSync( + join(dir, 'workflow.ts'), + CLEAN.replace('{ body: { received: start.message } }', '{ bdy: { received: start.message } }') + ) + + await check() + + expect(stdoutJson()).toMatchObject({ diagnostics: [{ code: 'E_UNKNOWN_PARAM' }] }) + const stderr = vi.mocked(console.error).mock.calls.map((call) => call.join(' ')) + expect(stderr).toEqual([expect.stringMatching(/^::error file=.*,title=E_UNKNOWN_PARAM::/)]) + }) + it('leaves stored() to the server, which holds the stored values', async () => { cacheCatalog() writeFileSync( diff --git a/packages/sim-cli/vitest.config.ts b/packages/sim-cli/vitest.config.ts index 6f729af4c84..9d5c40db1e1 100644 --- a/packages/sim-cli/vitest.config.ts +++ b/packages/sim-cli/vitest.config.ts @@ -6,6 +6,11 @@ export default mergeConfig( defineConfig({ test: { include: ['src/**/*.test.ts'], + /** + * The CLI writes GitHub Actions annotations and step summaries when these are set, as they + * are on a CI runner: every test starts outside a job, and one that needs a job stubs them. + */ + env: { GITHUB_ACTIONS: '', GITHUB_STEP_SUMMARY: '', GITHUB_WORKSPACE: '' }, }, }) ) From 60b79b19bb8099e566324d9e78872a7ba5349341 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:05:58 -0800 Subject: [PATCH 72/85] fix(sim-cli): a machine-format source status annotates its findings in a GitHub Actions job, as a display one does --- packages/sim-cli/src/commands/protocol/source-status.ts | 2 +- .../src/commands/protocol/workspace-source-status.test.ts | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index edc4bb0070c..756b2b3dc73 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -152,11 +152,11 @@ export function printStatusReport( findings: readonly Diagnostic[] ): void { const shown = findingsOutput(format, false, report.dir) + shown.print(findings) if (shown.machine) { printDocument(format, findings.length > 0 ? { ...report, ...shown.result(findings) } : report) return } - shown.print(findings) const s = styles() const lines = [s.bold(sanitize(heading))] if (report.local.length === 0) lines.push('No local changes.') 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 9072e2d6f69..68b24862b39 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 @@ -160,6 +160,14 @@ describe('workspaces source status', () => { await run('status') expect(printed()).toMatchObject({ plan: { warnings: 1 }, diagnostics: [warning] }) + expect(vi.mocked(console.error)).not.toHaveBeenCalled() + + vi.stubEnv('GITHUB_ACTIONS', 'true') + await run('status') + + expect(vi.mocked(console.error).mock.calls.map((call) => call.join(' '))).toEqual([ + `::warning file=${join(dir, warning.file)},line=1,col=8,title=W_UNRESOLVED_REF::${warning.message}`, + ]) }) it('waits for no writer: a status while another command holds the directory exits 10, reading nothing', async () => { From 45d590ae577a3571f8dc205239505e0a82aa20b4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:10:49 -0800 Subject: [PATCH 73/85] fix(workspace-source): staging rechecks the workspace payer under its row lock, reports an unreadable staged total as unavailable, and an apply consumes only the staged copy it read --- apps/sim/lib/billing/storage/tracking.ts | 40 +++++-- .../application/staging.integration.ts | 110 +++++++++++++++++- .../sim/lib/workspace-source/staging/store.ts | 47 +++++--- 3 files changed, 172 insertions(+), 25 deletions(-) diff --git a/apps/sim/lib/billing/storage/tracking.ts b/apps/sim/lib/billing/storage/tracking.ts index 0a5858621d1..38116adfe9f 100644 --- a/apps/sim/lib/billing/storage/tracking.ts +++ b/apps/sim/lib/billing/storage/tracking.ts @@ -194,6 +194,20 @@ function getWorkspaceBillingEntity(row: LockedWorkspaceStorage): BillingEntity { : { type: 'user', id: row.billedAccountUserId } } +/** Whether the locked workspace row still routes storage to `context`'s payer. */ +function routesToContextPayer( + row: LockedWorkspaceStorage, + context: StorageBillingContext +): boolean { + const currentBillingEntity = getWorkspaceBillingEntity(row) + return ( + row.id === context.workspaceId && + currentBillingEntity.type === context.billingEntity.type && + currentBillingEntity.id === context.billingEntity.id && + row.billedAccountUserId === context.billedAccountUserId + ) +} + /** * Rejects an optimistic storage context when the workspace payer changed before * the transaction acquired its lock. @@ -202,19 +216,27 @@ function assertWorkspaceStorageContext( row: LockedWorkspaceStorage, context: StorageBillingContext ): BillingEntity { - const currentBillingEntity = getWorkspaceBillingEntity(row) - const expectedBillingEntity = context.billingEntity - if ( - row.id !== context.workspaceId || - currentBillingEntity.type !== expectedBillingEntity.type || - currentBillingEntity.id !== expectedBillingEntity.id || - row.billedAccountUserId !== context.billedAccountUserId - ) { + if (!routesToContextPayer(row, context)) { throw new Error( `Storage payer changed for workspace ${context.workspaceId}; resolve a fresh billing context` ) } - return currentBillingEntity + return getWorkspaceBillingEntity(row) +} + +/** + * Whether the workspace still routes storage to the payer `context` resolved before `tx` opened. + * Locks the workspace row as {@link lockWorkspaceStorageForMutationInTx} does (taking its place in + * the lock order), so no payer transfer moves the workspace before `tx` ends. + */ +export async function isWorkspaceStoragePayerInTx( + tx: DbOrTx, + context: StorageBillingContext +): Promise { + return routesToContextPayer( + await lockWorkspaceStorageForMutationInTx(tx, context.workspaceId), + context + ) } /** diff --git a/apps/sim/lib/workspace-source/application/staging.integration.ts b/apps/sim/lib/workspace-source/application/staging.integration.ts index ab764a03700..297b1f72c71 100644 --- a/apps/sim/lib/workspace-source/application/staging.integration.ts +++ b/apps/sim/lib/workspace-source/application/staging.integration.ts @@ -55,10 +55,48 @@ vi.mock('@/lib/billing/storage/limits', async (importOriginal) => { } }) +/** + * While `stalePayer` is set, staging resolves its payer as that user, as a payer transfer that + * lands between the resolve and the staging transaction leaves it. + */ +const payers = vi.hoisted(() => ({ stalePayer: null as string | null })) +vi.mock('@/lib/billing/storage/context', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + resolveStorageBillingContext: async ( + ...args: Parameters + ) => { + const context = await actual.resolveStorageBillingContext(...args) + const stale = payers.stalePayer + return stale === null + ? context + : { + ...context, + billedAccountUserId: stale, + billingEntity: { type: 'user' as const, id: stale }, + } + }, + } +}) +/** While `fail` is set, reading the bytes staged against a payer's quota errors. */ +const stagedReads = vi.hoisted(() => ({ fail: false })) +vi.mock('@/lib/billing/core/payer-context', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + workspacesPaidBy: (...args: Parameters) => { + if (stagedReads.fail) throw new Error('Connection terminated unexpectedly') + return actual.workspacesPaidBy(...args) + }, + } +}) + import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server' import { findMissingSourceBlobs, stageSourceBlobs, + stagingScopeOf, } from '@/lib/workspace-source/application/stage-blobs' import { blobManifest, @@ -66,7 +104,10 @@ import { sourceRunner, sourceWorkspaces, } from '@/lib/workspace-source/application/workspace-source.test-helpers' -import { sweepExpiredStagedBlobs } from '@/lib/workspace-source/staging/store' +import { + markStagedBlobsConsumed, + sweepExpiredStagedBlobs, +} from '@/lib/workspace-source/staging/store' let storageRoot = '' const ownerId = generateId() @@ -380,6 +421,73 @@ describe('workspace source staging', () => { } ) + check( + 'a payer that changed before the staging transaction refuses staging as unavailable, charging neither payer', + async () => { + const workspaceId = await workspaces.create({ name: 'Staging payer moved', ownerId: payerId }) + // The payer the workspace moved away from, with room to spare: only the move refuses. + await db.insert(userStats).values({ id: generateId(), userId: ownerId }) + vi.stubEnv('FREE_STORAGE_LIMIT_GB', '1') + payers.stalePayer = ownerId + try { + const refused = await failure(stage(payer, workspaceId, [blob('payer moved')])) + expect(refused).toMatchObject({ code: 'unavailable' }) + expect(await rows(workspaceId)).toEqual([]) + expect(objectsUnder(workspaceId)).toEqual([]) + } finally { + payers.stalePayer = null + vi.unstubAllEnvs() + } + } + ) + + check( + 'staged bytes that cannot be read refuse staging as unavailable, never as a full staging area', + async () => { + const workspaceId = await workspaces.create({ name: 'Staged read down', ownerId: payerId }) + vi.stubEnv('FREE_STORAGE_LIMIT_GB', '1') + stagedReads.fail = true + try { + const refused = await failure(stage(payer, workspaceId, [blob('staged read down')])) + expect(refused).toMatchObject({ code: 'unavailable' }) + expect(await rows(workspaceId)).toEqual([]) + } finally { + stagedReads.fail = false + vi.unstubAllEnvs() + } + } + ) + + check( + 'an apply marks consumed only the staged copy it read, not one staged again in its place after it expired', + async () => { + const workspaceId = await newWorkspace() + const a = blob('replaced alpha') + await stage(owner, workspaceId, [a]) + const [read] = await rows(workspaceId) + await db + .update(workspaceSourceStagedBlob) + .set({ expiresAt: new Date(Date.now() - 1000) }) + .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) + await stage(owner, workspaceId, [a]) + + await markStagedBlobsConsumed(stagingScopeOf(owner, workspaceId), [ + { sha256: a.sha256, size: a.size, storageKey: read.storageKey }, + ]) + + const held = await db + .select({ + storageKey: workspaceSourceStagedBlob.storageKey, + consumedAt: workspaceSourceStagedBlob.consumedAt, + }) + .from(workspaceSourceStagedBlob) + .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) + expect(held).toHaveLength(1) + expect(held[0].storageKey).not.toBe(read.storageKey) + expect(held[0].consumedAt).toBeNull() + } + ) + check('bytes that do not hash to their name refuse the whole batch, nothing stored', async () => { const workspaceId = await newWorkspace() const good = blob('good bytes') diff --git a/apps/sim/lib/workspace-source/staging/store.ts b/apps/sim/lib/workspace-source/staging/store.ts index d321ae86197..abae0550c8e 100644 --- a/apps/sim/lib/workspace-source/staging/store.ts +++ b/apps/sim/lib/workspace-source/staging/store.ts @@ -28,6 +28,7 @@ import { checkStorageQuotaForBillingContext, isStorageEnforcementEnabled, } from '@/lib/billing/storage/limits' +import { isWorkspaceStoragePayerInTx } from '@/lib/billing/storage/tracking' import { OrchestrationError } from '@/lib/core/orchestration/types' import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' import type { DbTransaction } from '@/lib/db/types' @@ -49,6 +50,8 @@ const SWEEP_BATCH = 500 const STORAGE_CONTEXT = 'workspace' as const +const QUOTA_UNAVAILABLE = 'Could not check the storage quota for staging; retry shortly.' + /** A staged blob as an apply reads it. */ export interface StagedBlob { sha256: string @@ -146,32 +149,41 @@ async function payerStagedBytes(tx: DbTransaction, payer: BillingEntity): Promis /** * Refuses staging `bytes` more in `billing`'s workspace when the bytes its payer stores, plus those - * staged in any of the payer's workspaces, plus these would pass the payer's storage quota. Holds the - * payer's staging lock until `tx` ends (through the insert that follows), so concurrent staging in - * another workspace of the same payer cannot pass the check together. A quota that could not be read is a `503`, never - * {@link SourceStagingFullError}, which a client takes as permanent. + * staged in any of the payer's workspaces, plus these would pass the payer's storage quota. First + * confirms the workspace is still paid by `billing`'s payer (resolved before `tx` opened), locking + * its row so no payer transfer moves it before `tx` ends; then holds the payer's staging lock until + * `tx` ends (through the insert that follows), so concurrent staging in another workspace of the + * same payer cannot pass the check together. A payer that moved, or a quota or staged total that + * could not be read, is a `503`, never {@link SourceStagingFullError}, which a client takes as + * permanent. */ async function assertStagingWithinQuota( tx: DbTransaction, billing: StorageBillingContext, bytes: number ): Promise { + if (!(await isWorkspaceStoragePayerInTx(tx, billing))) { + throw new OrchestrationError( + 'unavailable', + 'The workspace changed payer while staging; retry shortly.' + ) + } const { type, id } = billing.billingEntity await acquireAdvisoryXactLock( tx, 'workspace_source_staging', `workspace-source-staging-payer:${type}:${id}` ) - const quota = await checkStorageQuotaForBillingContext( - billing, - (await payerStagedBytes(tx, billing.billingEntity)) + bytes, - tx - ) + let staged: number + try { + staged = await payerStagedBytes(tx, billing.billingEntity) + } catch (error) { + logger.error('Could not read the bytes staged against the storage quota', { error }) + throw new OrchestrationError('unavailable', QUOTA_UNAVAILABLE) + } + const quota = await checkStorageQuotaForBillingContext(billing, staged + bytes, tx) if (quota.unavailable) { - throw new OrchestrationError( - 'unavailable', - 'Could not check the storage quota for staging; retry shortly.' - ) + throw new OrchestrationError('unavailable', QUOTA_UNAVAILABLE) } if (!quota.allowed) { throw new SourceStagingFullError( @@ -349,7 +361,9 @@ export async function stageBlobs( /** * Marks `blobs` consumed: an apply wrote their bytes into the workspace, which now charges for - * them, so they no longer count toward the payer's quota. They stay staged until they expire. + * them, so they no longer count toward the payer's quota. They stay staged until they expire. Each + * is matched by its storage key too, so a row staged again in its place since the apply read it + * (once it expired) keeps counting. */ export async function markStagedBlobsConsumed( target: StagingScope, @@ -362,7 +376,10 @@ export async function markStagedBlobsConsumed( .where( and( inScope(target), - inArray(workspaceSourceStagedBlob.sha256, [...new Set(blobs.map((blob) => blob.sha256))]) + inArray(workspaceSourceStagedBlob.sha256, [...new Set(blobs.map((blob) => blob.sha256))]), + inArray(workspaceSourceStagedBlob.storageKey, [ + ...new Set(blobs.map((blob) => blob.storageKey)), + ]) ) ) } From 35f7ee4c332163c02873d4ff9cbd29b797943620 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:10:50 -0800 Subject: [PATCH 74/85] fix(workspace-source): a knowledge write that fails partway still consumes the staged documents it uploaded --- .../application/apply-workspace-source.ts | 16 +++++++++++++--- .../application/kinds/knowledge/adapter.ts | 4 +++- .../application/knowledge.integration.ts | 14 ++++++++++++++ .../lib/workspace-source/application/types.ts | 7 +++++-- 4 files changed, 35 insertions(+), 6 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts index 468c7053b10..a4c8687a6d0 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -401,7 +401,8 @@ async function consumeStagedBlobs(target: StagingScope, consumed: StagedBlob[]): /** * Writes the plan's changes in write order under `lease`, recording each into `base` and * `result`; the first failure stops it and is reported as `result.failed`. Each write reads its - * binary files from `staged`; returns the staged blobs of the writes that succeeded. + * binary files from `staged`; returns the staged blobs the workspace now stores: those of the + * writes that succeeded, and those the failed write reported stored before it failed. */ async function writeAll( changes: PlannedChange[], @@ -419,15 +420,23 @@ async function writeAll( const consumed: StagedBlob[] = [] for (const change of writeOrder(changes)) { const read: StagedBlob[] = [] + const stored: StagedBlob[] = [] + const stagedAt = (path: string) => { + const blob = staged.get(path) + if (!blob) throw new Error('A blob write ran without its staged bytes') + return blob + } const writeCtx: ApplyContext = { ...ctx, blobs: { read(path) { - const blob = staged.get(path) - if (!blob) throw new Error('A blob write ran without its staged bytes') + const blob = stagedAt(path) read.push(blob) return readStagedBlob(blob) }, + stored(path) { + stored.push(stagedAt(path)) + }, }, } try { @@ -457,6 +466,7 @@ async function writeAll( if (written.base) base.resources[address] = written.base else delete base.resources[address] } catch (error) { + consumed.push(...stored) const failure = failureOf(error, change, result.applyId) result.failed = failure.failed result.diagnostics.push(...failure.diagnostics) diff --git a/apps/sim/lib/workspace-source/application/kinds/knowledge/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/knowledge/adapter.ts index d8c3381edff..2476d786af9 100644 --- a/apps/sim/lib/workspace-source/application/kinds/knowledge/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/knowledge/adapter.ts @@ -469,7 +469,8 @@ async function uploadDocs( for (const upload of uploads) { if (!ctx.blobs) throw new Error('A document upload needs its staged bytes') // One document's bytes at a time: a large knowledge base never sits in memory whole. - const buffer = await ctx.blobs.read(knowledgeDocPath(key, upload.name)) + const path = knowledgeDocPath(key, upload.name) + const buffer = await ctx.blobs.read(path) const extension = getFileExtension(upload.name) const { document } = await uploadKnowledgeDocument.execute({ principal: ctx.principal, @@ -484,6 +485,7 @@ async function uploadDocs( }, }, }) + ctx.blobs.stored(path) hashes.set(document.id, upload.doc.sha256) if (upload.replaces) { await finishReplace(ctx, knowledgeBaseId, upload.replaces, document.id, upload.name) diff --git a/apps/sim/lib/workspace-source/application/knowledge.integration.ts b/apps/sim/lib/workspace-source/application/knowledge.integration.ts index 8deeafbc44e..8c3a38c94c5 100644 --- a/apps/sim/lib/workspace-source/application/knowledge.integration.ts +++ b/apps/sim/lib/workspace-source/application/knowledge.integration.ts @@ -22,6 +22,7 @@ import { permissionGroupWorkspace, user, userStats, + workspaceSourceStagedBlob, } from '@sim/db/schema' import { sha256Hex } from '@sim/security/hash' import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' @@ -1089,6 +1090,19 @@ describe('knowledge bases as workspace source', () => { expect(first.failed).toMatchObject({ key: 'policies', code: 'E_APPLY_FAILED' }) const stored = await knowledgeBaseNamed(workspaceId, 'Policies') expect(await filenames(stored.id)).toEqual(['refunds.md']) + // The uploaded document is stored, so its staged bytes stop counting toward the quota. + const staging = await db + .select({ + sha256: workspaceSourceStagedBlob.sha256, + consumedAt: workspaceSourceStagedBlob.consumedAt, + }) + .from(workspaceSourceStagedBlob) + .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) + const consumed = (path: string) => + staging.find((row) => row.sha256 === sha256Hex(POLICIES.docs[path] ?? Buffer.alloc(0))) + ?.consumedAt ?? null + expect(consumed(REFUNDS)).toBeInstanceOf(Date) + expect(consumed('knowledge/policies/docs/shipping.txt')).toBeNull() const second = await apply(workspaceId, POLICIES, { base: first.base }) diff --git a/apps/sim/lib/workspace-source/application/types.ts b/apps/sim/lib/workspace-source/application/types.ts index d7b33029204..d990b892f58 100644 --- a/apps/sim/lib/workspace-source/application/types.ts +++ b/apps/sim/lib/workspace-source/application/types.ts @@ -81,9 +81,12 @@ export interface ApplyContext extends SourceContext { writtenDrafts: Map /** * Reads the staged bytes of a blob a write needs, by directory path, checked against its - * SHA-256. Loaded one blob at a time, so a write never holds more than it is writing. + * SHA-256. Loaded one blob at a time, so a write never holds more than it is writing. The blobs + * a write read are consumed (stop counting toward the payer's quota) once it succeeds; a write + * that stores several one at a time calls `stored` after each, so one that fails partway still + * consumes those the workspace now holds. */ - blobs?: { read(path: string): Promise } + blobs?: { read(path: string): Promise; stored(path: string): void } } /** A stored resource of one kind: its key (when bound), id, display name and kind state. */ From f3206ab41b049760ad9563df0823664d9006d9f6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:10:51 -0800 Subject: [PATCH 75/85] docs(workspace-source): staging an applied blob again counts it against the quota again --- apps/docs/openapi-v2-workflows.json | 2 +- apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 35c7250e301..21388e46934 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -9350,7 +9350,7 @@ "post": { "operationId": "stageWorkspaceSourceBlobs", "summary": "Stage workspace source blobs", - "description": "Stage the bytes of binary files (workspace files, knowledge documents) for a workspace source apply, as multipart form data: one file part per blob, its field name the SHA-256 of its bytes. At most 1000 files and 8000000 bytes per request, 10000000 bytes per file; a larger file goes in a request of its own. A body over 10001024 bytes answers `413` (`PAYLOAD_TOO_LARGE`) before it is read. A part whose bytes hash to another SHA-256 refuses the whole request (`400`), nothing staged. Staged files are scoped to the workspace and the caller, capped at 20000 files and 4000000000 bytes (`413` with `details.code` `SOURCE_STAGING_FULL` past either), count against the workspace payer's storage quota while held (`413` with `SOURCE_STAGING_FULL` past it), and expire a day after they were last staged; asking for them or applying with them never renews them, and an apply does not remove them. Staging the same bytes again only renews them. Requires workspace write access. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:write`.", + "description": "Stage the bytes of binary files (workspace files, knowledge documents) for a workspace source apply, as multipart form data: one file part per blob, its field name the SHA-256 of its bytes. At most 1000 files and 8000000 bytes per request, 10000000 bytes per file; a larger file goes in a request of its own. A body over 10001024 bytes answers `413` (`PAYLOAD_TOO_LARGE`) before it is read. A part whose bytes hash to another SHA-256 refuses the whole request (`400`), nothing staged. Staged files are scoped to the workspace and the caller, capped at 20000 files and 4000000000 bytes (`413` with `details.code` `SOURCE_STAGING_FULL` past either), count against the workspace payer's storage quota while held (`413` with `SOURCE_STAGING_FULL` past it) until an apply writes them into the workspace, and expire a day after they were last staged; asking for them or applying with them never renews them, and an apply does not remove them. Staging the same bytes again renews them, and once an apply wrote them makes them count against the quota again, so it can answer `SOURCE_STAGING_FULL` too. Requires workspace write access. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:write`.", "x-sim-operation": "workspaces.source.blobs.stage", "x-oauth-scope": "api:write", "tags": ["Workflows"], diff --git a/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts b/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts index 076511bb7c2..943639f3c57 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts @@ -250,7 +250,7 @@ export const workspaceSourceOpenApiRoutes = [ applicationOperation: workspaceSourceOperations.stageBlobs, operationId: 'stageWorkspaceSourceBlobs', summary: 'Stage workspace source blobs', - description: `Stage the bytes of binary files (workspace files, knowledge documents) for a workspace source apply, as multipart form data: one file part per blob, its field name the SHA-256 of its bytes. At most ${WORKSPACE_SOURCE_LIMITS.maxBlobsPerRequest} files and ${WORKSPACE_SOURCE_LIMITS.maxBlobBytesPerRequest} bytes per request, ${WORKSPACE_SOURCE_LIMITS.maxBlobBytes} bytes per file; a larger file goes in a request of its own. A body over ${WORKSPACE_SOURCE_STAGE_MAX_BYTES} bytes answers \`413\` (\`PAYLOAD_TOO_LARGE\`) before it is read. A part whose bytes hash to another SHA-256 refuses the whole request (\`400\`), nothing staged. Staged files are scoped to the workspace and the caller, capped at ${WORKSPACE_SOURCE_LIMITS.maxStagedBlobs} files and ${WORKSPACE_SOURCE_LIMITS.maxStagedBytes} bytes (\`413\` with \`details.code\` \`SOURCE_STAGING_FULL\` past either), count against the workspace payer's storage quota while held (\`413\` with \`SOURCE_STAGING_FULL\` past it), and expire a day after they were last staged; asking for them or applying with them never renews them, and an apply does not remove them. Staging the same bytes again only renews them. Requires workspace write access. Returns \`403\` while workflows as code is not enabled.`, + description: `Stage the bytes of binary files (workspace files, knowledge documents) for a workspace source apply, as multipart form data: one file part per blob, its field name the SHA-256 of its bytes. At most ${WORKSPACE_SOURCE_LIMITS.maxBlobsPerRequest} files and ${WORKSPACE_SOURCE_LIMITS.maxBlobBytesPerRequest} bytes per request, ${WORKSPACE_SOURCE_LIMITS.maxBlobBytes} bytes per file; a larger file goes in a request of its own. A body over ${WORKSPACE_SOURCE_STAGE_MAX_BYTES} bytes answers \`413\` (\`PAYLOAD_TOO_LARGE\`) before it is read. A part whose bytes hash to another SHA-256 refuses the whole request (\`400\`), nothing staged. Staged files are scoped to the workspace and the caller, capped at ${WORKSPACE_SOURCE_LIMITS.maxStagedBlobs} files and ${WORKSPACE_SOURCE_LIMITS.maxStagedBytes} bytes (\`413\` with \`details.code\` \`SOURCE_STAGING_FULL\` past either), count against the workspace payer's storage quota while held (\`413\` with \`SOURCE_STAGING_FULL\` past it) until an apply writes them into the workspace, and expire a day after they were last staged; asking for them or applying with them never renews them, and an apply does not remove them. Staging the same bytes again renews them, and once an apply wrote them makes them count against the quota again, so it can answer \`SOURCE_STAGING_FULL\` too. Requires workspace write access. Returns \`403\` while workflows as code is not enabled.`, tags: ['Workflows'], errors: [...RESOURCE_MUTATION_ERRORS, 'PayloadTooLarge'], success: { description: 'The binary files staged.', headers: RATE_LIMIT_HEADERS }, From 2f41f4b4978af36bb9129cfb195300367f924077 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:11:56 -0800 Subject: [PATCH 76/85] fix(logs): a run that fails after its input stage, before it runs, records its redacted input --- .../workflows/executor/execution-core.test.ts | 25 +++++++++++++++++++ .../lib/workflows/executor/execution-core.ts | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/workflows/executor/execution-core.test.ts b/apps/sim/lib/workflows/executor/execution-core.test.ts index fd5a8f4f24a..99d506c9817 100644 --- a/apps/sim/lib/workflows/executor/execution-core.test.ts +++ b/apps/sim/lib/workflows/executor/execution-core.test.ts @@ -1097,6 +1097,31 @@ describe('executeWorkflowCore terminal finalization sequencing', () => { } ) + it('logs the redacted input of a run that fails after its input stage, before it runs', async () => { + const state = createRestoredState(createManifest()) + state.blockStates = { previous: { output: { result: 'restored alice@example.com' } } } + maskBatchMock + .mockImplementationOnce(async (texts: string[]) => ({ + masked: texts.map((text) => text.replaceAll('alice@example.com', '')), + scrubbedCount: 0, + })) + .mockRejectedValue(new Error('PII service unavailable')) + + await expect( + executeWorkflowCore({ + snapshot: createPiiSnapshot(state, { email: 'alice@example.com' }), + callbacks: {}, + loggingSession: loggingSession as unknown as LoggingSession, + }) + ).rejects.toThrow() + + expect(executorExecuteMock).not.toHaveBeenCalled() + expect(safeCompleteWithErrorMock).toHaveBeenCalledOnce() + expect(safeCompleteWithErrorMock.mock.calls[0]?.[0]?.workflowInput).toEqual({ + email: '', + }) + }) + it.each([ ['another workspace', 'workspace-2', 'workflow-1', 'source-execution'], ['another workflow', 'workspace-1', 'workflow-2', 'source-execution'], diff --git a/apps/sim/lib/workflows/executor/execution-core.ts b/apps/sim/lib/workflows/executor/execution-core.ts index 3de1bec9296..709587b26b4 100644 --- a/apps/sim/lib/workflows/executor/execution-core.ts +++ b/apps/sim/lib/workflows/executor/execution-core.ts @@ -1187,6 +1187,7 @@ async function executeWorkflowCoreImpl( }) processedInput = await redactObjectStrings(processedInput, inputOpts) } + executorInput = processedInput if (piiRedaction.blockOutputs.enabled) { // Resume / run-from-block restore prior block outputs into state. If those @@ -1364,7 +1365,6 @@ async function executeWorkflowCoreImpl( } } - executorInput = processedInput const executorInstance = new Executor({ workflow: serializedWorkflow, envVarValues: decryptedEnvVars, From d7279f4d09008623535fcac66e2f9042e5d41c29 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:12:37 -0800 Subject: [PATCH 77/85] fix(logs): a completion that falls back to the cost-only log keeps the run input --- .../logs/execution/logging-session.test.ts | 26 +++++++++++++++++++ .../sim/lib/logs/execution/logging-session.ts | 6 +++++ 2 files changed, 32 insertions(+) diff --git a/apps/sim/lib/logs/execution/logging-session.test.ts b/apps/sim/lib/logs/execution/logging-session.test.ts index 69c1211fb30..f8481ae80ba 100644 --- a/apps/sim/lib/logs/execution/logging-session.test.ts +++ b/apps/sim/lib/logs/execution/logging-session.test.ts @@ -141,6 +141,9 @@ function createDisplayProvenance(matches: ResolvedSecretTraceMatch[], complete = } } +/** A run's input, as its completion records it. */ +const INPUT = { hello: 'world' } + describe('LoggingSession diagnostic projection', () => { it('projects execution errors with the run-scoped secret provenance', () => { const secret = 'logging-session-secret-7f3a91' @@ -551,6 +554,29 @@ describe('LoggingSession completion retries', () => { ) }) + it.each([ + ['success', (session: LoggingSession) => session.safeComplete({ workflowInput: INPUT })], + ['error', (session: LoggingSession) => session.safeCompleteWithError({ workflowInput: INPUT })], + [ + 'cancellation', + (session: LoggingSession) => session.safeCompleteWithCancellation({ workflowInput: INPUT }), + ], + ['pause', (session: LoggingSession) => session.safeCompleteWithPause({ workflowInput: INPUT })], + ])('keeps the run input when a %s completion falls back', async (_, complete) => { + const session = new LoggingSession('workflow-1', 'execution-input', 'api', 'req-1') + session.setResolvedSecretTraceRegistry(createSecretRegistry([])) + completeWorkflowExecutionMock + .mockRejectedValueOnce(new Error('finalize failed')) + .mockResolvedValueOnce({}) + + await complete(session) + + expect(completeWorkflowExecutionMock).toHaveBeenCalledTimes(2) + expect(completeWorkflowExecutionMock).toHaveBeenLastCalledWith( + expect.objectContaining({ executionId: 'execution-input', workflowInput: INPUT }) + ) + }) + it('projects only TraceSpans while preserving functional completion values', async () => { const session = new LoggingSession('workflow-1', 'execution-safe', 'api', 'req-1') const secret = 'sk-demo / trace?token=7f3a91' diff --git a/apps/sim/lib/logs/execution/logging-session.ts b/apps/sim/lib/logs/execution/logging-session.ts index b949f83ae6a..73cfeae2f9b 100644 --- a/apps/sim/lib/logs/execution/logging-session.ts +++ b/apps/sim/lib/logs/execution/logging-session.ts @@ -1532,6 +1532,7 @@ export class LoggingSession { }) await this.completeWithCostOnlyLog({ traceSpans: params.traceSpans, + workflowInput: params.workflowInput, endedAt: params.endedAt, totalDurationMs: params.totalDurationMs, errorMessage: `Failed to store trace spans: ${errorMsg}`, @@ -1561,6 +1562,7 @@ export class LoggingSession { ) await this.completeWithCostOnlyLog({ traceSpans: params?.traceSpans, + workflowInput: params?.workflowInput, endedAt: params?.endedAt, totalDurationMs: params?.totalDurationMs, errorMessage: @@ -1595,6 +1597,7 @@ export class LoggingSession { ) await this.completeWithCostOnlyLog({ traceSpans: params?.traceSpans, + workflowInput: params?.workflowInput, endedAt: params?.endedAt, totalDurationMs: params?.totalDurationMs, errorMessage: 'Run was cancelled', @@ -1624,6 +1627,7 @@ export class LoggingSession { ) await this.completeWithCostOnlyLog({ traceSpans: params?.traceSpans, + workflowInput: params?.workflowInput, endedAt: params?.endedAt, totalDurationMs: params?.totalDurationMs, errorMessage: 'Run paused but failed to store full trace spans', @@ -1731,6 +1735,7 @@ export class LoggingSession { private async completeWithCostOnlyLog(params: { traceSpans?: TraceSpan[] + workflowInput?: unknown endedAt?: string totalDurationMs?: number errorMessage: string @@ -1766,6 +1771,7 @@ export class LoggingSession { costSummary, finalOutput, traceSpans: [], + workflowInput: params.workflowInput, executionState: params.executionState, finalizationPath: params.finalizationPath, completionFailure: params.errorMessage, From 41c4ab3dc9f0a6d995bfddc5a083f35251e6706d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:13:26 -0800 Subject: [PATCH 78/85] fix(workflow-code): block meta written among block()'s params points at its fourth argument --- packages/workflow-code/src/compile/blocks.ts | 4 +++- .../workflow-code/src/compile/ergonomics.test.ts | 12 +++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 8b437b3993f..2ddecfc7cf7 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -1141,7 +1141,9 @@ function compileWrittenParams( hint: alias ? `Write it as ${alias}; the value kind picks the basic or advanced field.` : (BLOCK_META_KEYS as readonly string[]).includes(key) - ? `${key} is block meta, not a param: pass it in the builder's third argument, ('Name', {…}, { ${key}: … }).` + ? builder.kind === 'generic' + ? `${key} is block meta, not a param: pass it in block()'s fourth argument, block('type', 'Name', {…}, { ${key}: … }).` + : `${key} is block meta, not a param: pass it in the builder's third argument, ('Name', {…}, { ${key}: … }).` : didYouMean(key, index.fields.keys()), blockKey: decl.key, param: key, diff --git a/packages/workflow-code/src/compile/ergonomics.test.ts b/packages/workflow-code/src/compile/ergonomics.test.ts index 63e38f8cb8d..0bceee7331f 100644 --- a/packages/workflow-code/src/compile/ergonomics.test.ts +++ b/packages/workflow-code/src/compile/ergonomics.test.ts @@ -10,7 +10,7 @@ import { compileWorkflow } from './index' const fake = (...parts: string[]) => parts.join('') const IMPORTS = - "import { agent, api, childWorkflow, condition, customTool, credential, fn, human, js, mail, mcp, parallel, raw, slack, stored, t, table, trigger, workflow } from '@sim/workflow-sdk'" + "import { agent, api, block, childWorkflow, condition, customTool, credential, fn, human, js, mail, mcp, parallel, raw, slack, stored, t, table, trigger, workflow } from '@sim/workflow-sdk'" function source(body: string, header = '// @sim-sdk 1'): string { return `${header}\n${IMPORTS}\n\nexport default workflow('Test', {}, () => {\n${body}\n})\n` @@ -78,6 +78,16 @@ describe('param aliases', () => { /^retry is block meta, not a param: pass it in the builder's third argument/ ) }) + + it('points block meta written among the params of block() at its fourth argument', () => { + const result = run( + source(" block('mail', 'M', { to: 'a@b.c', retry: { enabled: true, maxTries: 3 } })") + ) + const unknown = result.diagnostics.find((d) => d.code === 'E_UNKNOWN_PARAM') + expect(unknown?.hint).toBe( + "retry is block meta, not a param: pass it in block()'s fourth argument, block('type', 'Name', {…}, { retry: … })." + ) + }) }) describe('stored()', () => { From 7c11885ef1e1d7a5c9fa1706f47025b5b8892c95 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:15:46 -0800 Subject: [PATCH 79/85] fix(sim-cli): webhook URLs after an apply name blocks by the saved lock for a deployment-only write, strip escapes from a read failure, and a cancelled read fails the command --- .../src/commands/protocol/deployed-urls.ts | 7 +- .../protocol/workspace-source-apply.test.ts | 75 +++++++++++++++++++ .../protocol/workspace-source-apply.ts | 22 ++++-- 3 files changed, 97 insertions(+), 7 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/deployed-urls.ts b/packages/sim-cli/src/commands/protocol/deployed-urls.ts index 0ad2087a284..7e53c87dbda 100644 --- a/packages/sim-cli/src/commands/protocol/deployed-urls.ts +++ b/packages/sim-cli/src/commands/protocol/deployed-urls.ts @@ -7,6 +7,7 @@ import { parseWorkflowLock } from '@sim/workflow-code' import { printError } from '#sim-cli/output/io' import { sanitize } from '#sim-cli/output/render' import type { GetWorkflowDeploymentResponse } from '../../generated/v2-api' +import { REQUEST_CANCELLED, SimApiError } from '../../http/client' import type { OperationClient } from '../../runtime/called-operations' /** A webhook of a deployed workflow, which callers reach at `url`. */ @@ -48,7 +49,8 @@ export function namedUrls( /** * The URL of each webhook `workflowId`'s live deployment serves, named through `names`. A failed - * read is reported and yields none: the deploy itself stands. + * read is reported and yields none: the deploy itself stands. A cancelled read is rethrown, so a + * cancelled command never reports success. */ export async function deployedUrls( client: OperationClient<'getWorkflowDeployment'>, @@ -61,8 +63,9 @@ export async function deployedUrls( }) return namedUrls(data.webhooks, names) } catch (error) { + if (error instanceof SimApiError && error.code === REQUEST_CANCELLED) throw error printError( - `The deploy succeeded, but its webhook URLs could not be read (${getErrorMessage(error)}): \`sim workflows deployment status ${workflowId}\` lists them.` + `The deploy succeeded, but its webhook URLs could not be read (${sanitize(getErrorMessage(error))}): \`sim workflows deployment status ${sanitize(workflowId)}\` lists them.` ) return [] } diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index d9706e985a3..6f0a6a46b61 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1671,6 +1671,81 @@ describe('workspaces source apply', () => { }) }) + it('names the webhook URLs of a deployment-only apply by the lock the directory holds', async () => { + const hookUrl = 'https://sim.example/api/webhooks/trigger/abc' + const lock = { + version: 1, + blocks: { leadin: { id: 'b-hook', parent: null, ident: 'hook', order: 0 } }, + variables: {}, + } + mkdirSync(join(dir, 'workflows/ingest/.sim'), { recursive: true }) + writeFileSync(join(dir, 'workflows/ingest/.sim/lock.json'), JSON.stringify(lock)) + request.mockImplementation(async (path: string) => + path === '/api/v2/workflows/wf_1/deployment' + ? { + data: { + id: 'wf_1', + isDeployed: true, + webhooks: [{ blockId: 'b-hook', provider: 'generic', url: hookUrl }], + }, + } + : answer({ + plan: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + applied: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + files: {}, + base: { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } }, + }) + ) + + await apply('--yes') + + const printed = vi + .mocked(console.log) + .mock.calls.map(([line]) => String(line)) + .join('\n') + expect(JSON.parse(printed)).toMatchObject({ + urls: [{ workflow: 'ingest', block: 'leadin (hook)', url: hookUrl }], + }) + }) + + it('reports webhook URLs it could not read without the terminal escapes the failure carried', async () => { + request.mockImplementation(async (path: string) => { + if (path === '/api/v2/workflows/wf_1/deployment') { + throw new SimApiError('gateway \u001b[2Jcleared', 502) + } + return answer({ + plan: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + applied: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + base: { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } }, + }) + }) + + await apply('--yes') + + const warned = vi + .mocked(console.error) + .mock.calls.map(([line]) => String(line)) + .join('\n') + expect(warned).toContain('its webhook URLs could not be read (gateway cleared)') + expect(warned).not.toContain('\u001b') + }) + + it('fails, rather than reports success, when its webhook URL read is cancelled', async () => { + request.mockImplementation(async (path: string) => { + if (path === '/api/v2/workflows/wf_1/deployment') { + throw new SimApiError('Request cancelled.', 0, 'REQUEST_CANCELLED') + } + return answer({ + plan: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + applied: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + base: { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } }, + }) + }) + + await expect(apply('--yes')).rejects.toMatchObject({ code: 'REQUEST_CANCELLED' }) + expect(vi.mocked(console.log)).not.toHaveBeenCalled() + }) + it('appends the plan and its errors to the GitHub Actions step summary', async () => { const summary = join(dir, 'step-summary.md') vi.stubEnv('GITHUB_ACTIONS', 'true') diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index c31c0915aa8..88f66bb0e8d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -46,6 +46,7 @@ import { isMissing, orphanedCodeFiles, readSourceJson, + readSourceText, readWritten, recordedStats, updateSourceDir, @@ -918,7 +919,15 @@ export function attachWorkspaceSourceApply(source: Command): void { printError(`Stopped at ${data.failed.kind} ${data.failed.key}: ${data.failed.message}`) setSoftExitCode(failedExitCode(data.failed)) } - report(data, undefined, await deploymentUrls(client, data)) + // A promotion's directory holds the source workspace's locks, whose ids the target's + // blocks do not have. + report( + data, + undefined, + await deploymentUrls(client, data, async (path) => + promotion ? null : readSourceText(options.dir, path) + ) + ) }, { readOnly: mode === 'dry-run' || mode === 'plan' } ) @@ -998,11 +1007,13 @@ function workflowUrlsText(urls: readonly WorkflowUrl[]): string { /** * The webhook URLs of each workflow a written apply deployed (a `deployments/.ts` it created * or updated), in the workspace it wrote: a promotion's are the target's, which are new URLs. - * Each block is named as the workflow's reprinted lock names it. + * Each block is named as the workflow's reprinted lock names it, or, when the apply did not + * reprint the workflow (it wrote only the deployment), as `savedLock` reads it from the directory. */ async function deploymentUrls( client: OperationClient<'getWorkflowDeployment'>, - data: ApplyData + data: ApplyData, + savedLock: (path: string) => Promise ): Promise { if (data.dryRun) return [] const base = parseWorkspaceBase(data.base).base @@ -1013,8 +1024,9 @@ async function deploymentUrls( deployed.map(async ({ key }): Promise => { const workflowId = base?.resources[resourceAddress('workflow', key)]?.id if (!workflowId) return [] - const lock = data.files[`${workflowFolder(key)}/${SOURCE_LOCK_FILE}`] - const named = await deployedUrls(client, workflowId, lockBlockNames(lock ?? null)) + const lockPath = `${workflowFolder(key)}/${SOURCE_LOCK_FILE}` + const lock = data.files[lockPath] ?? (await savedLock(lockPath)) + const named = await deployedUrls(client, workflowId, lockBlockNames(lock)) return named.map((url) => ({ workflow: key, ...url })) }) ) From 705a06590d13b681c856bde0437463e48e22ccc0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:16:12 -0800 Subject: [PATCH 80/85] docs(catalog): a sunset block whose id is a base type with a visible newer version reads as that version --- apps/sim/lib/catalog/application/get-block.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/catalog/application/get-block.ts b/apps/sim/lib/catalog/application/get-block.ts index 9d34c774f78..a05ac252e9e 100644 --- a/apps/sim/lib/catalog/application/get-block.ts +++ b/apps/sim/lib/catalog/application/get-block.ts @@ -38,7 +38,10 @@ export interface GetCatalogBlockResult { * enumerate unrevealed blocks one id at a time. The one exception is a sunset * (legacy or deprecated) block hidden only for its lifecycle: placed instances * keep running, so it reads by its exact id (`starter`), its description leading - * with the block that replaces it (`start_trigger`). + * with the block that replaces it (`start_trigger`). An exact id that is also a + * base type with a visible newer version (`cursor`, beside `cursor_v3`) reads + * as that version, the name the list publishes it under, and the response + * echoes the resolved id. */ export const getCatalogBlock = defineAuthorizedWorkspaceUseCase({ operation: catalogOperations.readBlock, From cd81e29a9ebb795fcf1928f2e3098f788f8d994b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:17:44 -0800 Subject: [PATCH 81/85] fix(tables): a table name that starts with tbl_ is still addressable by name; only a reference shaped like a minted id skips the name lookup --- .../sim/lib/table/application/context.test.ts | 15 ++++++++++++++- apps/sim/lib/table/application/context.ts | 4 ++-- apps/sim/lib/table/ids.ts | 19 ++++++++++++++----- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/apps/sim/lib/table/application/context.test.ts b/apps/sim/lib/table/application/context.test.ts index c5836fef455..8f309c36ed1 100644 --- a/apps/sim/lib/table/application/context.test.ts +++ b/apps/sim/lib/table/application/context.test.ts @@ -96,10 +96,23 @@ describe('table application context', () => { // A stale id is never read as a name, so it costs no second query. await expect( - resolveActiveTableContext({ tableId: 'tbl_gone', assertedWorkspaceId: 'workspace-1' }) + resolveActiveTableContext({ + tableId: 'tbl_0123456789abcdef0123456789abcdef', + assertedWorkspaceId: 'workspace-1', + }) ).rejects.toMatchObject({ code: 'not_found' }) expect(findByName).not.toHaveBeenCalled() + // A name that only starts like an id is still a name. + findByName.mockResolvedValueOnce([ + { id: 'table-2', workspaceId: 'workspace-1', name: 'tbl_sales' }, + ]) + await expect( + resolveActiveTableContext({ tableId: 'tbl_sales', assertedWorkspaceId: 'workspace-1' }) + ).resolves.toMatchObject({ tableId: 'table-2' }) + expect(findByName).toHaveBeenLastCalledWith('workspace-1', 'tbl_sales') + findByName.mockClear() + // A name never reaches past the asserted workspace, even if the lookup returned a foreign row. findByName.mockResolvedValueOnce([{ id: 'table-1', workspaceId: 'workspace-1', name: 'leads' }]) await expect( diff --git a/apps/sim/lib/table/application/context.ts b/apps/sim/lib/table/application/context.ts index d1690f572a2..cbdeccbf7db 100644 --- a/apps/sim/lib/table/application/context.ts +++ b/apps/sim/lib/table/application/context.ts @@ -1,7 +1,7 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import type { TableAuthorizationContext } from '@/lib/table/application/authorization' import { TABLE_NOT_FOUND_MESSAGE } from '@/lib/table/constants' -import { TABLE_ID_PREFIX } from '@/lib/table/ids' +import { isTableIdShaped } from '@/lib/table/ids' import { findActiveTablesByExactName, getTableById } from '@/lib/table/service' import type { TableDefinition } from '@/lib/table/types' import { loadActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' @@ -33,7 +33,7 @@ export async function resolveTableWorkspaceContext( */ async function requireTable(tableId: string, workspaceId: string | undefined) { let table = await getTableById(tableId) - if (!table && workspaceId !== undefined && !tableId.startsWith(TABLE_ID_PREFIX)) { + if (!table && workspaceId !== undefined && !isTableIdShaped(tableId)) { const named = await findActiveTablesByExactName(workspaceId, tableId) if (named.length === 1) table = named[0] } diff --git a/apps/sim/lib/table/ids.ts b/apps/sim/lib/table/ids.ts index c4b035af915..18dcdf43b20 100644 --- a/apps/sim/lib/table/ids.ts +++ b/apps/sim/lib/table/ids.ts @@ -1,16 +1,25 @@ import { generateId } from '@sim/utils/id' -/** What every table id starts with: a reference that does not is no table id. */ -export const TABLE_ID_PREFIX = 'tbl_' +/** What every table id starts with. */ +const TABLE_ID_PREFIX = 'tbl_' + +/** The shape {@link generateTableId} mints: `tbl_` and 32 lowercase hex digits. */ +const TABLE_ID_SHAPE = /^tbl_[0-9a-f]{32}$/ + +/** + * Whether `reference` is shaped like a table id, so it is never read as a table name: a name + * that merely starts with `tbl_` (`tbl_sales`) still is one. + */ +export function isTableIdShaped(reference: string): boolean { + return TABLE_ID_SHAPE.test(reference) +} /** * Whether `reference`, a table route's `{tableId}`, names `table`: its id, or (when not shaped * like an id) its name, which is unique among a workspace's active tables. */ export function referencesTable(reference: string, table: { id: string; name: string }): boolean { - return ( - reference === table.id || (!reference.startsWith(TABLE_ID_PREFIX) && reference === table.name) - ) + return reference === table.id || (!isTableIdShaped(reference) && reference === table.name) } /** From 4c94efafc1a2fe3aa47d97b90c5475917716f450 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:18:49 -0800 Subject: [PATCH 82/85] docs(sim-cli): the workspace loop help names every deletion --allow-delete guards, and the README lists exits 14 and 15 --- packages/sim-cli/README.md | 5 +++-- packages/sim-cli/src/commands/protocol/source-loop-help.ts | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/sim-cli/README.md b/packages/sim-cli/README.md index be28a0b24b9..ae9bc8c691c 100644 --- a/packages/sim-cli/README.md +++ b/packages/sim-cli/README.md @@ -325,8 +325,9 @@ creates and dry runs, are resent up to 6 times first, each wait the longer of `R release both exited 1. Ctrl-C exits 130; a source apply or create already sent is finished and saved into its directory first. The `workflows source` and `workspaces source` commands also use 5 (stale), 6 (a locked workflow or folder; a locked block exits 1), 7 (too large), 8 (a workspace -apply stopped part-way), 10 (busy), 11 (status: local changes) and 12 (status: the server -changed). Command-specific codes: [Exit codes](https://docs.sim.ai/cli/scripting#exit-codes). +apply stopped part-way), 10 (busy), 11 (status: local changes), 12 (status: the server changed), +14 (a write without `--yes` where no terminal can ask: it printed the plan and wrote nothing) and 15 +(a workspace apply wrote part of its plan and held the rest back). Command-specific codes: [Exit codes](https://docs.sim.ai/cli/scripting#exit-codes). ## Workflows and workspaces as code diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index 1c9aaa87c51..5b6e26dcc92 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -52,7 +52,8 @@ ${loopRows([ Promote dev to prod: \`sim workspaces source apply --dir ./ws --to --dry-run\`, then --yes. -Flags the loop needs: --allow-delete (apply: a removed file, column, block or variable is refused -without it), --force (get: replace edits no apply has saved). A workflow deploys on apply when +Flags the loop needs: --allow-delete (apply: removing a resource, a column, rows or a document, +or a workflow's block or variable, is refused without it), --force (get: replace edits no apply +has saved). A workflow deploys on apply when deployments/.ts declares it. ${statusLine('sim workspaces source', './ws')}` From 26daa04c18db485c2786f0b457d01c2bd1b5975e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:24:05 -0800 Subject: [PATCH 83/85] refactor(workflow-code): simplify the round's fixes: explicit blob consumption for every write, one fallback completion shape, a shared cancellation check --- apps/sim/lib/billing/storage/tracking.ts | 29 ++++---- .../sim/lib/logs/execution/logging-session.ts | 71 ++++++++----------- apps/sim/lib/table/ids.ts | 5 +- .../application/apply-workspace-source.ts | 18 ++--- .../application/kinds/files/adapter.ts | 19 +++-- .../application/knowledge.integration.ts | 10 +-- .../application/staging.integration.ts | 25 ++----- .../lib/workspace-source/application/types.ts | 8 +-- .../sim/lib/workspace-source/staging/store.ts | 9 ++- .../src/commands/protocol/deployed-urls.ts | 4 +- .../src/commands/protocol/source-ui.ts | 4 +- .../protocol/workspace-source-apply.ts | 15 ++-- packages/sim-cli/src/http/client.ts | 5 ++ packages/workflow-code/src/compile/blocks.ts | 8 ++- 14 files changed, 109 insertions(+), 121 deletions(-) diff --git a/apps/sim/lib/billing/storage/tracking.ts b/apps/sim/lib/billing/storage/tracking.ts index 38116adfe9f..37f4959f97d 100644 --- a/apps/sim/lib/billing/storage/tracking.ts +++ b/apps/sim/lib/billing/storage/tracking.ts @@ -194,18 +194,18 @@ function getWorkspaceBillingEntity(row: LockedWorkspaceStorage): BillingEntity { : { type: 'user', id: row.billedAccountUserId } } -/** Whether the locked workspace row still routes storage to `context`'s payer. */ -function routesToContextPayer( +/** The payer the locked workspace row routes storage to, when it is still `context`'s; else `null`. */ +function contextPayerOf( row: LockedWorkspaceStorage, context: StorageBillingContext -): boolean { - const currentBillingEntity = getWorkspaceBillingEntity(row) - return ( - row.id === context.workspaceId && - currentBillingEntity.type === context.billingEntity.type && - currentBillingEntity.id === context.billingEntity.id && +): BillingEntity | null { + const current = getWorkspaceBillingEntity(row) + return row.id === context.workspaceId && + current.type === context.billingEntity.type && + current.id === context.billingEntity.id && row.billedAccountUserId === context.billedAccountUserId - ) + ? current + : null } /** @@ -216,12 +216,13 @@ function assertWorkspaceStorageContext( row: LockedWorkspaceStorage, context: StorageBillingContext ): BillingEntity { - if (!routesToContextPayer(row, context)) { + const payer = contextPayerOf(row, context) + if (!payer) { throw new Error( `Storage payer changed for workspace ${context.workspaceId}; resolve a fresh billing context` ) } - return getWorkspaceBillingEntity(row) + return payer } /** @@ -233,10 +234,8 @@ export async function isWorkspaceStoragePayerInTx( tx: DbOrTx, context: StorageBillingContext ): Promise { - return routesToContextPayer( - await lockWorkspaceStorageForMutationInTx(tx, context.workspaceId), - context - ) + const row = await lockWorkspaceStorageForMutationInTx(tx, context.workspaceId) + return contextPayerOf(row, context) !== null } /** diff --git a/apps/sim/lib/logs/execution/logging-session.ts b/apps/sim/lib/logs/execution/logging-session.ts index 73cfeae2f9b..e6721a971a4 100644 --- a/apps/sim/lib/logs/execution/logging-session.ts +++ b/apps/sim/lib/logs/execution/logging-session.ts @@ -194,6 +194,12 @@ export interface SessionPausedParams { executionState?: SerializableExecutionState } +/** What a completion was given that its cost-only fallback carries over. */ +type FallbackCompletion = Pick< + SessionCompleteParams, + 'endedAt' | 'totalDurationMs' | 'traceSpans' | 'workflowInput' | 'executionState' +> + export interface LoggingSessionOptions { /** * Overrides the per-run fixed charge. Pass `0` for a run whose base charge is @@ -1530,16 +1536,11 @@ export class LoggingSession { requestId: this.requestId, error: errorMsg, }) - await this.completeWithCostOnlyLog({ - traceSpans: params.traceSpans, - workflowInput: params.workflowInput, - endedAt: params.endedAt, - totalDurationMs: params.totalDurationMs, + await this.completeWithCostOnlyLog(params, { errorMessage: `Failed to store trace spans: ${errorMsg}`, isError: false, finalizationPath: 'fallback_completed', finalOutput: params.finalOutput || {}, - executionState: params.executionState, }) } } @@ -1560,11 +1561,7 @@ export class LoggingSession { `CompleteWithError failed for execution ${this.executionId}, attempting fallback`, { requestId: this.requestId, error: errorMsg } ) - await this.completeWithCostOnlyLog({ - traceSpans: params?.traceSpans, - workflowInput: params?.workflowInput, - endedAt: params?.endedAt, - totalDurationMs: params?.totalDurationMs, + await this.completeWithCostOnlyLog(params, { errorMessage: params?.error?.message || `Execution failed to store trace spans: ${errorMsg}`, isError: true, @@ -1572,7 +1569,6 @@ export class LoggingSession { finalOutput: { error: params?.error?.message || `Execution failed to store trace spans: ${errorMsg}`, }, - executionState: params?.executionState, status: 'failed', }) } @@ -1595,16 +1591,11 @@ export class LoggingSession { `CompleteWithCancellation failed for execution ${this.executionId}, attempting fallback`, { requestId: this.requestId, error: errorMsg } ) - await this.completeWithCostOnlyLog({ - traceSpans: params?.traceSpans, - workflowInput: params?.workflowInput, - endedAt: params?.endedAt, - totalDurationMs: params?.totalDurationMs, + await this.completeWithCostOnlyLog(params, { errorMessage: 'Run was cancelled', isError: false, finalizationPath: 'cancelled', finalOutput: { cancelled: true }, - executionState: params?.executionState, status: 'cancelled', }) } @@ -1625,16 +1616,11 @@ export class LoggingSession { `CompleteWithPause failed for execution ${this.executionId}, attempting fallback`, { requestId: this.requestId, error: errorMsg } ) - await this.completeWithCostOnlyLog({ - traceSpans: params?.traceSpans, - workflowInput: params?.workflowInput, - endedAt: params?.endedAt, - totalDurationMs: params?.totalDurationMs, + await this.completeWithCostOnlyLog(params, { errorMessage: 'Run paused but failed to store full trace spans', isError: false, finalizationPath: 'paused', finalOutput: { paused: true }, - executionState: params?.executionState, status: 'pending', }) } @@ -1733,18 +1719,21 @@ export class LoggingSession { } } - private async completeWithCostOnlyLog(params: { - traceSpans?: TraceSpan[] - workflowInput?: unknown - endedAt?: string - totalDurationMs?: number - errorMessage: string - isError: boolean - finalizationPath: ExecutionFinalizationPath - finalOutput?: Record - executionState?: SerializableExecutionState - status?: 'completed' | 'failed' | 'cancelled' | 'pending' - }): Promise { + /** + * Completes the run with no trace spans, after the full completion failed: `completion` is + * what that completion was given (its timing, input and state carry over), `params` what the + * fallback records instead. + */ + private async completeWithCostOnlyLog( + completion: FallbackCompletion | undefined, + params: { + errorMessage: string + isError: boolean + finalizationPath: ExecutionFinalizationPath + finalOutput?: Record + status?: 'completed' | 'failed' | 'cancelled' | 'pending' + } + ): Promise { if (this.completed || this.completing) { return } @@ -1761,18 +1750,18 @@ export class LoggingSession { // from the in-memory trace spans when available (this fallback fires when // persisting spans failed, not when computing them did), else just the // base execution charge. - const costSummary = calculateCostSummary(params.traceSpans, this.costOptions) + const costSummary = calculateCostSummary(completion?.traceSpans, this.costOptions) const finalOutput = params.finalOutput || { _fallback: true, error: params.errorMessage } await this.completeExecutionWithFinalization({ - endedAt: params.endedAt || new Date().toISOString(), - totalDurationMs: params.totalDurationMs || 0, + endedAt: completion?.endedAt || new Date().toISOString(), + totalDurationMs: completion?.totalDurationMs || 0, costSummary, finalOutput, traceSpans: [], - workflowInput: params.workflowInput, - executionState: params.executionState, + workflowInput: completion?.workflowInput, + executionState: completion?.executionState, finalizationPath: params.finalizationPath, completionFailure: params.errorMessage, level: params.isError ? 'error' : 'info', diff --git a/apps/sim/lib/table/ids.ts b/apps/sim/lib/table/ids.ts index 18dcdf43b20..bbc23b0bd58 100644 --- a/apps/sim/lib/table/ids.ts +++ b/apps/sim/lib/table/ids.ts @@ -1,10 +1,9 @@ import { generateId } from '@sim/utils/id' -/** What every table id starts with. */ const TABLE_ID_PREFIX = 'tbl_' -/** The shape {@link generateTableId} mints: `tbl_` and 32 lowercase hex digits. */ -const TABLE_ID_SHAPE = /^tbl_[0-9a-f]{32}$/ +/** The shape {@link generateTableId} mints: the prefix and 32 lowercase hex digits. */ +const TABLE_ID_SHAPE = new RegExp(`^${TABLE_ID_PREFIX}[0-9a-f]{32}$`) /** * Whether `reference` is shaped like a table id, so it is never read as a table name: a name diff --git a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts index a4c8687a6d0..497161798a0 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -401,8 +401,8 @@ async function consumeStagedBlobs(target: StagingScope, consumed: StagedBlob[]): /** * Writes the plan's changes in write order under `lease`, recording each into `base` and * `result`; the first failure stops it and is reported as `result.failed`. Each write reads its - * binary files from `staged`; returns the staged blobs the workspace now stores: those of the - * writes that succeeded, and those the failed write reported stored before it failed. + * binary files from `staged`; returns the staged blobs the writes reported stored, the failed + * write's included. */ async function writeAll( changes: PlannedChange[], @@ -419,8 +419,6 @@ async function writeAll( ) const consumed: StagedBlob[] = [] for (const change of writeOrder(changes)) { - const read: StagedBlob[] = [] - const stored: StagedBlob[] = [] const stagedAt = (path: string) => { const blob = staged.get(path) if (!blob) throw new Error('A blob write ran without its staged bytes') @@ -429,20 +427,15 @@ async function writeAll( const writeCtx: ApplyContext = { ...ctx, blobs: { - read(path) { - const blob = stagedAt(path) - read.push(blob) - return readStagedBlob(blob) - }, - stored(path) { - stored.push(stagedAt(path)) + read: (path) => readStagedBlob(stagedAt(path)), + stored: (path) => { + consumed.push(stagedAt(path)) }, }, } try { await lease.confirm() const written = await write(change, writeCtx) - consumed.push(...read) Object.assign(result.files, written.text) for (const diagnostic of written.diagnostics ?? []) { const at = reported.get(findingIdentity(diagnostic)) @@ -466,7 +459,6 @@ async function writeAll( if (written.base) base.resources[address] = written.base else delete base.resources[address] } catch (error) { - consumed.push(...stored) const failure = failureOf(error, change, result.applyId) result.failed = failure.failed result.diagnostics.push(...failure.diagnostics) diff --git a/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts index 8bb9c7ed1cb..ce428f6bd8d 100644 --- a/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts @@ -480,14 +480,21 @@ async function claimFileKey( /** * The bytes a write sends and their SHA-256: read from the staging area, which checks them - * against the declared hash, so the declaration's hash is theirs. + * against the declared hash, so the declaration's hash is theirs. `stored` reports them stored + * once the write lands, so their staged copy stops counting toward the quota. */ async function contentOf( change: FileChange, ctx: ApplyContext -): Promise<{ content: Buffer; sha256: string }> { - if (!change.decl || !ctx.blobs) throw new Error('A file write needs its declaration and bytes') - return { content: await ctx.blobs.read(fileBlobPath(change.key)), sha256: change.decl.sha256 } +): Promise<{ content: Buffer; sha256: string; stored: () => void }> { + const { blobs } = ctx + if (!change.decl || !blobs) throw new Error('A file write needs its declaration and bytes') + const path = fileBlobPath(change.key) + return { + content: await blobs.read(path), + sha256: change.decl.sha256, + stored: () => blobs.stored(path), + } } /** The base entry of a file just written, from what the server recorded. */ @@ -599,7 +606,7 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { .catch(staleAs(change)) return { id: fileId, text: {} } } - const { content, sha256 } = await contentOf(change, ctx) + const { content, sha256, stored } = await contentOf(change, ctx) if (change.action === 'create') { const segments = change.key.split('/') const resourceKey = change.detail?.resourceKey @@ -617,6 +624,7 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { : {}), }, }) + stored() return written(ctx, change.key, created.id, sha256) } const fileId = change.storedId @@ -634,6 +642,7 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { }, }) .catch(staleAs(change)) + stored() return written(ctx, change.key, fileId, sha256) }, diff --git a/apps/sim/lib/workspace-source/application/knowledge.integration.ts b/apps/sim/lib/workspace-source/application/knowledge.integration.ts index 8c3a38c94c5..09eddb6d484 100644 --- a/apps/sim/lib/workspace-source/application/knowledge.integration.ts +++ b/apps/sim/lib/workspace-source/application/knowledge.integration.ts @@ -1098,11 +1098,11 @@ describe('knowledge bases as workspace source', () => { }) .from(workspaceSourceStagedBlob) .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) - const consumed = (path: string) => - staging.find((row) => row.sha256 === sha256Hex(POLICIES.docs[path] ?? Buffer.alloc(0))) - ?.consumedAt ?? null - expect(consumed(REFUNDS)).toBeInstanceOf(Date) - expect(consumed('knowledge/policies/docs/shipping.txt')).toBeNull() + const consumedAt = new Map(staging.map((row) => [row.sha256, row.consumedAt])) + const hashOf = (path: string) => sha256Hex(POLICIES.docs[path] ?? Buffer.alloc(0)) + expect(consumedAt.get(hashOf(REFUNDS))).toBeInstanceOf(Date) + // Still staged, and unconsumed: a missing row reads undefined, never null. + expect(consumedAt.get(hashOf('knowledge/policies/docs/shipping.txt'))).toBeNull() const second = await apply(workspaceId, POLICIES, { base: first.base }) diff --git a/apps/sim/lib/workspace-source/application/staging.integration.ts b/apps/sim/lib/workspace-source/application/staging.integration.ts index 297b1f72c71..fed2e8ae5e6 100644 --- a/apps/sim/lib/workspace-source/application/staging.integration.ts +++ b/apps/sim/lib/workspace-source/application/staging.integration.ts @@ -173,13 +173,14 @@ async function missing( return result.missing } -/** What the staging table holds for the workspace: scope, hash and size per row. */ +/** The workspace's staging rows, read directly. */ async function rows(workspaceId: string) { return db .select({ scope: workspaceSourceStagedBlob.scope, sha256: workspaceSourceStagedBlob.sha256, storageKey: workspaceSourceStagedBlob.storageKey, + consumedAt: workspaceSourceStagedBlob.consumedAt, }) .from(workspaceSourceStagedBlob) .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) @@ -340,16 +341,10 @@ describe('workspace source staging', () => { const restaged = { sha256: sha256Hex(notes), size: notes.byteLength, content: notes } const refused = await failure(stage(applier, workspaceId, [restaged])) expect(refused).toMatchObject({ name: 'SourceStagingFullError' }) - const consumedNotes = await db - .select({ consumedAt: workspaceSourceStagedBlob.consumedAt }) - .from(workspaceSourceStagedBlob) - .where( - and( - eq(workspaceSourceStagedBlob.workspaceId, workspaceId), - eq(workspaceSourceStagedBlob.sha256, restaged.sha256) - ) - ) - expect(consumedNotes).toEqual([{ consumedAt: expect.any(Date) }]) + const [consumedNotes] = (await rows(workspaceId)).filter( + (row) => row.sha256 === restaged.sha256 + ) + expect(consumedNotes.consumedAt).toBeInstanceOf(Date) // Renewing a blob that still counts adds nothing, so it fits with 2 bytes left. expect((await stage(applier, workspaceId, [six])).staged).toEqual([ @@ -475,13 +470,7 @@ describe('workspace source staging', () => { { sha256: a.sha256, size: a.size, storageKey: read.storageKey }, ]) - const held = await db - .select({ - storageKey: workspaceSourceStagedBlob.storageKey, - consumedAt: workspaceSourceStagedBlob.consumedAt, - }) - .from(workspaceSourceStagedBlob) - .where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId)) + const held = await rows(workspaceId) expect(held).toHaveLength(1) expect(held[0].storageKey).not.toBe(read.storageKey) expect(held[0].consumedAt).toBeNull() diff --git a/apps/sim/lib/workspace-source/application/types.ts b/apps/sim/lib/workspace-source/application/types.ts index d990b892f58..84e189e1f88 100644 --- a/apps/sim/lib/workspace-source/application/types.ts +++ b/apps/sim/lib/workspace-source/application/types.ts @@ -81,10 +81,10 @@ export interface ApplyContext extends SourceContext { writtenDrafts: Map /** * Reads the staged bytes of a blob a write needs, by directory path, checked against its - * SHA-256. Loaded one blob at a time, so a write never holds more than it is writing. The blobs - * a write read are consumed (stop counting toward the payer's quota) once it succeeds; a write - * that stores several one at a time calls `stored` after each, so one that fails partway still - * consumes those the workspace now holds. + * SHA-256. Loaded one blob at a time, so a write never holds more than it is writing. A write + * calls `stored` once the workspace holds a blob's bytes, which consumes its staged copy (it + * stops counting toward the payer's quota), so a write that fails partway still consumes those + * it stored. */ blobs?: { read(path: string): Promise; stored(path: string): void } } diff --git a/apps/sim/lib/workspace-source/staging/store.ts b/apps/sim/lib/workspace-source/staging/store.ts index abae0550c8e..cd4d8adf183 100644 --- a/apps/sim/lib/workspace-source/staging/store.ts +++ b/apps/sim/lib/workspace-source/staging/store.ts @@ -59,6 +59,9 @@ export interface StagedBlob { storageKey: string } +/** A staged blob as staging reads it: `consumed` once an apply wrote it into the workspace. */ +type HeldBlob = StagedBlob & { consumed: boolean } + /** The workspace and caller a staged blob belongs to. */ export interface StagingScope { workspaceId: string @@ -89,8 +92,8 @@ export async function findStagedBlobs( target: StagingScope, hashes: readonly string[], until: Date = new Date() -): Promise> { - const found = new Map() +): Promise> { + const found = new Map() if (hashes.length === 0) return found const rows = await db .select({ @@ -304,7 +307,7 @@ export async function stageBlobs( count: fresh.length, bytes: fresh.reduce((sum, blob) => sum + blob.bytes.byteLength, 0), } - if (fresh.length > 0) assertStagingFits(await stagedUsage(target, tx), adding) + assertStagingFits(await stagedUsage(target, tx), adding) if (billing) await assertStagingWithinQuota(tx, billing, adding.bytes) if (fresh.length === 0) return new Map() const hashes = fresh.map((blob) => blob.sha256) diff --git a/packages/sim-cli/src/commands/protocol/deployed-urls.ts b/packages/sim-cli/src/commands/protocol/deployed-urls.ts index 7e53c87dbda..d96e283ae3b 100644 --- a/packages/sim-cli/src/commands/protocol/deployed-urls.ts +++ b/packages/sim-cli/src/commands/protocol/deployed-urls.ts @@ -7,7 +7,7 @@ import { parseWorkflowLock } from '@sim/workflow-code' import { printError } from '#sim-cli/output/io' import { sanitize } from '#sim-cli/output/render' import type { GetWorkflowDeploymentResponse } from '../../generated/v2-api' -import { REQUEST_CANCELLED, SimApiError } from '../../http/client' +import { isRequestCancelled } from '../../http/client' import type { OperationClient } from '../../runtime/called-operations' /** A webhook of a deployed workflow, which callers reach at `url`. */ @@ -63,7 +63,7 @@ export async function deployedUrls( }) return namedUrls(data.webhooks, names) } catch (error) { - if (error instanceof SimApiError && error.code === REQUEST_CANCELLED) throw error + if (isRequestCancelled(error)) throw error printError( `The deploy succeeded, but its webhook URLs could not be read (${sanitize(getErrorMessage(error))}): \`sim workflows deployment status ${sanitize(workflowId)}\` lists them.` ) diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index bdfc04686ee..704d946fde7 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -24,7 +24,7 @@ import type { ApplyWorkflowSourceResponse, ApplyWorkspaceSourceResponse, } from '../../generated/v2-api' -import { noAnswer, REQUEST_CANCELLED, SimApiError } from '../../http/client' +import { isRequestCancelled, noAnswer, SimApiError } from '../../http/client' import { LocalRefusal } from './local-errors' /** One finding of a source write, as the workflow and workspace answers both carry it. */ @@ -339,7 +339,7 @@ const LOST_ANSWER_STATUSES = new Set([502, 504]) */ function answerLost(error: SimApiError): boolean { if (error instanceof LocalRefusal) return false - return noAnswer(error, LOST_ANSWER_STATUSES) || error.code === REQUEST_CANCELLED + return noAnswer(error, LOST_ANSWER_STATUSES) || isRequestCancelled(error) } /** diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 88f66bb0e8d..8eae6de1398 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -919,13 +919,13 @@ export function attachWorkspaceSourceApply(source: Command): void { printError(`Stopped at ${data.failed.kind} ${data.failed.key}: ${data.failed.message}`) setSoftExitCode(failedExitCode(data.failed)) } - // A promotion's directory holds the source workspace's locks, whose ids the target's - // blocks do not have. report( data, undefined, - await deploymentUrls(client, data, async (path) => - promotion ? null : readSourceText(options.dir, path) + await deploymentUrls( + client, + data, + promotion ? undefined : (path) => readSourceText(options.dir, path) ) ) }, @@ -1008,12 +1008,13 @@ function workflowUrlsText(urls: readonly WorkflowUrl[]): string { * The webhook URLs of each workflow a written apply deployed (a `deployments/.ts` it created * or updated), in the workspace it wrote: a promotion's are the target's, which are new URLs. * Each block is named as the workflow's reprinted lock names it, or, when the apply did not - * reprint the workflow (it wrote only the deployment), as `savedLock` reads it from the directory. + * reprint the workflow (it wrote only the deployment), as `savedLock` reads it from the directory + * (none for a promotion, whose directory holds the source workspace's block ids). */ async function deploymentUrls( client: OperationClient<'getWorkflowDeployment'>, data: ApplyData, - savedLock: (path: string) => Promise + savedLock?: (path: string) => Promise ): Promise { if (data.dryRun) return [] const base = parseWorkspaceBase(data.base).base @@ -1025,7 +1026,7 @@ async function deploymentUrls( const workflowId = base?.resources[resourceAddress('workflow', key)]?.id if (!workflowId) return [] const lockPath = `${workflowFolder(key)}/${SOURCE_LOCK_FILE}` - const lock = data.files[lockPath] ?? (await savedLock(lockPath)) + const lock = data.files[lockPath] ?? (await savedLock?.(lockPath)) ?? null const named = await deployedUrls(client, workflowId, lockBlockNames(lock)) return named.map((url) => ({ workflow: key, ...url })) }) diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts index 76633701c6f..3cb33e05e08 100644 --- a/packages/sim-cli/src/http/client.ts +++ b/packages/sim-cli/src/http/client.ts @@ -33,6 +33,11 @@ export class SimApiError extends Error { /** The code of a request the caller cancelled (its signal aborted): not an unreachable server. */ export const REQUEST_CANCELLED = 'REQUEST_CANCELLED' +/** Whether `error` is a request its caller cancelled, which no best-effort read may swallow. */ +export function isRequestCancelled(error: unknown): boolean { + return error instanceof SimApiError && error.code === REQUEST_CANCELLED +} + /** * Whether a request got no answer from the server: no connection or a timeout (status 0 with no * code, so never a cancellation), or one of the gateway `statuses` the caller treats as a gateway diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 2ddecfc7cf7..0404245d32f 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -1141,9 +1141,11 @@ function compileWrittenParams( hint: alias ? `Write it as ${alias}; the value kind picks the basic or advanced field.` : (BLOCK_META_KEYS as readonly string[]).includes(key) - ? builder.kind === 'generic' - ? `${key} is block meta, not a param: pass it in block()'s fourth argument, block('type', 'Name', {…}, { ${key}: … }).` - : `${key} is block meta, not a param: pass it in the builder's third argument, ('Name', {…}, { ${key}: … }).` + ? `${key} is block meta, not a param: pass it in ${ + builder.kind === 'generic' + ? `block()'s fourth argument, block('type', 'Name', {…}, { ${key}: … }).` + : `the builder's third argument, ('Name', {…}, { ${key}: … }).` + }` : didYouMean(key, index.fields.keys()), blockKey: decl.key, param: key, From 5db10cc9406c4e476a1ee1c912d0ad7877d916dc Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:39:03 -0800 Subject: [PATCH 84/85] test(logs): type the restored block state in the input-stage failure test --- apps/sim/lib/workflows/executor/execution-core.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/workflows/executor/execution-core.test.ts b/apps/sim/lib/workflows/executor/execution-core.test.ts index 99d506c9817..5a851be9493 100644 --- a/apps/sim/lib/workflows/executor/execution-core.test.ts +++ b/apps/sim/lib/workflows/executor/execution-core.test.ts @@ -1099,7 +1099,13 @@ describe('executeWorkflowCore terminal finalization sequencing', () => { it('logs the redacted input of a run that fails after its input stage, before it runs', async () => { const state = createRestoredState(createManifest()) - state.blockStates = { previous: { output: { result: 'restored alice@example.com' } } } + state.blockStates = { + previous: { + output: { result: 'restored alice@example.com' }, + executed: true, + executionTime: 0, + }, + } maskBatchMock .mockImplementationOnce(async (texts: string[]) => ({ masked: texts.map((text) => text.replaceAll('alice@example.com', '')), From b35d94beb0ba8cd528e57f6a073a6d00fe57e526 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 21 Nov 2026 06:55:35 -0800 Subject: [PATCH 85/85] docs(sim-cli): the group help's create example names the workspace the starter records --- packages/sim-cli/src/commands/protocol/source-loop-help.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index 5b6e26dcc92..c3eb53fd988 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -30,8 +30,9 @@ ${loopRows([ ['sim workflows source apply --dir ./wf --dry-run', 'the plan; nothing is written'], ['sim workflows source apply --dir ./wf --yes', 'save the draft'], ])} -A new workflow: \`sim workflows source create --dir ./new\` writes a starter; edit and check it, -then \`create --dir ./new --yes\` creates the workflow, and the loop above goes on from there. +A new workflow: \`sim workflows source create --dir ./new --workspace \` writes a +starter that records its workspace; edit and check it, then \`create --dir ./new --yes\` creates the +workflow there, and the loop above goes on from there. Flags the loop needs: --allow-delete (apply: an edit that removes a block or variable is refused without it), --deploy (apply, create: also deploy the saved draft), --force (get: replace another